Merge branch 'nd/multiple-work-trees' into next
[git/jrn.git] / builtin / fetch.c
blob7de94bcb40f3277d3973fd806a6d4ef8ad85c3ec
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-config.h"
16 #include "submodule.h"
17 #include "connected.h"
18 #include "argv-array.h"
20 static const char * const builtin_fetch_usage[] = {
21 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
22 N_("git fetch [<options>] <group>"),
23 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
24 N_("git fetch --all [<options>]"),
25 NULL
28 enum {
29 TAGS_UNSET = 0,
30 TAGS_DEFAULT = 1,
31 TAGS_SET = 2
34 static int fetch_prune_config = -1; /* unspecified */
35 static int prune = -1; /* unspecified */
36 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
38 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
39 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
40 static int tags = TAGS_DEFAULT, unshallow, update_shallow;
41 static const char *depth;
42 static const char *upload_pack;
43 static struct strbuf default_rla = STRBUF_INIT;
44 static struct transport *gtransport;
45 static struct transport *gsecondary;
46 static const char *submodule_prefix = "";
47 static const char *recurse_submodules_default;
48 static int shown_url = 0;
49 static int refmap_alloc, refmap_nr;
50 static const char **refmap_array;
52 static int option_parse_recurse_submodules(const struct option *opt,
53 const char *arg, int unset)
55 if (unset) {
56 recurse_submodules = RECURSE_SUBMODULES_OFF;
57 } else {
58 if (arg)
59 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
60 else
61 recurse_submodules = RECURSE_SUBMODULES_ON;
63 return 0;
66 static int git_fetch_config(const char *k, const char *v, void *cb)
68 if (!strcmp(k, "fetch.prune")) {
69 fetch_prune_config = git_config_bool(k, v);
70 return 0;
72 return 0;
75 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
77 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
80 * "git fetch --refmap='' origin foo"
81 * can be used to tell the command not to store anywhere
83 if (*arg)
84 refmap_array[refmap_nr++] = arg;
85 return 0;
88 static struct option builtin_fetch_options[] = {
89 OPT__VERBOSITY(&verbosity),
90 OPT_BOOL(0, "all", &all,
91 N_("fetch from all remotes")),
92 OPT_BOOL('a', "append", &append,
93 N_("append to .git/FETCH_HEAD instead of overwriting")),
94 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
95 N_("path to upload pack on remote end")),
96 OPT__FORCE(&force, N_("force overwrite of local branch")),
97 OPT_BOOL('m', "multiple", &multiple,
98 N_("fetch from multiple remotes")),
99 OPT_SET_INT('t', "tags", &tags,
100 N_("fetch all tags and associated objects"), TAGS_SET),
101 OPT_SET_INT('n', NULL, &tags,
102 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
103 OPT_BOOL('p', "prune", &prune,
104 N_("prune remote-tracking branches no longer on remote")),
105 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
106 N_("control recursive fetching of submodules"),
107 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
108 OPT_BOOL(0, "dry-run", &dry_run,
109 N_("dry run")),
110 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
111 OPT_BOOL('u', "update-head-ok", &update_head_ok,
112 N_("allow updating of HEAD ref")),
113 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
114 OPT_STRING(0, "depth", &depth, N_("depth"),
115 N_("deepen history of shallow clone")),
116 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
117 N_("convert to a complete repository"),
118 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
119 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
120 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
121 { OPTION_STRING, 0, "recurse-submodules-default",
122 &recurse_submodules_default, NULL,
123 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
124 OPT_BOOL(0, "update-shallow", &update_shallow,
125 N_("accept refs that update .git/shallow")),
126 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
127 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
128 OPT_END()
131 static void unlock_pack(void)
133 if (gtransport)
134 transport_unlock_pack(gtransport);
135 if (gsecondary)
136 transport_unlock_pack(gsecondary);
139 static void unlock_pack_on_signal(int signo)
141 unlock_pack();
142 sigchain_pop(signo);
143 raise(signo);
146 static void add_merge_config(struct ref **head,
147 const struct ref *remote_refs,
148 struct branch *branch,
149 struct ref ***tail)
151 int i;
153 for (i = 0; i < branch->merge_nr; i++) {
154 struct ref *rm, **old_tail = *tail;
155 struct refspec refspec;
157 for (rm = *head; rm; rm = rm->next) {
158 if (branch_merge_matches(branch, i, rm->name)) {
159 rm->fetch_head_status = FETCH_HEAD_MERGE;
160 break;
163 if (rm)
164 continue;
167 * Not fetched to a remote-tracking branch? We need to fetch
168 * it anyway to allow this branch's "branch.$name.merge"
169 * to be honored by 'git pull', but we do not have to
170 * fail if branch.$name.merge is misconfigured to point
171 * at a nonexisting branch. If we were indeed called by
172 * 'git pull', it will notice the misconfiguration because
173 * there is no entry in the resulting FETCH_HEAD marked
174 * for merging.
176 memset(&refspec, 0, sizeof(refspec));
177 refspec.src = branch->merge[i]->src;
178 get_fetch_map(remote_refs, &refspec, tail, 1);
179 for (rm = *old_tail; rm; rm = rm->next)
180 rm->fetch_head_status = FETCH_HEAD_MERGE;
184 static int add_existing(const char *refname, const unsigned char *sha1,
185 int flag, void *cbdata)
187 struct string_list *list = (struct string_list *)cbdata;
188 struct string_list_item *item = string_list_insert(list, refname);
189 item->util = xmalloc(20);
190 hashcpy(item->util, sha1);
191 return 0;
194 static int will_fetch(struct ref **head, const unsigned char *sha1)
196 struct ref *rm = *head;
197 while (rm) {
198 if (!hashcmp(rm->old_sha1, sha1))
199 return 1;
200 rm = rm->next;
202 return 0;
205 static void find_non_local_tags(struct transport *transport,
206 struct ref **head,
207 struct ref ***tail)
209 struct string_list existing_refs = STRING_LIST_INIT_DUP;
210 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
211 const struct ref *ref;
212 struct string_list_item *item = NULL;
214 for_each_ref(add_existing, &existing_refs);
215 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
216 if (!starts_with(ref->name, "refs/tags/"))
217 continue;
220 * The peeled ref always follows the matching base
221 * ref, so if we see a peeled ref that we don't want
222 * to fetch then we can mark the ref entry in the list
223 * as one to ignore by setting util to NULL.
225 if (ends_with(ref->name, "^{}")) {
226 if (item && !has_sha1_file(ref->old_sha1) &&
227 !will_fetch(head, ref->old_sha1) &&
228 !has_sha1_file(item->util) &&
229 !will_fetch(head, item->util))
230 item->util = NULL;
231 item = NULL;
232 continue;
236 * If item is non-NULL here, then we previously saw a
237 * ref not followed by a peeled reference, so we need
238 * to check if it is a lightweight tag that we want to
239 * fetch.
241 if (item && !has_sha1_file(item->util) &&
242 !will_fetch(head, item->util))
243 item->util = NULL;
245 item = NULL;
247 /* skip duplicates and refs that we already have */
248 if (string_list_has_string(&remote_refs, ref->name) ||
249 string_list_has_string(&existing_refs, ref->name))
250 continue;
252 item = string_list_insert(&remote_refs, ref->name);
253 item->util = (void *)ref->old_sha1;
255 string_list_clear(&existing_refs, 1);
258 * We may have a final lightweight tag that needs to be
259 * checked to see if it needs fetching.
261 if (item && !has_sha1_file(item->util) &&
262 !will_fetch(head, item->util))
263 item->util = NULL;
266 * For all the tags in the remote_refs string list,
267 * add them to the list of refs to be fetched
269 for_each_string_list_item(item, &remote_refs) {
270 /* Unless we have already decided to ignore this item... */
271 if (item->util)
273 struct ref *rm = alloc_ref(item->string);
274 rm->peer_ref = alloc_ref(item->string);
275 hashcpy(rm->old_sha1, item->util);
276 **tail = rm;
277 *tail = &rm->next;
281 string_list_clear(&remote_refs, 0);
284 static struct ref *get_ref_map(struct transport *transport,
285 struct refspec *refspecs, int refspec_count,
286 int tags, int *autotags)
288 int i;
289 struct ref *rm;
290 struct ref *ref_map = NULL;
291 struct ref **tail = &ref_map;
293 /* opportunistically-updated references: */
294 struct ref *orefs = NULL, **oref_tail = &orefs;
296 const struct ref *remote_refs = transport_get_remote_refs(transport);
298 if (refspec_count) {
299 struct refspec *fetch_refspec;
300 int fetch_refspec_nr;
302 for (i = 0; i < refspec_count; i++) {
303 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
304 if (refspecs[i].dst && refspecs[i].dst[0])
305 *autotags = 1;
307 /* Merge everything on the command line (but not --tags) */
308 for (rm = ref_map; rm; rm = rm->next)
309 rm->fetch_head_status = FETCH_HEAD_MERGE;
312 * For any refs that we happen to be fetching via
313 * command-line arguments, the destination ref might
314 * have been missing or have been different than the
315 * remote-tracking ref that would be derived from the
316 * configured refspec. In these cases, we want to
317 * take the opportunity to update their configured
318 * remote-tracking reference. However, we do not want
319 * to mention these entries in FETCH_HEAD at all, as
320 * they would simply be duplicates of existing
321 * entries, so we set them FETCH_HEAD_IGNORE below.
323 * We compute these entries now, based only on the
324 * refspecs specified on the command line. But we add
325 * them to the list following the refspecs resulting
326 * from the tags option so that one of the latter,
327 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
328 * by ref_remove_duplicates() in favor of one of these
329 * opportunistic entries with FETCH_HEAD_IGNORE.
331 if (refmap_array) {
332 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
333 fetch_refspec_nr = refmap_nr;
334 } else {
335 fetch_refspec = transport->remote->fetch;
336 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
339 for (i = 0; i < fetch_refspec_nr; i++)
340 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
342 if (tags == TAGS_SET)
343 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
344 } else if (refmap_array) {
345 die("--refmap option is only meaningful with command-line refspec(s).");
346 } else {
347 /* Use the defaults */
348 struct remote *remote = transport->remote;
349 struct branch *branch = branch_get(NULL);
350 int has_merge = branch_has_merge_config(branch);
351 if (remote &&
352 (remote->fetch_refspec_nr ||
353 /* Note: has_merge implies non-NULL branch->remote_name */
354 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
355 for (i = 0; i < remote->fetch_refspec_nr; i++) {
356 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
357 if (remote->fetch[i].dst &&
358 remote->fetch[i].dst[0])
359 *autotags = 1;
360 if (!i && !has_merge && ref_map &&
361 !remote->fetch[0].pattern)
362 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
365 * if the remote we're fetching from is the same
366 * as given in branch.<name>.remote, we add the
367 * ref given in branch.<name>.merge, too.
369 * Note: has_merge implies non-NULL branch->remote_name
371 if (has_merge &&
372 !strcmp(branch->remote_name, remote->name))
373 add_merge_config(&ref_map, remote_refs, branch, &tail);
374 } else {
375 ref_map = get_remote_ref(remote_refs, "HEAD");
376 if (!ref_map)
377 die(_("Couldn't find remote ref HEAD"));
378 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
379 tail = &ref_map->next;
383 if (tags == TAGS_SET)
384 /* also fetch all tags */
385 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
386 else if (tags == TAGS_DEFAULT && *autotags)
387 find_non_local_tags(transport, &ref_map, &tail);
389 /* Now append any refs to be updated opportunistically: */
390 *tail = orefs;
391 for (rm = orefs; rm; rm = rm->next) {
392 rm->fetch_head_status = FETCH_HEAD_IGNORE;
393 tail = &rm->next;
396 return ref_remove_duplicates(ref_map);
399 #define STORE_REF_ERROR_OTHER 1
400 #define STORE_REF_ERROR_DF_CONFLICT 2
402 static int s_update_ref(const char *action,
403 struct ref *ref,
404 int check_old)
406 char msg[1024];
407 char *rla = getenv("GIT_REFLOG_ACTION");
408 static struct ref_lock *lock;
410 if (dry_run)
411 return 0;
412 if (!rla)
413 rla = default_rla.buf;
414 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
415 lock = lock_any_ref_for_update(ref->name,
416 check_old ? ref->old_sha1 : NULL,
417 0, NULL);
418 if (!lock)
419 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
420 STORE_REF_ERROR_OTHER;
421 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
422 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
423 STORE_REF_ERROR_OTHER;
424 return 0;
427 #define REFCOL_WIDTH 10
429 static int update_local_ref(struct ref *ref,
430 const char *remote,
431 const struct ref *remote_ref,
432 struct strbuf *display)
434 struct commit *current = NULL, *updated;
435 enum object_type type;
436 struct branch *current_branch = branch_get(NULL);
437 const char *pretty_ref = prettify_refname(ref->name);
439 type = sha1_object_info(ref->new_sha1, NULL);
440 if (type < 0)
441 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
443 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
444 if (verbosity > 0)
445 strbuf_addf(display, "= %-*s %-*s -> %s",
446 TRANSPORT_SUMMARY(_("[up to date]")),
447 REFCOL_WIDTH, remote, pretty_ref);
448 return 0;
451 if (current_branch &&
452 !strcmp(ref->name, current_branch->name) &&
453 !(update_head_ok || is_bare_repository()) &&
454 !is_null_sha1(ref->old_sha1)) {
456 * If this is the head, and it's not okay to update
457 * the head, and the old value of the head isn't empty...
459 strbuf_addf(display,
460 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
461 TRANSPORT_SUMMARY(_("[rejected]")),
462 REFCOL_WIDTH, remote, pretty_ref);
463 return 1;
466 if (!is_null_sha1(ref->old_sha1) &&
467 starts_with(ref->name, "refs/tags/")) {
468 int r;
469 r = s_update_ref("updating tag", ref, 0);
470 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
471 r ? '!' : '-',
472 TRANSPORT_SUMMARY(_("[tag update]")),
473 REFCOL_WIDTH, remote, pretty_ref,
474 r ? _(" (unable to update local ref)") : "");
475 return r;
478 current = lookup_commit_reference_gently(ref->old_sha1, 1);
479 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
480 if (!current || !updated) {
481 const char *msg;
482 const char *what;
483 int r;
485 * Nicely describe the new ref we're fetching.
486 * Base this on the remote's ref name, as it's
487 * more likely to follow a standard layout.
489 const char *name = remote_ref ? remote_ref->name : "";
490 if (starts_with(name, "refs/tags/")) {
491 msg = "storing tag";
492 what = _("[new tag]");
493 } else if (starts_with(name, "refs/heads/")) {
494 msg = "storing head";
495 what = _("[new branch]");
496 } else {
497 msg = "storing ref";
498 what = _("[new ref]");
501 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
502 (recurse_submodules != RECURSE_SUBMODULES_ON))
503 check_for_new_submodule_commits(ref->new_sha1);
504 r = s_update_ref(msg, ref, 0);
505 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
506 r ? '!' : '*',
507 TRANSPORT_SUMMARY(what),
508 REFCOL_WIDTH, remote, pretty_ref,
509 r ? _(" (unable to update local ref)") : "");
510 return r;
513 if (in_merge_bases(current, updated)) {
514 char quickref[83];
515 int r;
516 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
517 strcat(quickref, "..");
518 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
519 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
520 (recurse_submodules != RECURSE_SUBMODULES_ON))
521 check_for_new_submodule_commits(ref->new_sha1);
522 r = s_update_ref("fast-forward", ref, 1);
523 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
524 r ? '!' : ' ',
525 TRANSPORT_SUMMARY_WIDTH, quickref,
526 REFCOL_WIDTH, remote, pretty_ref,
527 r ? _(" (unable to update local ref)") : "");
528 return r;
529 } else if (force || ref->force) {
530 char quickref[84];
531 int r;
532 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
533 strcat(quickref, "...");
534 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
535 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
536 (recurse_submodules != RECURSE_SUBMODULES_ON))
537 check_for_new_submodule_commits(ref->new_sha1);
538 r = s_update_ref("forced-update", ref, 1);
539 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
540 r ? '!' : '+',
541 TRANSPORT_SUMMARY_WIDTH, quickref,
542 REFCOL_WIDTH, remote, pretty_ref,
543 r ? _("unable to update local ref") : _("forced update"));
544 return r;
545 } else {
546 strbuf_addf(display, "! %-*s %-*s -> %s %s",
547 TRANSPORT_SUMMARY(_("[rejected]")),
548 REFCOL_WIDTH, remote, pretty_ref,
549 _("(non-fast-forward)"));
550 return 1;
554 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
556 struct ref **rm = cb_data;
557 struct ref *ref = *rm;
559 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
560 ref = ref->next;
561 if (!ref)
562 return -1; /* end of the list */
563 *rm = ref->next;
564 hashcpy(sha1, ref->old_sha1);
565 return 0;
568 static int store_updated_refs(const char *raw_url, const char *remote_name,
569 struct ref *ref_map)
571 FILE *fp;
572 struct commit *commit;
573 int url_len, i, rc = 0;
574 struct strbuf note = STRBUF_INIT;
575 const char *what, *kind;
576 struct ref *rm;
577 char *url;
578 const char *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
579 int want_status;
581 fp = fopen(filename, "a");
582 if (!fp)
583 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
585 if (raw_url)
586 url = transport_anonymize_url(raw_url);
587 else
588 url = xstrdup("foreign");
590 rm = ref_map;
591 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
592 rc = error(_("%s did not send all necessary objects\n"), url);
593 goto abort;
597 * We do a pass for each fetch_head_status type in their enum order, so
598 * merged entries are written before not-for-merge. That lets readers
599 * use FETCH_HEAD as a refname to refer to the ref to be merged.
601 for (want_status = FETCH_HEAD_MERGE;
602 want_status <= FETCH_HEAD_IGNORE;
603 want_status++) {
604 for (rm = ref_map; rm; rm = rm->next) {
605 struct ref *ref = NULL;
606 const char *merge_status_marker = "";
608 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
609 if (want_status == FETCH_HEAD_MERGE)
610 warning(_("reject %s because shallow roots are not allowed to be updated"),
611 rm->peer_ref ? rm->peer_ref->name : rm->name);
612 continue;
615 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
616 if (!commit)
617 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
619 if (rm->fetch_head_status != want_status)
620 continue;
622 if (rm->peer_ref) {
623 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
624 strcpy(ref->name, rm->peer_ref->name);
625 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
626 hashcpy(ref->new_sha1, rm->old_sha1);
627 ref->force = rm->peer_ref->force;
631 if (!strcmp(rm->name, "HEAD")) {
632 kind = "";
633 what = "";
635 else if (starts_with(rm->name, "refs/heads/")) {
636 kind = "branch";
637 what = rm->name + 11;
639 else if (starts_with(rm->name, "refs/tags/")) {
640 kind = "tag";
641 what = rm->name + 10;
643 else if (starts_with(rm->name, "refs/remotes/")) {
644 kind = "remote-tracking branch";
645 what = rm->name + 13;
647 else {
648 kind = "";
649 what = rm->name;
652 url_len = strlen(url);
653 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
655 url_len = i + 1;
656 if (4 < i && !strncmp(".git", url + i - 3, 4))
657 url_len = i - 3;
659 strbuf_reset(&note);
660 if (*what) {
661 if (*kind)
662 strbuf_addf(&note, "%s ", kind);
663 strbuf_addf(&note, "'%s' of ", what);
665 switch (rm->fetch_head_status) {
666 case FETCH_HEAD_NOT_FOR_MERGE:
667 merge_status_marker = "not-for-merge";
668 /* fall-through */
669 case FETCH_HEAD_MERGE:
670 fprintf(fp, "%s\t%s\t%s",
671 sha1_to_hex(rm->old_sha1),
672 merge_status_marker,
673 note.buf);
674 for (i = 0; i < url_len; ++i)
675 if ('\n' == url[i])
676 fputs("\\n", fp);
677 else
678 fputc(url[i], fp);
679 fputc('\n', fp);
680 break;
681 default:
682 /* do not write anything to FETCH_HEAD */
683 break;
686 strbuf_reset(&note);
687 if (ref) {
688 rc |= update_local_ref(ref, what, rm, &note);
689 free(ref);
690 } else
691 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
692 TRANSPORT_SUMMARY_WIDTH,
693 *kind ? kind : "branch",
694 REFCOL_WIDTH,
695 *what ? what : "HEAD");
696 if (note.len) {
697 if (verbosity >= 0 && !shown_url) {
698 fprintf(stderr, _("From %.*s\n"),
699 url_len, url);
700 shown_url = 1;
702 if (verbosity >= 0)
703 fprintf(stderr, " %s\n", note.buf);
708 if (rc & STORE_REF_ERROR_DF_CONFLICT)
709 error(_("some local refs could not be updated; try running\n"
710 " 'git remote prune %s' to remove any old, conflicting "
711 "branches"), remote_name);
713 abort:
714 strbuf_release(&note);
715 free(url);
716 fclose(fp);
717 return rc;
721 * We would want to bypass the object transfer altogether if
722 * everything we are going to fetch already exists and is connected
723 * locally.
725 static int quickfetch(struct ref *ref_map)
727 struct ref *rm = ref_map;
730 * If we are deepening a shallow clone we already have these
731 * objects reachable. Running rev-list here will return with
732 * a good (0) exit status and we'll bypass the fetch that we
733 * really need to perform. Claiming failure now will ensure
734 * we perform the network exchange to deepen our history.
736 if (depth)
737 return -1;
738 return check_everything_connected(iterate_ref_map, 1, &rm);
741 static int fetch_refs(struct transport *transport, struct ref *ref_map)
743 int ret = quickfetch(ref_map);
744 if (ret)
745 ret = transport_fetch_refs(transport, ref_map);
746 if (!ret)
747 ret |= store_updated_refs(transport->url,
748 transport->remote->name,
749 ref_map);
750 transport_unlock_pack(transport);
751 return ret;
754 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
755 const char *raw_url)
757 int url_len, i, result = 0;
758 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
759 char *url;
760 const char *dangling_msg = dry_run
761 ? _(" (%s will become dangling)")
762 : _(" (%s has become dangling)");
764 if (raw_url)
765 url = transport_anonymize_url(raw_url);
766 else
767 url = xstrdup("foreign");
769 url_len = strlen(url);
770 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
773 url_len = i + 1;
774 if (4 < i && !strncmp(".git", url + i - 3, 4))
775 url_len = i - 3;
777 for (ref = stale_refs; ref; ref = ref->next) {
778 if (!dry_run)
779 result |= delete_ref(ref->name, NULL, 0);
780 if (verbosity >= 0 && !shown_url) {
781 fprintf(stderr, _("From %.*s\n"), url_len, url);
782 shown_url = 1;
784 if (verbosity >= 0) {
785 fprintf(stderr, " x %-*s %-*s -> %s\n",
786 TRANSPORT_SUMMARY(_("[deleted]")),
787 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
788 warn_dangling_symref(stderr, dangling_msg, ref->name);
791 free(url);
792 free_refs(stale_refs);
793 return result;
796 static void check_not_current_branch(struct ref *ref_map)
798 struct branch *current_branch = branch_get(NULL);
800 if (is_bare_repository() || !current_branch)
801 return;
803 for (; ref_map; ref_map = ref_map->next)
804 if (ref_map->peer_ref && !strcmp(current_branch->refname,
805 ref_map->peer_ref->name))
806 die(_("Refusing to fetch into current branch %s "
807 "of non-bare repository"), current_branch->refname);
810 static int truncate_fetch_head(void)
812 const char *filename = git_path("FETCH_HEAD");
813 FILE *fp = fopen(filename, "w");
815 if (!fp)
816 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
817 fclose(fp);
818 return 0;
821 static void set_option(struct transport *transport, const char *name, const char *value)
823 int r = transport_set_option(transport, name, value);
824 if (r < 0)
825 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
826 name, value, transport->url);
827 if (r > 0)
828 warning(_("Option \"%s\" is ignored for %s\n"),
829 name, transport->url);
832 static struct transport *prepare_transport(struct remote *remote)
834 struct transport *transport;
835 transport = transport_get(remote, NULL);
836 transport_set_verbosity(transport, verbosity, progress);
837 if (upload_pack)
838 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
839 if (keep)
840 set_option(transport, TRANS_OPT_KEEP, "yes");
841 if (depth)
842 set_option(transport, TRANS_OPT_DEPTH, depth);
843 if (update_shallow)
844 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
845 return transport;
848 static void backfill_tags(struct transport *transport, struct ref *ref_map)
850 if (transport->cannot_reuse) {
851 gsecondary = prepare_transport(transport->remote);
852 transport = gsecondary;
855 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
856 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
857 fetch_refs(transport, ref_map);
859 if (gsecondary) {
860 transport_disconnect(gsecondary);
861 gsecondary = NULL;
865 static int do_fetch(struct transport *transport,
866 struct refspec *refs, int ref_count)
868 struct string_list existing_refs = STRING_LIST_INIT_DUP;
869 struct ref *ref_map;
870 struct ref *rm;
871 int autotags = (transport->remote->fetch_tags == 1);
872 int retcode = 0;
874 for_each_ref(add_existing, &existing_refs);
876 if (tags == TAGS_DEFAULT) {
877 if (transport->remote->fetch_tags == 2)
878 tags = TAGS_SET;
879 if (transport->remote->fetch_tags == -1)
880 tags = TAGS_UNSET;
883 if (!transport->get_refs_list || !transport->fetch)
884 die(_("Don't know how to fetch from %s"), transport->url);
886 /* if not appending, truncate FETCH_HEAD */
887 if (!append && !dry_run) {
888 retcode = truncate_fetch_head();
889 if (retcode)
890 goto cleanup;
893 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
894 if (!update_head_ok)
895 check_not_current_branch(ref_map);
897 for (rm = ref_map; rm; rm = rm->next) {
898 if (rm->peer_ref) {
899 struct string_list_item *peer_item =
900 string_list_lookup(&existing_refs,
901 rm->peer_ref->name);
902 if (peer_item)
903 hashcpy(rm->peer_ref->old_sha1,
904 peer_item->util);
908 if (tags == TAGS_DEFAULT && autotags)
909 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
910 if (prune) {
912 * We only prune based on refspecs specified
913 * explicitly (via command line or configuration); we
914 * don't care whether --tags was specified.
916 if (ref_count) {
917 prune_refs(refs, ref_count, ref_map, transport->url);
918 } else {
919 prune_refs(transport->remote->fetch,
920 transport->remote->fetch_refspec_nr,
921 ref_map,
922 transport->url);
925 if (fetch_refs(transport, ref_map)) {
926 free_refs(ref_map);
927 retcode = 1;
928 goto cleanup;
930 free_refs(ref_map);
932 /* if neither --no-tags nor --tags was specified, do automated tag
933 * following ... */
934 if (tags == TAGS_DEFAULT && autotags) {
935 struct ref **tail = &ref_map;
936 ref_map = NULL;
937 find_non_local_tags(transport, &ref_map, &tail);
938 if (ref_map)
939 backfill_tags(transport, ref_map);
940 free_refs(ref_map);
943 cleanup:
944 string_list_clear(&existing_refs, 1);
945 return retcode;
948 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
950 struct string_list *list = priv;
951 if (!remote->skip_default_update)
952 string_list_append(list, remote->name);
953 return 0;
956 struct remote_group_data {
957 const char *name;
958 struct string_list *list;
961 static int get_remote_group(const char *key, const char *value, void *priv)
963 struct remote_group_data *g = priv;
965 if (starts_with(key, "remotes.") &&
966 !strcmp(key + 8, g->name)) {
967 /* split list by white space */
968 int space = strcspn(value, " \t\n");
969 while (*value) {
970 if (space > 1) {
971 string_list_append(g->list,
972 xstrndup(value, space));
974 value += space + (value[space] != '\0');
975 space = strcspn(value, " \t\n");
979 return 0;
982 static int add_remote_or_group(const char *name, struct string_list *list)
984 int prev_nr = list->nr;
985 struct remote_group_data g;
986 g.name = name; g.list = list;
988 git_config(get_remote_group, &g);
989 if (list->nr == prev_nr) {
990 struct remote *remote;
991 if (!remote_is_configured(name))
992 return 0;
993 remote = remote_get(name);
994 string_list_append(list, remote->name);
996 return 1;
999 static void add_options_to_argv(struct argv_array *argv)
1001 if (dry_run)
1002 argv_array_push(argv, "--dry-run");
1003 if (prune != -1)
1004 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1005 if (update_head_ok)
1006 argv_array_push(argv, "--update-head-ok");
1007 if (force)
1008 argv_array_push(argv, "--force");
1009 if (keep)
1010 argv_array_push(argv, "--keep");
1011 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1012 argv_array_push(argv, "--recurse-submodules");
1013 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1014 argv_array_push(argv, "--recurse-submodules=on-demand");
1015 if (tags == TAGS_SET)
1016 argv_array_push(argv, "--tags");
1017 else if (tags == TAGS_UNSET)
1018 argv_array_push(argv, "--no-tags");
1019 if (verbosity >= 2)
1020 argv_array_push(argv, "-v");
1021 if (verbosity >= 1)
1022 argv_array_push(argv, "-v");
1023 else if (verbosity < 0)
1024 argv_array_push(argv, "-q");
1028 static int fetch_multiple(struct string_list *list)
1030 int i, result = 0;
1031 struct argv_array argv = ARGV_ARRAY_INIT;
1033 if (!append && !dry_run) {
1034 int errcode = truncate_fetch_head();
1035 if (errcode)
1036 return errcode;
1039 argv_array_pushl(&argv, "fetch", "--append", NULL);
1040 add_options_to_argv(&argv);
1042 for (i = 0; i < list->nr; i++) {
1043 const char *name = list->items[i].string;
1044 argv_array_push(&argv, name);
1045 if (verbosity >= 0)
1046 printf(_("Fetching %s\n"), name);
1047 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1048 error(_("Could not fetch %s"), name);
1049 result = 1;
1051 argv_array_pop(&argv);
1054 argv_array_clear(&argv);
1055 return result;
1058 static int fetch_one(struct remote *remote, int argc, const char **argv)
1060 static const char **refs = NULL;
1061 struct refspec *refspec;
1062 int ref_nr = 0;
1063 int exit_code;
1065 if (!remote)
1066 die(_("No remote repository specified. Please, specify either a URL or a\n"
1067 "remote name from which new revisions should be fetched."));
1069 gtransport = prepare_transport(remote);
1071 if (prune < 0) {
1072 /* no command line request */
1073 if (0 <= gtransport->remote->prune)
1074 prune = gtransport->remote->prune;
1075 else if (0 <= fetch_prune_config)
1076 prune = fetch_prune_config;
1077 else
1078 prune = PRUNE_BY_DEFAULT;
1081 if (argc > 0) {
1082 int j = 0;
1083 int i;
1084 refs = xcalloc(argc + 1, sizeof(const char *));
1085 for (i = 0; i < argc; i++) {
1086 if (!strcmp(argv[i], "tag")) {
1087 i++;
1088 if (i >= argc)
1089 die(_("You need to specify a tag name."));
1090 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1091 argv[i], argv[i]);
1092 } else
1093 refs[j++] = argv[i];
1095 refs[j] = NULL;
1096 ref_nr = j;
1099 sigchain_push_common(unlock_pack_on_signal);
1100 atexit(unlock_pack);
1101 refspec = parse_fetch_refspec(ref_nr, refs);
1102 exit_code = do_fetch(gtransport, refspec, ref_nr);
1103 free_refspec(ref_nr, refspec);
1104 transport_disconnect(gtransport);
1105 gtransport = NULL;
1106 return exit_code;
1109 int cmd_fetch(int argc, const char **argv, const char *prefix)
1111 int i;
1112 struct string_list list = STRING_LIST_INIT_NODUP;
1113 struct remote *remote;
1114 int result = 0;
1115 static const char *argv_gc_auto[] = {
1116 "gc", "--auto", NULL,
1119 packet_trace_identity("fetch");
1121 /* Record the command line for the reflog */
1122 strbuf_addstr(&default_rla, "fetch");
1123 for (i = 1; i < argc; i++)
1124 strbuf_addf(&default_rla, " %s", argv[i]);
1126 git_config(git_fetch_config, NULL);
1128 argc = parse_options(argc, argv, prefix,
1129 builtin_fetch_options, builtin_fetch_usage, 0);
1131 if (unshallow) {
1132 if (depth)
1133 die(_("--depth and --unshallow cannot be used together"));
1134 else if (!is_repository_shallow())
1135 die(_("--unshallow on a complete repository does not make sense"));
1136 else {
1137 static char inf_depth[12];
1138 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1139 depth = inf_depth;
1143 /* no need to be strict, transport_set_option() will validate it again */
1144 if (depth && atoi(depth) < 1)
1145 die(_("depth %s is not a positive number"), depth);
1147 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1148 if (recurse_submodules_default) {
1149 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1150 set_config_fetch_recurse_submodules(arg);
1152 gitmodules_config();
1153 git_config(submodule_config, NULL);
1156 if (all) {
1157 if (argc == 1)
1158 die(_("fetch --all does not take a repository argument"));
1159 else if (argc > 1)
1160 die(_("fetch --all does not make sense with refspecs"));
1161 (void) for_each_remote(get_one_remote_for_fetch, &list);
1162 result = fetch_multiple(&list);
1163 } else if (argc == 0) {
1164 /* No arguments -- use default remote */
1165 remote = remote_get(NULL);
1166 result = fetch_one(remote, argc, argv);
1167 } else if (multiple) {
1168 /* All arguments are assumed to be remotes or groups */
1169 for (i = 0; i < argc; i++)
1170 if (!add_remote_or_group(argv[i], &list))
1171 die(_("No such remote or remote group: %s"), argv[i]);
1172 result = fetch_multiple(&list);
1173 } else {
1174 /* Single remote or group */
1175 (void) add_remote_or_group(argv[0], &list);
1176 if (list.nr > 1) {
1177 /* More than one remote */
1178 if (argc > 1)
1179 die(_("Fetching a group and specifying refspecs does not make sense"));
1180 result = fetch_multiple(&list);
1181 } else {
1182 /* Zero or one remotes */
1183 remote = remote_get(argv[0]);
1184 result = fetch_one(remote, argc-1, argv+1);
1188 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1189 struct argv_array options = ARGV_ARRAY_INIT;
1191 add_options_to_argv(&options);
1192 result = fetch_populated_submodules(&options,
1193 submodule_prefix,
1194 recurse_submodules,
1195 verbosity < 0);
1196 argv_array_clear(&options);
1199 /* All names were strdup()ed or strndup()ed */
1200 list.strdup_strings = 1;
1201 string_list_clear(&list, 0);
1203 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1205 return result;