1/*
2 * "git fetch"
3 */
4#include "cache.h"
5#include "refs.h"
6#include "commit.h"
7#include "builtin.h"
8#include "string-list.h"
9#include "remote.h"
10#include "transport.h"
11#include "run-command.h"
12#include "parse-options.h"
13#include "sigchain.h"
14#include "transport.h"
15#include "submodule.h"
16#include "connected.h"
17#include "argv-array.h"
18
19static const char * const builtin_fetch_usage[] = {
20 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
21 N_("git fetch [<options>] <group>"),
22 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
23 N_("git fetch --all [<options>]"),
24 NULL
25};
26
27enum {
28 TAGS_UNSET = 0,
29 TAGS_DEFAULT = 1,
30 TAGS_SET = 2
31};
32
33static int all, append, dry_run, force, keep, multiple, prune, update_head_ok, verbosity;
34static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
35static int tags = TAGS_DEFAULT, unshallow;
36static const char *depth;
37static const char *upload_pack;
38static struct strbuf default_rla = STRBUF_INIT;
39static struct transport *transport;
40static const char *submodule_prefix = "";
41static const char *recurse_submodules_default;
42
43static int option_parse_recurse_submodules(const struct option *opt,
44 const char *arg, int unset)
45{
46 if (unset) {
47 recurse_submodules = RECURSE_SUBMODULES_OFF;
48 } else {
49 if (arg)
50 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
51 else
52 recurse_submodules = RECURSE_SUBMODULES_ON;
53 }
54 return 0;
55}
56
57static struct option builtin_fetch_options[] = {
58 OPT__VERBOSITY(&verbosity),
59 OPT_BOOLEAN(0, "all", &all,
60 N_("fetch from all remotes")),
61 OPT_BOOLEAN('a', "append", &append,
62 N_("append to .git/FETCH_HEAD instead of overwriting")),
63 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
64 N_("path to upload pack on remote end")),
65 OPT__FORCE(&force, N_("force overwrite of local branch")),
66 OPT_BOOLEAN('m', "multiple", &multiple,
67 N_("fetch from multiple remotes")),
68 OPT_SET_INT('t', "tags", &tags,
69 N_("fetch all tags and associated objects"), TAGS_SET),
70 OPT_SET_INT('n', NULL, &tags,
71 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
72 OPT_BOOLEAN('p', "prune", &prune,
73 N_("prune remote-tracking branches no longer on remote")),
74 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
75 N_("control recursive fetching of submodules"),
76 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
77 OPT_BOOLEAN(0, "dry-run", &dry_run,
78 N_("dry run")),
79 OPT_BOOLEAN('k', "keep", &keep, N_("keep downloaded pack")),
80 OPT_BOOLEAN('u', "update-head-ok", &update_head_ok,
81 N_("allow updating of HEAD ref")),
82 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
83 OPT_STRING(0, "depth", &depth, N_("depth"),
84 N_("deepen history of shallow clone")),
85 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
86 N_("convert to a complete repository"),
87 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
88 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
89 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
90 { OPTION_STRING, 0, "recurse-submodules-default",
91 &recurse_submodules_default, NULL,
92 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
93 OPT_END()
94};
95
96static void unlock_pack(void)
97{
98 if (transport)
99 transport_unlock_pack(transport);
100}
101
102static void unlock_pack_on_signal(int signo)
103{
104 unlock_pack();
105 sigchain_pop(signo);
106 raise(signo);
107}
108
109static void add_merge_config(struct ref **head,
110 const struct ref *remote_refs,
111 struct branch *branch,
112 struct ref ***tail)
113{
114 int i;
115
116 for (i = 0; i < branch->merge_nr; i++) {
117 struct ref *rm, **old_tail = *tail;
118 struct refspec refspec;
119
120 for (rm = *head; rm; rm = rm->next) {
121 if (branch_merge_matches(branch, i, rm->name)) {
122 rm->fetch_head_status = FETCH_HEAD_MERGE;
123 break;
124 }
125 }
126 if (rm)
127 continue;
128
129 /*
130 * Not fetched to a remote-tracking branch? We need to fetch
131 * it anyway to allow this branch's "branch.$name.merge"
132 * to be honored by 'git pull', but we do not have to
133 * fail if branch.$name.merge is misconfigured to point
134 * at a nonexisting branch. If we were indeed called by
135 * 'git pull', it will notice the misconfiguration because
136 * there is no entry in the resulting FETCH_HEAD marked
137 * for merging.
138 */
139 memset(&refspec, 0, sizeof(refspec));
140 refspec.src = branch->merge[i]->src;
141 get_fetch_map(remote_refs, &refspec, tail, 1);
142 for (rm = *old_tail; rm; rm = rm->next)
143 rm->fetch_head_status = FETCH_HEAD_MERGE;
144 }
145}
146
147static void find_non_local_tags(struct transport *transport,
148 struct ref **head,
149 struct ref ***tail);
150
151static struct ref *get_ref_map(struct transport *transport,
152 struct refspec *refs, int ref_count, int tags,
153 int *autotags)
154{
155 int i;
156 struct ref *rm;
157 struct ref *ref_map = NULL;
158 struct ref **tail = &ref_map;
159
160 const struct ref *remote_refs = transport_get_remote_refs(transport);
161
162 if (ref_count || tags == TAGS_SET) {
163 struct ref **old_tail;
164
165 for (i = 0; i < ref_count; i++) {
166 get_fetch_map(remote_refs, &refs[i], &tail, 0);
167 if (refs[i].dst && refs[i].dst[0])
168 *autotags = 1;
169 }
170 /* Merge everything on the command line, but not --tags */
171 for (rm = ref_map; rm; rm = rm->next)
172 rm->fetch_head_status = FETCH_HEAD_MERGE;
173 if (tags == TAGS_SET)
174 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
175
176 /*
177 * For any refs that we happen to be fetching via command-line
178 * arguments, take the opportunity to update their configured
179 * counterparts. However, we do not want to mention these
180 * entries in FETCH_HEAD at all, as they would simply be
181 * duplicates of existing entries.
182 */
183 old_tail = tail;
184 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
185 get_fetch_map(ref_map, &transport->remote->fetch[i],
186 &tail, 1);
187 for (rm = *old_tail; rm; rm = rm->next)
188 rm->fetch_head_status = FETCH_HEAD_IGNORE;
189 } else {
190 /* Use the defaults */
191 struct remote *remote = transport->remote;
192 struct branch *branch = branch_get(NULL);
193 int has_merge = branch_has_merge_config(branch);
194 if (remote &&
195 (remote->fetch_refspec_nr ||
196 /* Note: has_merge implies non-NULL branch->remote_name */
197 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
198 for (i = 0; i < remote->fetch_refspec_nr; i++) {
199 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
200 if (remote->fetch[i].dst &&
201 remote->fetch[i].dst[0])
202 *autotags = 1;
203 if (!i && !has_merge && ref_map &&
204 !remote->fetch[0].pattern)
205 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
206 }
207 /*
208 * if the remote we're fetching from is the same
209 * as given in branch.<name>.remote, we add the
210 * ref given in branch.<name>.merge, too.
211 *
212 * Note: has_merge implies non-NULL branch->remote_name
213 */
214 if (has_merge &&
215 !strcmp(branch->remote_name, remote->name))
216 add_merge_config(&ref_map, remote_refs, branch, &tail);
217 } else {
218 ref_map = get_remote_ref(remote_refs, "HEAD");
219 if (!ref_map)
220 die(_("Couldn't find remote ref HEAD"));
221 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
222 tail = &ref_map->next;
223 }
224 }
225 if (tags == TAGS_DEFAULT && *autotags)
226 find_non_local_tags(transport, &ref_map, &tail);
227 ref_remove_duplicates(ref_map);
228
229 return ref_map;
230}
231
232#define STORE_REF_ERROR_OTHER 1
233#define STORE_REF_ERROR_DF_CONFLICT 2
234
235static int s_update_ref(const char *action,
236 struct ref *ref,
237 int check_old)
238{
239 char msg[1024];
240 char *rla = getenv("GIT_REFLOG_ACTION");
241 static struct ref_lock *lock;
242
243 if (dry_run)
244 return 0;
245 if (!rla)
246 rla = default_rla.buf;
247 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
248 lock = lock_any_ref_for_update(ref->name,
249 check_old ? ref->old_sha1 : NULL,
250 0, NULL);
251 if (!lock)
252 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
253 STORE_REF_ERROR_OTHER;
254 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
255 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
256 STORE_REF_ERROR_OTHER;
257 return 0;
258}
259
260#define REFCOL_WIDTH 10
261
262static int update_local_ref(struct ref *ref,
263 const char *remote,
264 const struct ref *remote_ref,
265 struct strbuf *display)
266{
267 struct commit *current = NULL, *updated;
268 enum object_type type;
269 struct branch *current_branch = branch_get(NULL);
270 const char *pretty_ref = prettify_refname(ref->name);
271
272 type = sha1_object_info(ref->new_sha1, NULL);
273 if (type < 0)
274 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
275
276 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
277 if (verbosity > 0)
278 strbuf_addf(display, "= %-*s %-*s -> %s",
279 TRANSPORT_SUMMARY(_("[up to date]")),
280 REFCOL_WIDTH, remote, pretty_ref);
281 return 0;
282 }
283
284 if (current_branch &&
285 !strcmp(ref->name, current_branch->name) &&
286 !(update_head_ok || is_bare_repository()) &&
287 !is_null_sha1(ref->old_sha1)) {
288 /*
289 * If this is the head, and it's not okay to update
290 * the head, and the old value of the head isn't empty...
291 */
292 strbuf_addf(display,
293 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
294 TRANSPORT_SUMMARY(_("[rejected]")),
295 REFCOL_WIDTH, remote, pretty_ref);
296 return 1;
297 }
298
299 if (!is_null_sha1(ref->old_sha1) &&
300 !prefixcmp(ref->name, "refs/tags/")) {
301 int r;
302 r = s_update_ref("updating tag", ref, 0);
303 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
304 r ? '!' : '-',
305 TRANSPORT_SUMMARY(_("[tag update]")),
306 REFCOL_WIDTH, remote, pretty_ref,
307 r ? _(" (unable to update local ref)") : "");
308 return r;
309 }
310
311 current = lookup_commit_reference_gently(ref->old_sha1, 1);
312 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
313 if (!current || !updated) {
314 const char *msg;
315 const char *what;
316 int r;
317 /*
318 * Nicely describe the new ref we're fetching.
319 * Base this on the remote's ref name, as it's
320 * more likely to follow a standard layout.
321 */
322 const char *name = remote_ref ? remote_ref->name : "";
323 if (!prefixcmp(name, "refs/tags/")) {
324 msg = "storing tag";
325 what = _("[new tag]");
326 } else if (!prefixcmp(name, "refs/heads/")) {
327 msg = "storing head";
328 what = _("[new branch]");
329 } else {
330 msg = "storing ref";
331 what = _("[new ref]");
332 }
333
334 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
335 (recurse_submodules != RECURSE_SUBMODULES_ON))
336 check_for_new_submodule_commits(ref->new_sha1);
337 r = s_update_ref(msg, ref, 0);
338 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
339 r ? '!' : '*',
340 TRANSPORT_SUMMARY(what),
341 REFCOL_WIDTH, remote, pretty_ref,
342 r ? _(" (unable to update local ref)") : "");
343 return r;
344 }
345
346 if (in_merge_bases(current, updated)) {
347 char quickref[83];
348 int r;
349 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
350 strcat(quickref, "..");
351 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
352 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
353 (recurse_submodules != RECURSE_SUBMODULES_ON))
354 check_for_new_submodule_commits(ref->new_sha1);
355 r = s_update_ref("fast-forward", ref, 1);
356 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
357 r ? '!' : ' ',
358 TRANSPORT_SUMMARY_WIDTH, quickref,
359 REFCOL_WIDTH, remote, pretty_ref,
360 r ? _(" (unable to update local ref)") : "");
361 return r;
362 } else if (force || ref->force) {
363 char quickref[84];
364 int r;
365 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
366 strcat(quickref, "...");
367 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
368 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
369 (recurse_submodules != RECURSE_SUBMODULES_ON))
370 check_for_new_submodule_commits(ref->new_sha1);
371 r = s_update_ref("forced-update", ref, 1);
372 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
373 r ? '!' : '+',
374 TRANSPORT_SUMMARY_WIDTH, quickref,
375 REFCOL_WIDTH, remote, pretty_ref,
376 r ? _("unable to update local ref") : _("forced update"));
377 return r;
378 } else {
379 strbuf_addf(display, "! %-*s %-*s -> %s %s",
380 TRANSPORT_SUMMARY(_("[rejected]")),
381 REFCOL_WIDTH, remote, pretty_ref,
382 _("(non-fast-forward)"));
383 return 1;
384 }
385}
386
387static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
388{
389 struct ref **rm = cb_data;
390 struct ref *ref = *rm;
391
392 if (!ref)
393 return -1; /* end of the list */
394 *rm = ref->next;
395 hashcpy(sha1, ref->old_sha1);
396 return 0;
397}
398
399static int store_updated_refs(const char *raw_url, const char *remote_name,
400 struct ref *ref_map)
401{
402 FILE *fp;
403 struct commit *commit;
404 int url_len, i, shown_url = 0, rc = 0;
405 struct strbuf note = STRBUF_INIT;
406 const char *what, *kind;
407 struct ref *rm;
408 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
409 int want_status;
410
411 fp = fopen(filename, "a");
412 if (!fp)
413 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
414
415 if (raw_url)
416 url = transport_anonymize_url(raw_url);
417 else
418 url = xstrdup("foreign");
419
420 rm = ref_map;
421 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
422 rc = error(_("%s did not send all necessary objects\n"), url);
423 goto abort;
424 }
425
426 /*
427 * We do a pass for each fetch_head_status type in their enum order, so
428 * merged entries are written before not-for-merge. That lets readers
429 * use FETCH_HEAD as a refname to refer to the ref to be merged.
430 */
431 for (want_status = FETCH_HEAD_MERGE;
432 want_status <= FETCH_HEAD_IGNORE;
433 want_status++) {
434 for (rm = ref_map; rm; rm = rm->next) {
435 struct ref *ref = NULL;
436 const char *merge_status_marker = "";
437
438 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
439 if (!commit)
440 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
441
442 if (rm->fetch_head_status != want_status)
443 continue;
444
445 if (rm->peer_ref) {
446 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
447 strcpy(ref->name, rm->peer_ref->name);
448 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
449 hashcpy(ref->new_sha1, rm->old_sha1);
450 ref->force = rm->peer_ref->force;
451 }
452
453
454 if (!strcmp(rm->name, "HEAD")) {
455 kind = "";
456 what = "";
457 }
458 else if (!prefixcmp(rm->name, "refs/heads/")) {
459 kind = "branch";
460 what = rm->name + 11;
461 }
462 else if (!prefixcmp(rm->name, "refs/tags/")) {
463 kind = "tag";
464 what = rm->name + 10;
465 }
466 else if (!prefixcmp(rm->name, "refs/remotes/")) {
467 kind = "remote-tracking branch";
468 what = rm->name + 13;
469 }
470 else {
471 kind = "";
472 what = rm->name;
473 }
474
475 url_len = strlen(url);
476 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
477 ;
478 url_len = i + 1;
479 if (4 < i && !strncmp(".git", url + i - 3, 4))
480 url_len = i - 3;
481
482 strbuf_reset(¬e);
483 if (*what) {
484 if (*kind)
485 strbuf_addf(¬e, "%s ", kind);
486 strbuf_addf(¬e, "'%s' of ", what);
487 }
488 switch (rm->fetch_head_status) {
489 case FETCH_HEAD_NOT_FOR_MERGE:
490 merge_status_marker = "not-for-merge";
491 /* fall-through */
492 case FETCH_HEAD_MERGE:
493 fprintf(fp, "%s\t%s\t%s",
494 sha1_to_hex(rm->old_sha1),
495 merge_status_marker,
496 note.buf);
497 for (i = 0; i < url_len; ++i)
498 if ('\n' == url[i])
499 fputs("\\n", fp);
500 else
501 fputc(url[i], fp);
502 fputc('\n', fp);
503 break;
504 default:
505 /* do not write anything to FETCH_HEAD */
506 break;
507 }
508
509 strbuf_reset(¬e);
510 if (ref) {
511 rc |= update_local_ref(ref, what, rm, ¬e);
512 free(ref);
513 } else
514 strbuf_addf(¬e, "* %-*s %-*s -> FETCH_HEAD",
515 TRANSPORT_SUMMARY_WIDTH,
516 *kind ? kind : "branch",
517 REFCOL_WIDTH,
518 *what ? what : "HEAD");
519 if (note.len) {
520 if (verbosity >= 0 && !shown_url) {
521 fprintf(stderr, _("From %.*s\n"),
522 url_len, url);
523 shown_url = 1;
524 }
525 if (verbosity >= 0)
526 fprintf(stderr, " %s\n", note.buf);
527 }
528 }
529 }
530
531 if (rc & STORE_REF_ERROR_DF_CONFLICT)
532 error(_("some local refs could not be updated; try running\n"
533 " 'git remote prune %s' to remove any old, conflicting "
534 "branches"), remote_name);
535
536 abort:
537 strbuf_release(¬e);
538 free(url);
539 fclose(fp);
540 return rc;
541}
542
543/*
544 * We would want to bypass the object transfer altogether if
545 * everything we are going to fetch already exists and is connected
546 * locally.
547 */
548static int quickfetch(struct ref *ref_map)
549{
550 struct ref *rm = ref_map;
551
552 /*
553 * If we are deepening a shallow clone we already have these
554 * objects reachable. Running rev-list here will return with
555 * a good (0) exit status and we'll bypass the fetch that we
556 * really need to perform. Claiming failure now will ensure
557 * we perform the network exchange to deepen our history.
558 */
559 if (depth)
560 return -1;
561 return check_everything_connected(iterate_ref_map, 1, &rm);
562}
563
564static int fetch_refs(struct transport *transport, struct ref *ref_map)
565{
566 int ret = quickfetch(ref_map);
567 if (ret)
568 ret = transport_fetch_refs(transport, ref_map);
569 if (!ret)
570 ret |= store_updated_refs(transport->url,
571 transport->remote->name,
572 ref_map);
573 transport_unlock_pack(transport);
574 return ret;
575}
576
577static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
578{
579 int result = 0;
580 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
581 const char *dangling_msg = dry_run
582 ? _(" (%s will become dangling)")
583 : _(" (%s has become dangling)");
584
585 for (ref = stale_refs; ref; ref = ref->next) {
586 if (!dry_run)
587 result |= delete_ref(ref->name, NULL, 0);
588 if (verbosity >= 0) {
589 fprintf(stderr, " x %-*s %-*s -> %s\n",
590 TRANSPORT_SUMMARY(_("[deleted]")),
591 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
592 warn_dangling_symref(stderr, dangling_msg, ref->name);
593 }
594 }
595 free_refs(stale_refs);
596 return result;
597}
598
599static int add_existing(const char *refname, const unsigned char *sha1,
600 int flag, void *cbdata)
601{
602 struct string_list *list = (struct string_list *)cbdata;
603 struct string_list_item *item = string_list_insert(list, refname);
604 item->util = xmalloc(20);
605 hashcpy(item->util, sha1);
606 return 0;
607}
608
609static int will_fetch(struct ref **head, const unsigned char *sha1)
610{
611 struct ref *rm = *head;
612 while (rm) {
613 if (!hashcmp(rm->old_sha1, sha1))
614 return 1;
615 rm = rm->next;
616 }
617 return 0;
618}
619
620static void find_non_local_tags(struct transport *transport,
621 struct ref **head,
622 struct ref ***tail)
623{
624 struct string_list existing_refs = STRING_LIST_INIT_DUP;
625 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
626 const struct ref *ref;
627 struct string_list_item *item = NULL;
628
629 for_each_ref(add_existing, &existing_refs);
630 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
631 if (prefixcmp(ref->name, "refs/tags/"))
632 continue;
633
634 /*
635 * The peeled ref always follows the matching base
636 * ref, so if we see a peeled ref that we don't want
637 * to fetch then we can mark the ref entry in the list
638 * as one to ignore by setting util to NULL.
639 */
640 if (!suffixcmp(ref->name, "^{}")) {
641 if (item && !has_sha1_file(ref->old_sha1) &&
642 !will_fetch(head, ref->old_sha1) &&
643 !has_sha1_file(item->util) &&
644 !will_fetch(head, item->util))
645 item->util = NULL;
646 item = NULL;
647 continue;
648 }
649
650 /*
651 * If item is non-NULL here, then we previously saw a
652 * ref not followed by a peeled reference, so we need
653 * to check if it is a lightweight tag that we want to
654 * fetch.
655 */
656 if (item && !has_sha1_file(item->util) &&
657 !will_fetch(head, item->util))
658 item->util = NULL;
659
660 item = NULL;
661
662 /* skip duplicates and refs that we already have */
663 if (string_list_has_string(&remote_refs, ref->name) ||
664 string_list_has_string(&existing_refs, ref->name))
665 continue;
666
667 item = string_list_insert(&remote_refs, ref->name);
668 item->util = (void *)ref->old_sha1;
669 }
670 string_list_clear(&existing_refs, 1);
671
672 /*
673 * We may have a final lightweight tag that needs to be
674 * checked to see if it needs fetching.
675 */
676 if (item && !has_sha1_file(item->util) &&
677 !will_fetch(head, item->util))
678 item->util = NULL;
679
680 /*
681 * For all the tags in the remote_refs string list,
682 * add them to the list of refs to be fetched
683 */
684 for_each_string_list_item(item, &remote_refs) {
685 /* Unless we have already decided to ignore this item... */
686 if (item->util)
687 {
688 struct ref *rm = alloc_ref(item->string);
689 rm->peer_ref = alloc_ref(item->string);
690 hashcpy(rm->old_sha1, item->util);
691 **tail = rm;
692 *tail = &rm->next;
693 }
694 }
695
696 string_list_clear(&remote_refs, 0);
697}
698
699static void check_not_current_branch(struct ref *ref_map)
700{
701 struct branch *current_branch = branch_get(NULL);
702
703 if (is_bare_repository() || !current_branch)
704 return;
705
706 for (; ref_map; ref_map = ref_map->next)
707 if (ref_map->peer_ref && !strcmp(current_branch->refname,
708 ref_map->peer_ref->name))
709 die(_("Refusing to fetch into current branch %s "
710 "of non-bare repository"), current_branch->refname);
711}
712
713static int truncate_fetch_head(void)
714{
715 char *filename = git_path("FETCH_HEAD");
716 FILE *fp = fopen(filename, "w");
717
718 if (!fp)
719 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
720 fclose(fp);
721 return 0;
722}
723
724static int do_fetch(struct transport *transport,
725 struct refspec *refs, int ref_count)
726{
727 struct string_list existing_refs = STRING_LIST_INIT_DUP;
728 struct ref *ref_map;
729 struct ref *rm;
730 int autotags = (transport->remote->fetch_tags == 1);
731 int retcode = 0;
732
733 for_each_ref(add_existing, &existing_refs);
734
735 if (tags == TAGS_DEFAULT) {
736 if (transport->remote->fetch_tags == 2)
737 tags = TAGS_SET;
738 if (transport->remote->fetch_tags == -1)
739 tags = TAGS_UNSET;
740 }
741
742 if (!transport->get_refs_list || !transport->fetch)
743 die(_("Don't know how to fetch from %s"), transport->url);
744
745 /* if not appending, truncate FETCH_HEAD */
746 if (!append && !dry_run) {
747 retcode = truncate_fetch_head();
748 if (retcode)
749 goto cleanup;
750 }
751
752 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
753 if (!update_head_ok)
754 check_not_current_branch(ref_map);
755
756 for (rm = ref_map; rm; rm = rm->next) {
757 if (rm->peer_ref) {
758 struct string_list_item *peer_item =
759 string_list_lookup(&existing_refs,
760 rm->peer_ref->name);
761 if (peer_item)
762 hashcpy(rm->peer_ref->old_sha1,
763 peer_item->util);
764 }
765 }
766
767 if (tags == TAGS_DEFAULT && autotags)
768 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
769 if (fetch_refs(transport, ref_map)) {
770 free_refs(ref_map);
771 retcode = 1;
772 goto cleanup;
773 }
774 if (prune) {
775 /* If --tags was specified, pretend the user gave us the canonical tags refspec */
776 if (tags == TAGS_SET) {
777 const char *tags_str = "refs/tags/*:refs/tags/*";
778 struct refspec *tags_refspec, *refspec;
779
780 /* Copy the refspec and add the tags to it */
781 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
782 tags_refspec = parse_fetch_refspec(1, &tags_str);
783 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
784 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
785 ref_count++;
786
787 prune_refs(refspec, ref_count, ref_map);
788
789 ref_count--;
790 /* The rest of the strings belong to fetch_one */
791 free_refspec(1, tags_refspec);
792 free(refspec);
793 } else if (ref_count) {
794 prune_refs(refs, ref_count, ref_map);
795 } else {
796 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
797 }
798 }
799 free_refs(ref_map);
800
801 /* if neither --no-tags nor --tags was specified, do automated tag
802 * following ... */
803 if (tags == TAGS_DEFAULT && autotags) {
804 struct ref **tail = &ref_map;
805 ref_map = NULL;
806 find_non_local_tags(transport, &ref_map, &tail);
807 if (ref_map) {
808 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
809 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
810 fetch_refs(transport, ref_map);
811 }
812 free_refs(ref_map);
813 }
814
815 cleanup:
816 string_list_clear(&existing_refs, 1);
817 return retcode;
818}
819
820static void set_option(const char *name, const char *value)
821{
822 int r = transport_set_option(transport, name, value);
823 if (r < 0)
824 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
825 name, value, transport->url);
826 if (r > 0)
827 warning(_("Option \"%s\" is ignored for %s\n"),
828 name, transport->url);
829}
830
831static int get_one_remote_for_fetch(struct remote *remote, void *priv)
832{
833 struct string_list *list = priv;
834 if (!remote->skip_default_update)
835 string_list_append(list, remote->name);
836 return 0;
837}
838
839struct remote_group_data {
840 const char *name;
841 struct string_list *list;
842};
843
844static int get_remote_group(const char *key, const char *value, void *priv)
845{
846 struct remote_group_data *g = priv;
847
848 if (!prefixcmp(key, "remotes.") &&
849 !strcmp(key + 8, g->name)) {
850 /* split list by white space */
851 int space = strcspn(value, " \t\n");
852 while (*value) {
853 if (space > 1) {
854 string_list_append(g->list,
855 xstrndup(value, space));
856 }
857 value += space + (value[space] != '\0');
858 space = strcspn(value, " \t\n");
859 }
860 }
861
862 return 0;
863}
864
865static int add_remote_or_group(const char *name, struct string_list *list)
866{
867 int prev_nr = list->nr;
868 struct remote_group_data g;
869 g.name = name; g.list = list;
870
871 git_config(get_remote_group, &g);
872 if (list->nr == prev_nr) {
873 struct remote *remote;
874 if (!remote_is_configured(name))
875 return 0;
876 remote = remote_get(name);
877 string_list_append(list, remote->name);
878 }
879 return 1;
880}
881
882static void add_options_to_argv(struct argv_array *argv)
883{
884 if (dry_run)
885 argv_array_push(argv, "--dry-run");
886 if (prune)
887 argv_array_push(argv, "--prune");
888 if (update_head_ok)
889 argv_array_push(argv, "--update-head-ok");
890 if (force)
891 argv_array_push(argv, "--force");
892 if (keep)
893 argv_array_push(argv, "--keep");
894 if (recurse_submodules == RECURSE_SUBMODULES_ON)
895 argv_array_push(argv, "--recurse-submodules");
896 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
897 argv_array_push(argv, "--recurse-submodules=on-demand");
898 if (tags == TAGS_SET)
899 argv_array_push(argv, "--tags");
900 else if (tags == TAGS_UNSET)
901 argv_array_push(argv, "--no-tags");
902 if (verbosity >= 2)
903 argv_array_push(argv, "-v");
904 if (verbosity >= 1)
905 argv_array_push(argv, "-v");
906 else if (verbosity < 0)
907 argv_array_push(argv, "-q");
908
909}
910
911static int fetch_multiple(struct string_list *list)
912{
913 int i, result = 0;
914 struct argv_array argv = ARGV_ARRAY_INIT;
915
916 if (!append && !dry_run) {
917 int errcode = truncate_fetch_head();
918 if (errcode)
919 return errcode;
920 }
921
922 argv_array_pushl(&argv, "fetch", "--append", NULL);
923 add_options_to_argv(&argv);
924
925 for (i = 0; i < list->nr; i++) {
926 const char *name = list->items[i].string;
927 argv_array_push(&argv, name);
928 if (verbosity >= 0)
929 printf(_("Fetching %s\n"), name);
930 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
931 error(_("Could not fetch %s"), name);
932 result = 1;
933 }
934 argv_array_pop(&argv);
935 }
936
937 argv_array_clear(&argv);
938 return result;
939}
940
941static int fetch_one(struct remote *remote, int argc, const char **argv)
942{
943 int i;
944 static const char **refs = NULL;
945 struct refspec *refspec;
946 int ref_nr = 0;
947 int exit_code;
948
949 if (!remote)
950 die(_("No remote repository specified. Please, specify either a URL or a\n"
951 "remote name from which new revisions should be fetched."));
952
953 transport = transport_get(remote, NULL);
954 transport_set_verbosity(transport, verbosity, progress);
955 if (upload_pack)
956 set_option(TRANS_OPT_UPLOADPACK, upload_pack);
957 if (keep)
958 set_option(TRANS_OPT_KEEP, "yes");
959 if (depth)
960 set_option(TRANS_OPT_DEPTH, depth);
961
962 if (argc > 0) {
963 int j = 0;
964 refs = xcalloc(argc + 1, sizeof(const char *));
965 for (i = 0; i < argc; i++) {
966 if (!strcmp(argv[i], "tag")) {
967 char *ref;
968 i++;
969 if (i >= argc)
970 die(_("You need to specify a tag name."));
971 ref = xmalloc(strlen(argv[i]) * 2 + 22);
972 strcpy(ref, "refs/tags/");
973 strcat(ref, argv[i]);
974 strcat(ref, ":refs/tags/");
975 strcat(ref, argv[i]);
976 refs[j++] = ref;
977 } else
978 refs[j++] = argv[i];
979 }
980 refs[j] = NULL;
981 ref_nr = j;
982 }
983
984 sigchain_push_common(unlock_pack_on_signal);
985 atexit(unlock_pack);
986 refspec = parse_fetch_refspec(ref_nr, refs);
987 exit_code = do_fetch(transport, refspec, ref_nr);
988 free_refspec(ref_nr, refspec);
989 transport_disconnect(transport);
990 transport = NULL;
991 return exit_code;
992}
993
994int cmd_fetch(int argc, const char **argv, const char *prefix)
995{
996 int i;
997 struct string_list list = STRING_LIST_INIT_NODUP;
998 struct remote *remote;
999 int result = 0;
1000 static const char *argv_gc_auto[] = {
1001 "gc", "--auto", NULL,
1002 };
1003
1004 packet_trace_identity("fetch");
1005
1006 /* Record the command line for the reflog */
1007 strbuf_addstr(&default_rla, "fetch");
1008 for (i = 1; i < argc; i++)
1009 strbuf_addf(&default_rla, " %s", argv[i]);
1010
1011 argc = parse_options(argc, argv, prefix,
1012 builtin_fetch_options, builtin_fetch_usage, 0);
1013
1014 if (unshallow) {
1015 if (depth)
1016 die(_("--depth and --unshallow cannot be used together"));
1017 else if (!is_repository_shallow())
1018 die(_("--unshallow on a complete repository does not make sense"));
1019 else {
1020 static char inf_depth[12];
1021 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1022 depth = inf_depth;
1023 }
1024 }
1025
1026 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1027 if (recurse_submodules_default) {
1028 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1029 set_config_fetch_recurse_submodules(arg);
1030 }
1031 gitmodules_config();
1032 git_config(submodule_config, NULL);
1033 }
1034
1035 if (all) {
1036 if (argc == 1)
1037 die(_("fetch --all does not take a repository argument"));
1038 else if (argc > 1)
1039 die(_("fetch --all does not make sense with refspecs"));
1040 (void) for_each_remote(get_one_remote_for_fetch, &list);
1041 result = fetch_multiple(&list);
1042 } else if (argc == 0) {
1043 /* No arguments -- use default remote */
1044 remote = remote_get(NULL);
1045 result = fetch_one(remote, argc, argv);
1046 } else if (multiple) {
1047 /* All arguments are assumed to be remotes or groups */
1048 for (i = 0; i < argc; i++)
1049 if (!add_remote_or_group(argv[i], &list))
1050 die(_("No such remote or remote group: %s"), argv[i]);
1051 result = fetch_multiple(&list);
1052 } else {
1053 /* Single remote or group */
1054 (void) add_remote_or_group(argv[0], &list);
1055 if (list.nr > 1) {
1056 /* More than one remote */
1057 if (argc > 1)
1058 die(_("Fetching a group and specifying refspecs does not make sense"));
1059 result = fetch_multiple(&list);
1060 } else {
1061 /* Zero or one remotes */
1062 remote = remote_get(argv[0]);
1063 result = fetch_one(remote, argc-1, argv+1);
1064 }
1065 }
1066
1067 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1068 struct argv_array options = ARGV_ARRAY_INIT;
1069
1070 add_options_to_argv(&options);
1071 result = fetch_populated_submodules(&options,
1072 submodule_prefix,
1073 recurse_submodules,
1074 verbosity < 0);
1075 argv_array_clear(&options);
1076 }
1077
1078 /* All names were strdup()ed or strndup()ed */
1079 list.strdup_strings = 1;
1080 string_list_clear(&list, 0);
1081
1082 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1083
1084 return result;
1085}