Merge branch 'hv/submodule-config' into next
[git/jrn.git] / builtin / fetch.c
blob7736b2fa3f01ab70270bec5183b5a40453e6f2ee
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, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
578 int want_status;
580 fp = fopen(filename, "a");
581 if (!fp)
582 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
584 if (raw_url)
585 url = transport_anonymize_url(raw_url);
586 else
587 url = xstrdup("foreign");
589 rm = ref_map;
590 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
591 rc = error(_("%s did not send all necessary objects\n"), url);
592 goto abort;
596 * We do a pass for each fetch_head_status type in their enum order, so
597 * merged entries are written before not-for-merge. That lets readers
598 * use FETCH_HEAD as a refname to refer to the ref to be merged.
600 for (want_status = FETCH_HEAD_MERGE;
601 want_status <= FETCH_HEAD_IGNORE;
602 want_status++) {
603 for (rm = ref_map; rm; rm = rm->next) {
604 struct ref *ref = NULL;
605 const char *merge_status_marker = "";
607 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
608 if (want_status == FETCH_HEAD_MERGE)
609 warning(_("reject %s because shallow roots are not allowed to be updated"),
610 rm->peer_ref ? rm->peer_ref->name : rm->name);
611 continue;
614 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
615 if (!commit)
616 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
618 if (rm->fetch_head_status != want_status)
619 continue;
621 if (rm->peer_ref) {
622 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
623 strcpy(ref->name, rm->peer_ref->name);
624 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
625 hashcpy(ref->new_sha1, rm->old_sha1);
626 ref->force = rm->peer_ref->force;
630 if (!strcmp(rm->name, "HEAD")) {
631 kind = "";
632 what = "";
634 else if (starts_with(rm->name, "refs/heads/")) {
635 kind = "branch";
636 what = rm->name + 11;
638 else if (starts_with(rm->name, "refs/tags/")) {
639 kind = "tag";
640 what = rm->name + 10;
642 else if (starts_with(rm->name, "refs/remotes/")) {
643 kind = "remote-tracking branch";
644 what = rm->name + 13;
646 else {
647 kind = "";
648 what = rm->name;
651 url_len = strlen(url);
652 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
654 url_len = i + 1;
655 if (4 < i && !strncmp(".git", url + i - 3, 4))
656 url_len = i - 3;
658 strbuf_reset(&note);
659 if (*what) {
660 if (*kind)
661 strbuf_addf(&note, "%s ", kind);
662 strbuf_addf(&note, "'%s' of ", what);
664 switch (rm->fetch_head_status) {
665 case FETCH_HEAD_NOT_FOR_MERGE:
666 merge_status_marker = "not-for-merge";
667 /* fall-through */
668 case FETCH_HEAD_MERGE:
669 fprintf(fp, "%s\t%s\t%s",
670 sha1_to_hex(rm->old_sha1),
671 merge_status_marker,
672 note.buf);
673 for (i = 0; i < url_len; ++i)
674 if ('\n' == url[i])
675 fputs("\\n", fp);
676 else
677 fputc(url[i], fp);
678 fputc('\n', fp);
679 break;
680 default:
681 /* do not write anything to FETCH_HEAD */
682 break;
685 strbuf_reset(&note);
686 if (ref) {
687 rc |= update_local_ref(ref, what, rm, &note);
688 free(ref);
689 } else
690 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
691 TRANSPORT_SUMMARY_WIDTH,
692 *kind ? kind : "branch",
693 REFCOL_WIDTH,
694 *what ? what : "HEAD");
695 if (note.len) {
696 if (verbosity >= 0 && !shown_url) {
697 fprintf(stderr, _("From %.*s\n"),
698 url_len, url);
699 shown_url = 1;
701 if (verbosity >= 0)
702 fprintf(stderr, " %s\n", note.buf);
707 if (rc & STORE_REF_ERROR_DF_CONFLICT)
708 error(_("some local refs could not be updated; try running\n"
709 " 'git remote prune %s' to remove any old, conflicting "
710 "branches"), remote_name);
712 abort:
713 strbuf_release(&note);
714 free(url);
715 fclose(fp);
716 return rc;
720 * We would want to bypass the object transfer altogether if
721 * everything we are going to fetch already exists and is connected
722 * locally.
724 static int quickfetch(struct ref *ref_map)
726 struct ref *rm = ref_map;
729 * If we are deepening a shallow clone we already have these
730 * objects reachable. Running rev-list here will return with
731 * a good (0) exit status and we'll bypass the fetch that we
732 * really need to perform. Claiming failure now will ensure
733 * we perform the network exchange to deepen our history.
735 if (depth)
736 return -1;
737 return check_everything_connected(iterate_ref_map, 1, &rm);
740 static int fetch_refs(struct transport *transport, struct ref *ref_map)
742 int ret = quickfetch(ref_map);
743 if (ret)
744 ret = transport_fetch_refs(transport, ref_map);
745 if (!ret)
746 ret |= store_updated_refs(transport->url,
747 transport->remote->name,
748 ref_map);
749 transport_unlock_pack(transport);
750 return ret;
753 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
754 const char *raw_url)
756 int url_len, i, result = 0;
757 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
758 char *url;
759 const char *dangling_msg = dry_run
760 ? _(" (%s will become dangling)")
761 : _(" (%s has become dangling)");
763 if (raw_url)
764 url = transport_anonymize_url(raw_url);
765 else
766 url = xstrdup("foreign");
768 url_len = strlen(url);
769 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
772 url_len = i + 1;
773 if (4 < i && !strncmp(".git", url + i - 3, 4))
774 url_len = i - 3;
776 for (ref = stale_refs; ref; ref = ref->next) {
777 if (!dry_run)
778 result |= delete_ref(ref->name, NULL, 0);
779 if (verbosity >= 0 && !shown_url) {
780 fprintf(stderr, _("From %.*s\n"), url_len, url);
781 shown_url = 1;
783 if (verbosity >= 0) {
784 fprintf(stderr, " x %-*s %-*s -> %s\n",
785 TRANSPORT_SUMMARY(_("[deleted]")),
786 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
787 warn_dangling_symref(stderr, dangling_msg, ref->name);
790 free(url);
791 free_refs(stale_refs);
792 return result;
795 static void check_not_current_branch(struct ref *ref_map)
797 struct branch *current_branch = branch_get(NULL);
799 if (is_bare_repository() || !current_branch)
800 return;
802 for (; ref_map; ref_map = ref_map->next)
803 if (ref_map->peer_ref && !strcmp(current_branch->refname,
804 ref_map->peer_ref->name))
805 die(_("Refusing to fetch into current branch %s "
806 "of non-bare repository"), current_branch->refname);
809 static int truncate_fetch_head(void)
811 char *filename = git_path("FETCH_HEAD");
812 FILE *fp = fopen(filename, "w");
814 if (!fp)
815 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
816 fclose(fp);
817 return 0;
820 static void set_option(struct transport *transport, const char *name, const char *value)
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);
831 static struct transport *prepare_transport(struct remote *remote)
833 struct transport *transport;
834 transport = transport_get(remote, NULL);
835 transport_set_verbosity(transport, verbosity, progress);
836 if (upload_pack)
837 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
838 if (keep)
839 set_option(transport, TRANS_OPT_KEEP, "yes");
840 if (depth)
841 set_option(transport, TRANS_OPT_DEPTH, depth);
842 if (update_shallow)
843 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
844 return transport;
847 static void backfill_tags(struct transport *transport, struct ref *ref_map)
849 if (transport->cannot_reuse) {
850 gsecondary = prepare_transport(transport->remote);
851 transport = gsecondary;
854 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
855 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
856 fetch_refs(transport, ref_map);
858 if (gsecondary) {
859 transport_disconnect(gsecondary);
860 gsecondary = NULL;
864 static int do_fetch(struct transport *transport,
865 struct refspec *refs, int ref_count)
867 struct string_list existing_refs = STRING_LIST_INIT_DUP;
868 struct ref *ref_map;
869 struct ref *rm;
870 int autotags = (transport->remote->fetch_tags == 1);
871 int retcode = 0;
873 for_each_ref(add_existing, &existing_refs);
875 if (tags == TAGS_DEFAULT) {
876 if (transport->remote->fetch_tags == 2)
877 tags = TAGS_SET;
878 if (transport->remote->fetch_tags == -1)
879 tags = TAGS_UNSET;
882 if (!transport->get_refs_list || !transport->fetch)
883 die(_("Don't know how to fetch from %s"), transport->url);
885 /* if not appending, truncate FETCH_HEAD */
886 if (!append && !dry_run) {
887 retcode = truncate_fetch_head();
888 if (retcode)
889 goto cleanup;
892 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
893 if (!update_head_ok)
894 check_not_current_branch(ref_map);
896 for (rm = ref_map; rm; rm = rm->next) {
897 if (rm->peer_ref) {
898 struct string_list_item *peer_item =
899 string_list_lookup(&existing_refs,
900 rm->peer_ref->name);
901 if (peer_item)
902 hashcpy(rm->peer_ref->old_sha1,
903 peer_item->util);
907 if (tags == TAGS_DEFAULT && autotags)
908 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
909 if (prune) {
911 * We only prune based on refspecs specified
912 * explicitly (via command line or configuration); we
913 * don't care whether --tags was specified.
915 if (ref_count) {
916 prune_refs(refs, ref_count, ref_map, transport->url);
917 } else {
918 prune_refs(transport->remote->fetch,
919 transport->remote->fetch_refspec_nr,
920 ref_map,
921 transport->url);
924 if (fetch_refs(transport, ref_map)) {
925 free_refs(ref_map);
926 retcode = 1;
927 goto cleanup;
929 free_refs(ref_map);
931 /* if neither --no-tags nor --tags was specified, do automated tag
932 * following ... */
933 if (tags == TAGS_DEFAULT && autotags) {
934 struct ref **tail = &ref_map;
935 ref_map = NULL;
936 find_non_local_tags(transport, &ref_map, &tail);
937 if (ref_map)
938 backfill_tags(transport, ref_map);
939 free_refs(ref_map);
942 cleanup:
943 string_list_clear(&existing_refs, 1);
944 return retcode;
947 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
949 struct string_list *list = priv;
950 if (!remote->skip_default_update)
951 string_list_append(list, remote->name);
952 return 0;
955 struct remote_group_data {
956 const char *name;
957 struct string_list *list;
960 static int get_remote_group(const char *key, const char *value, void *priv)
962 struct remote_group_data *g = priv;
964 if (starts_with(key, "remotes.") &&
965 !strcmp(key + 8, g->name)) {
966 /* split list by white space */
967 int space = strcspn(value, " \t\n");
968 while (*value) {
969 if (space > 1) {
970 string_list_append(g->list,
971 xstrndup(value, space));
973 value += space + (value[space] != '\0');
974 space = strcspn(value, " \t\n");
978 return 0;
981 static int add_remote_or_group(const char *name, struct string_list *list)
983 int prev_nr = list->nr;
984 struct remote_group_data g;
985 g.name = name; g.list = list;
987 git_config(get_remote_group, &g);
988 if (list->nr == prev_nr) {
989 struct remote *remote;
990 if (!remote_is_configured(name))
991 return 0;
992 remote = remote_get(name);
993 string_list_append(list, remote->name);
995 return 1;
998 static void add_options_to_argv(struct argv_array *argv)
1000 if (dry_run)
1001 argv_array_push(argv, "--dry-run");
1002 if (prune != -1)
1003 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1004 if (update_head_ok)
1005 argv_array_push(argv, "--update-head-ok");
1006 if (force)
1007 argv_array_push(argv, "--force");
1008 if (keep)
1009 argv_array_push(argv, "--keep");
1010 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1011 argv_array_push(argv, "--recurse-submodules");
1012 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1013 argv_array_push(argv, "--recurse-submodules=on-demand");
1014 if (tags == TAGS_SET)
1015 argv_array_push(argv, "--tags");
1016 else if (tags == TAGS_UNSET)
1017 argv_array_push(argv, "--no-tags");
1018 if (verbosity >= 2)
1019 argv_array_push(argv, "-v");
1020 if (verbosity >= 1)
1021 argv_array_push(argv, "-v");
1022 else if (verbosity < 0)
1023 argv_array_push(argv, "-q");
1027 static int fetch_multiple(struct string_list *list)
1029 int i, result = 0;
1030 struct argv_array argv = ARGV_ARRAY_INIT;
1032 if (!append && !dry_run) {
1033 int errcode = truncate_fetch_head();
1034 if (errcode)
1035 return errcode;
1038 argv_array_pushl(&argv, "fetch", "--append", NULL);
1039 add_options_to_argv(&argv);
1041 for (i = 0; i < list->nr; i++) {
1042 const char *name = list->items[i].string;
1043 argv_array_push(&argv, name);
1044 if (verbosity >= 0)
1045 printf(_("Fetching %s\n"), name);
1046 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1047 error(_("Could not fetch %s"), name);
1048 result = 1;
1050 argv_array_pop(&argv);
1053 argv_array_clear(&argv);
1054 return result;
1057 static int fetch_one(struct remote *remote, int argc, const char **argv)
1059 static const char **refs = NULL;
1060 struct refspec *refspec;
1061 int ref_nr = 0;
1062 int exit_code;
1064 if (!remote)
1065 die(_("No remote repository specified. Please, specify either a URL or a\n"
1066 "remote name from which new revisions should be fetched."));
1068 gtransport = prepare_transport(remote);
1070 if (prune < 0) {
1071 /* no command line request */
1072 if (0 <= gtransport->remote->prune)
1073 prune = gtransport->remote->prune;
1074 else if (0 <= fetch_prune_config)
1075 prune = fetch_prune_config;
1076 else
1077 prune = PRUNE_BY_DEFAULT;
1080 if (argc > 0) {
1081 int j = 0;
1082 int i;
1083 refs = xcalloc(argc + 1, sizeof(const char *));
1084 for (i = 0; i < argc; i++) {
1085 if (!strcmp(argv[i], "tag")) {
1086 i++;
1087 if (i >= argc)
1088 die(_("You need to specify a tag name."));
1089 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1090 argv[i], argv[i]);
1091 } else
1092 refs[j++] = argv[i];
1094 refs[j] = NULL;
1095 ref_nr = j;
1098 sigchain_push_common(unlock_pack_on_signal);
1099 atexit(unlock_pack);
1100 refspec = parse_fetch_refspec(ref_nr, refs);
1101 exit_code = do_fetch(gtransport, refspec, ref_nr);
1102 free_refspec(ref_nr, refspec);
1103 transport_disconnect(gtransport);
1104 gtransport = NULL;
1105 return exit_code;
1108 int cmd_fetch(int argc, const char **argv, const char *prefix)
1110 int i;
1111 struct string_list list = STRING_LIST_INIT_NODUP;
1112 struct remote *remote;
1113 int result = 0;
1114 static const char *argv_gc_auto[] = {
1115 "gc", "--auto", NULL,
1118 packet_trace_identity("fetch");
1120 /* Record the command line for the reflog */
1121 strbuf_addstr(&default_rla, "fetch");
1122 for (i = 1; i < argc; i++)
1123 strbuf_addf(&default_rla, " %s", argv[i]);
1125 git_config(git_fetch_config, NULL);
1127 argc = parse_options(argc, argv, prefix,
1128 builtin_fetch_options, builtin_fetch_usage, 0);
1130 if (unshallow) {
1131 if (depth)
1132 die(_("--depth and --unshallow cannot be used together"));
1133 else if (!is_repository_shallow())
1134 die(_("--unshallow on a complete repository does not make sense"));
1135 else {
1136 static char inf_depth[12];
1137 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1138 depth = inf_depth;
1142 /* no need to be strict, transport_set_option() will validate it again */
1143 if (depth && atoi(depth) < 1)
1144 die(_("depth %s is not a positive number"), depth);
1146 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1147 if (recurse_submodules_default) {
1148 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1149 set_config_fetch_recurse_submodules(arg);
1151 gitmodules_config();
1152 git_config(submodule_config, NULL);
1155 if (all) {
1156 if (argc == 1)
1157 die(_("fetch --all does not take a repository argument"));
1158 else if (argc > 1)
1159 die(_("fetch --all does not make sense with refspecs"));
1160 (void) for_each_remote(get_one_remote_for_fetch, &list);
1161 result = fetch_multiple(&list);
1162 } else if (argc == 0) {
1163 /* No arguments -- use default remote */
1164 remote = remote_get(NULL);
1165 result = fetch_one(remote, argc, argv);
1166 } else if (multiple) {
1167 /* All arguments are assumed to be remotes or groups */
1168 for (i = 0; i < argc; i++)
1169 if (!add_remote_or_group(argv[i], &list))
1170 die(_("No such remote or remote group: %s"), argv[i]);
1171 result = fetch_multiple(&list);
1172 } else {
1173 /* Single remote or group */
1174 (void) add_remote_or_group(argv[0], &list);
1175 if (list.nr > 1) {
1176 /* More than one remote */
1177 if (argc > 1)
1178 die(_("Fetching a group and specifying refspecs does not make sense"));
1179 result = fetch_multiple(&list);
1180 } else {
1181 /* Zero or one remotes */
1182 remote = remote_get(argv[0]);
1183 result = fetch_one(remote, argc-1, argv+1);
1187 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1188 struct argv_array options = ARGV_ARRAY_INIT;
1190 add_options_to_argv(&options);
1191 result = fetch_populated_submodules(&options,
1192 submodule_prefix,
1193 recurse_submodules,
1194 verbosity < 0);
1195 argv_array_clear(&options);
1198 /* All names were strdup()ed or strndup()ed */
1199 list.strdup_strings = 1;
1200 string_list_clear(&list, 0);
1202 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1204 return result;