t: redirect stderr GIT_TRACE to descriptor 4
[git/mingw.git] / builtin / fetch.c
blob75a55e590bdc3411e5e4aeee6275fbfff4451904
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 "submodule.h"
15 #include "connected.h"
16 #include "argv-array.h"
18 static const char * const builtin_fetch_usage[] = {
19 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
20 N_("git fetch [<options>] <group>"),
21 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
22 N_("git fetch --all [<options>]"),
23 NULL
26 enum {
27 TAGS_UNSET = 0,
28 TAGS_DEFAULT = 1,
29 TAGS_SET = 2
32 static int fetch_prune_config = -1; /* unspecified */
33 static int prune = -1; /* unspecified */
34 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
36 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
37 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
38 static int tags = TAGS_DEFAULT, unshallow, update_shallow;
39 static const char *depth;
40 static const char *upload_pack;
41 static struct strbuf default_rla = STRBUF_INIT;
42 static struct transport *gtransport;
43 static struct transport *gsecondary;
44 static const char *submodule_prefix = "";
45 static const char *recurse_submodules_default;
46 static int shown_url = 0;
47 static int refmap_alloc, refmap_nr;
48 static const char **refmap_array;
50 static int option_parse_recurse_submodules(const struct option *opt,
51 const char *arg, int unset)
53 if (unset) {
54 recurse_submodules = RECURSE_SUBMODULES_OFF;
55 } else {
56 if (arg)
57 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
58 else
59 recurse_submodules = RECURSE_SUBMODULES_ON;
61 return 0;
64 static int git_fetch_config(const char *k, const char *v, void *cb)
66 if (!strcmp(k, "fetch.prune")) {
67 fetch_prune_config = git_config_bool(k, v);
68 return 0;
70 return git_default_config(k, v, cb);
73 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
75 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
78 * "git fetch --refmap='' origin foo"
79 * can be used to tell the command not to store anywhere
81 if (*arg)
82 refmap_array[refmap_nr++] = arg;
83 return 0;
86 static struct option builtin_fetch_options[] = {
87 OPT__VERBOSITY(&verbosity),
88 OPT_BOOL(0, "all", &all,
89 N_("fetch from all remotes")),
90 OPT_BOOL('a', "append", &append,
91 N_("append to .git/FETCH_HEAD instead of overwriting")),
92 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
93 N_("path to upload pack on remote end")),
94 OPT__FORCE(&force, N_("force overwrite of local branch")),
95 OPT_BOOL('m', "multiple", &multiple,
96 N_("fetch from multiple remotes")),
97 OPT_SET_INT('t', "tags", &tags,
98 N_("fetch all tags and associated objects"), TAGS_SET),
99 OPT_SET_INT('n', NULL, &tags,
100 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
101 OPT_BOOL('p', "prune", &prune,
102 N_("prune remote-tracking branches no longer on remote")),
103 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
104 N_("control recursive fetching of submodules"),
105 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
106 OPT_BOOL(0, "dry-run", &dry_run,
107 N_("dry run")),
108 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
109 OPT_BOOL('u', "update-head-ok", &update_head_ok,
110 N_("allow updating of HEAD ref")),
111 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
112 OPT_STRING(0, "depth", &depth, N_("depth"),
113 N_("deepen history of shallow clone")),
114 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
115 N_("convert to a complete repository"),
116 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
117 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
118 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
119 { OPTION_STRING, 0, "recurse-submodules-default",
120 &recurse_submodules_default, NULL,
121 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
122 OPT_BOOL(0, "update-shallow", &update_shallow,
123 N_("accept refs that update .git/shallow")),
124 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
125 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
126 OPT_END()
129 static void unlock_pack(void)
131 if (gtransport)
132 transport_unlock_pack(gtransport);
133 if (gsecondary)
134 transport_unlock_pack(gsecondary);
137 static void unlock_pack_on_signal(int signo)
139 unlock_pack();
140 sigchain_pop(signo);
141 raise(signo);
144 static void add_merge_config(struct ref **head,
145 const struct ref *remote_refs,
146 struct branch *branch,
147 struct ref ***tail)
149 int i;
151 for (i = 0; i < branch->merge_nr; i++) {
152 struct ref *rm, **old_tail = *tail;
153 struct refspec refspec;
155 for (rm = *head; rm; rm = rm->next) {
156 if (branch_merge_matches(branch, i, rm->name)) {
157 rm->fetch_head_status = FETCH_HEAD_MERGE;
158 break;
161 if (rm)
162 continue;
165 * Not fetched to a remote-tracking branch? We need to fetch
166 * it anyway to allow this branch's "branch.$name.merge"
167 * to be honored by 'git pull', but we do not have to
168 * fail if branch.$name.merge is misconfigured to point
169 * at a nonexisting branch. If we were indeed called by
170 * 'git pull', it will notice the misconfiguration because
171 * there is no entry in the resulting FETCH_HEAD marked
172 * for merging.
174 memset(&refspec, 0, sizeof(refspec));
175 refspec.src = branch->merge[i]->src;
176 get_fetch_map(remote_refs, &refspec, tail, 1);
177 for (rm = *old_tail; rm; rm = rm->next)
178 rm->fetch_head_status = FETCH_HEAD_MERGE;
182 static int add_existing(const char *refname, const unsigned char *sha1,
183 int flag, void *cbdata)
185 struct string_list *list = (struct string_list *)cbdata;
186 struct string_list_item *item = string_list_insert(list, refname);
187 item->util = xmalloc(20);
188 hashcpy(item->util, sha1);
189 return 0;
192 static int will_fetch(struct ref **head, const unsigned char *sha1)
194 struct ref *rm = *head;
195 while (rm) {
196 if (!hashcmp(rm->old_sha1, sha1))
197 return 1;
198 rm = rm->next;
200 return 0;
203 static void find_non_local_tags(struct transport *transport,
204 struct ref **head,
205 struct ref ***tail)
207 struct string_list existing_refs = STRING_LIST_INIT_DUP;
208 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
209 const struct ref *ref;
210 struct string_list_item *item = NULL;
212 for_each_ref(add_existing, &existing_refs);
213 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
214 if (!starts_with(ref->name, "refs/tags/"))
215 continue;
218 * The peeled ref always follows the matching base
219 * ref, so if we see a peeled ref that we don't want
220 * to fetch then we can mark the ref entry in the list
221 * as one to ignore by setting util to NULL.
223 if (ends_with(ref->name, "^{}")) {
224 if (item && !has_sha1_file(ref->old_sha1) &&
225 !will_fetch(head, ref->old_sha1) &&
226 !has_sha1_file(item->util) &&
227 !will_fetch(head, item->util))
228 item->util = NULL;
229 item = NULL;
230 continue;
234 * If item is non-NULL here, then we previously saw a
235 * ref not followed by a peeled reference, so we need
236 * to check if it is a lightweight tag that we want to
237 * fetch.
239 if (item && !has_sha1_file(item->util) &&
240 !will_fetch(head, item->util))
241 item->util = NULL;
243 item = NULL;
245 /* skip duplicates and refs that we already have */
246 if (string_list_has_string(&remote_refs, ref->name) ||
247 string_list_has_string(&existing_refs, ref->name))
248 continue;
250 item = string_list_insert(&remote_refs, ref->name);
251 item->util = (void *)ref->old_sha1;
253 string_list_clear(&existing_refs, 1);
256 * We may have a final lightweight tag that needs to be
257 * checked to see if it needs fetching.
259 if (item && !has_sha1_file(item->util) &&
260 !will_fetch(head, item->util))
261 item->util = NULL;
264 * For all the tags in the remote_refs string list,
265 * add them to the list of refs to be fetched
267 for_each_string_list_item(item, &remote_refs) {
268 /* Unless we have already decided to ignore this item... */
269 if (item->util)
271 struct ref *rm = alloc_ref(item->string);
272 rm->peer_ref = alloc_ref(item->string);
273 hashcpy(rm->old_sha1, item->util);
274 **tail = rm;
275 *tail = &rm->next;
279 string_list_clear(&remote_refs, 0);
282 static struct ref *get_ref_map(struct transport *transport,
283 struct refspec *refspecs, int refspec_count,
284 int tags, int *autotags)
286 int i;
287 struct ref *rm;
288 struct ref *ref_map = NULL;
289 struct ref **tail = &ref_map;
291 /* opportunistically-updated references: */
292 struct ref *orefs = NULL, **oref_tail = &orefs;
294 const struct ref *remote_refs = transport_get_remote_refs(transport);
296 if (refspec_count) {
297 struct refspec *fetch_refspec;
298 int fetch_refspec_nr;
300 for (i = 0; i < refspec_count; i++) {
301 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
302 if (refspecs[i].dst && refspecs[i].dst[0])
303 *autotags = 1;
305 /* Merge everything on the command line (but not --tags) */
306 for (rm = ref_map; rm; rm = rm->next)
307 rm->fetch_head_status = FETCH_HEAD_MERGE;
310 * For any refs that we happen to be fetching via
311 * command-line arguments, the destination ref might
312 * have been missing or have been different than the
313 * remote-tracking ref that would be derived from the
314 * configured refspec. In these cases, we want to
315 * take the opportunity to update their configured
316 * remote-tracking reference. However, we do not want
317 * to mention these entries in FETCH_HEAD at all, as
318 * they would simply be duplicates of existing
319 * entries, so we set them FETCH_HEAD_IGNORE below.
321 * We compute these entries now, based only on the
322 * refspecs specified on the command line. But we add
323 * them to the list following the refspecs resulting
324 * from the tags option so that one of the latter,
325 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
326 * by ref_remove_duplicates() in favor of one of these
327 * opportunistic entries with FETCH_HEAD_IGNORE.
329 if (refmap_array) {
330 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
331 fetch_refspec_nr = refmap_nr;
332 } else {
333 fetch_refspec = transport->remote->fetch;
334 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
337 for (i = 0; i < fetch_refspec_nr; i++)
338 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
340 if (tags == TAGS_SET)
341 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
342 } else if (refmap_array) {
343 die("--refmap option is only meaningful with command-line refspec(s).");
344 } else {
345 /* Use the defaults */
346 struct remote *remote = transport->remote;
347 struct branch *branch = branch_get(NULL);
348 int has_merge = branch_has_merge_config(branch);
349 if (remote &&
350 (remote->fetch_refspec_nr ||
351 /* Note: has_merge implies non-NULL branch->remote_name */
352 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
353 for (i = 0; i < remote->fetch_refspec_nr; i++) {
354 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
355 if (remote->fetch[i].dst &&
356 remote->fetch[i].dst[0])
357 *autotags = 1;
358 if (!i && !has_merge && ref_map &&
359 !remote->fetch[0].pattern)
360 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
363 * if the remote we're fetching from is the same
364 * as given in branch.<name>.remote, we add the
365 * ref given in branch.<name>.merge, too.
367 * Note: has_merge implies non-NULL branch->remote_name
369 if (has_merge &&
370 !strcmp(branch->remote_name, remote->name))
371 add_merge_config(&ref_map, remote_refs, branch, &tail);
372 } else {
373 ref_map = get_remote_ref(remote_refs, "HEAD");
374 if (!ref_map)
375 die(_("Couldn't find remote ref HEAD"));
376 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
377 tail = &ref_map->next;
381 if (tags == TAGS_SET)
382 /* also fetch all tags */
383 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
384 else if (tags == TAGS_DEFAULT && *autotags)
385 find_non_local_tags(transport, &ref_map, &tail);
387 /* Now append any refs to be updated opportunistically: */
388 *tail = orefs;
389 for (rm = orefs; rm; rm = rm->next) {
390 rm->fetch_head_status = FETCH_HEAD_IGNORE;
391 tail = &rm->next;
394 return ref_remove_duplicates(ref_map);
397 #define STORE_REF_ERROR_OTHER 1
398 #define STORE_REF_ERROR_DF_CONFLICT 2
400 static int s_update_ref(const char *action,
401 struct ref *ref,
402 int check_old)
404 char msg[1024];
405 char *rla = getenv("GIT_REFLOG_ACTION");
406 struct ref_transaction *transaction;
407 struct strbuf err = STRBUF_INIT;
408 int ret, df_conflict = 0;
410 if (dry_run)
411 return 0;
412 if (!rla)
413 rla = default_rla.buf;
414 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
416 transaction = ref_transaction_begin(&err);
417 if (!transaction ||
418 ref_transaction_update(transaction, ref->name, ref->new_sha1,
419 ref->old_sha1, 0, check_old, msg, &err))
420 goto fail;
422 ret = ref_transaction_commit(transaction, &err);
423 if (ret) {
424 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
425 goto fail;
428 ref_transaction_free(transaction);
429 strbuf_release(&err);
430 return 0;
431 fail:
432 ref_transaction_free(transaction);
433 error("%s", err.buf);
434 strbuf_release(&err);
435 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
436 : STORE_REF_ERROR_OTHER;
439 #define REFCOL_WIDTH 10
441 static int update_local_ref(struct ref *ref,
442 const char *remote,
443 const struct ref *remote_ref,
444 struct strbuf *display)
446 struct commit *current = NULL, *updated;
447 enum object_type type;
448 struct branch *current_branch = branch_get(NULL);
449 const char *pretty_ref = prettify_refname(ref->name);
451 type = sha1_object_info(ref->new_sha1, NULL);
452 if (type < 0)
453 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
455 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
456 if (verbosity > 0)
457 strbuf_addf(display, "= %-*s %-*s -> %s",
458 TRANSPORT_SUMMARY(_("[up to date]")),
459 REFCOL_WIDTH, remote, pretty_ref);
460 return 0;
463 if (current_branch &&
464 !strcmp(ref->name, current_branch->name) &&
465 !(update_head_ok || is_bare_repository()) &&
466 !is_null_sha1(ref->old_sha1)) {
468 * If this is the head, and it's not okay to update
469 * the head, and the old value of the head isn't empty...
471 strbuf_addf(display,
472 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
473 TRANSPORT_SUMMARY(_("[rejected]")),
474 REFCOL_WIDTH, remote, pretty_ref);
475 return 1;
478 if (!is_null_sha1(ref->old_sha1) &&
479 starts_with(ref->name, "refs/tags/")) {
480 int r;
481 r = s_update_ref("updating tag", ref, 0);
482 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
483 r ? '!' : '-',
484 TRANSPORT_SUMMARY(_("[tag update]")),
485 REFCOL_WIDTH, remote, pretty_ref,
486 r ? _(" (unable to update local ref)") : "");
487 return r;
490 current = lookup_commit_reference_gently(ref->old_sha1, 1);
491 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
492 if (!current || !updated) {
493 const char *msg;
494 const char *what;
495 int r;
497 * Nicely describe the new ref we're fetching.
498 * Base this on the remote's ref name, as it's
499 * more likely to follow a standard layout.
501 const char *name = remote_ref ? remote_ref->name : "";
502 if (starts_with(name, "refs/tags/")) {
503 msg = "storing tag";
504 what = _("[new tag]");
505 } else if (starts_with(name, "refs/heads/")) {
506 msg = "storing head";
507 what = _("[new branch]");
508 } else {
509 msg = "storing ref";
510 what = _("[new ref]");
513 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
514 (recurse_submodules != RECURSE_SUBMODULES_ON))
515 check_for_new_submodule_commits(ref->new_sha1);
516 r = s_update_ref(msg, ref, 0);
517 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
518 r ? '!' : '*',
519 TRANSPORT_SUMMARY(what),
520 REFCOL_WIDTH, remote, pretty_ref,
521 r ? _(" (unable to update local ref)") : "");
522 return r;
525 if (in_merge_bases(current, updated)) {
526 char quickref[83];
527 int r;
528 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
529 strcat(quickref, "..");
530 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
531 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
532 (recurse_submodules != RECURSE_SUBMODULES_ON))
533 check_for_new_submodule_commits(ref->new_sha1);
534 r = s_update_ref("fast-forward", ref, 1);
535 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
536 r ? '!' : ' ',
537 TRANSPORT_SUMMARY_WIDTH, quickref,
538 REFCOL_WIDTH, remote, pretty_ref,
539 r ? _(" (unable to update local ref)") : "");
540 return r;
541 } else if (force || ref->force) {
542 char quickref[84];
543 int r;
544 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
545 strcat(quickref, "...");
546 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
547 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
548 (recurse_submodules != RECURSE_SUBMODULES_ON))
549 check_for_new_submodule_commits(ref->new_sha1);
550 r = s_update_ref("forced-update", ref, 1);
551 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
552 r ? '!' : '+',
553 TRANSPORT_SUMMARY_WIDTH, quickref,
554 REFCOL_WIDTH, remote, pretty_ref,
555 r ? _("unable to update local ref") : _("forced update"));
556 return r;
557 } else {
558 strbuf_addf(display, "! %-*s %-*s -> %s %s",
559 TRANSPORT_SUMMARY(_("[rejected]")),
560 REFCOL_WIDTH, remote, pretty_ref,
561 _("(non-fast-forward)"));
562 return 1;
566 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
568 struct ref **rm = cb_data;
569 struct ref *ref = *rm;
571 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
572 ref = ref->next;
573 if (!ref)
574 return -1; /* end of the list */
575 *rm = ref->next;
576 hashcpy(sha1, ref->old_sha1);
577 return 0;
580 static int store_updated_refs(const char *raw_url, const char *remote_name,
581 struct ref *ref_map)
583 FILE *fp;
584 struct commit *commit;
585 int url_len, i, rc = 0;
586 struct strbuf note = STRBUF_INIT;
587 const char *what, *kind;
588 struct ref *rm;
589 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
590 int want_status;
592 fp = fopen(filename, "a");
593 if (!fp)
594 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
596 if (raw_url)
597 url = transport_anonymize_url(raw_url);
598 else
599 url = xstrdup("foreign");
601 rm = ref_map;
602 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
603 rc = error(_("%s did not send all necessary objects\n"), url);
604 goto abort;
608 * We do a pass for each fetch_head_status type in their enum order, so
609 * merged entries are written before not-for-merge. That lets readers
610 * use FETCH_HEAD as a refname to refer to the ref to be merged.
612 for (want_status = FETCH_HEAD_MERGE;
613 want_status <= FETCH_HEAD_IGNORE;
614 want_status++) {
615 for (rm = ref_map; rm; rm = rm->next) {
616 struct ref *ref = NULL;
617 const char *merge_status_marker = "";
619 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
620 if (want_status == FETCH_HEAD_MERGE)
621 warning(_("reject %s because shallow roots are not allowed to be updated"),
622 rm->peer_ref ? rm->peer_ref->name : rm->name);
623 continue;
626 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
627 if (!commit)
628 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
630 if (rm->fetch_head_status != want_status)
631 continue;
633 if (rm->peer_ref) {
634 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
635 strcpy(ref->name, rm->peer_ref->name);
636 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
637 hashcpy(ref->new_sha1, rm->old_sha1);
638 ref->force = rm->peer_ref->force;
642 if (!strcmp(rm->name, "HEAD")) {
643 kind = "";
644 what = "";
646 else if (starts_with(rm->name, "refs/heads/")) {
647 kind = "branch";
648 what = rm->name + 11;
650 else if (starts_with(rm->name, "refs/tags/")) {
651 kind = "tag";
652 what = rm->name + 10;
654 else if (starts_with(rm->name, "refs/remotes/")) {
655 kind = "remote-tracking branch";
656 what = rm->name + 13;
658 else {
659 kind = "";
660 what = rm->name;
663 url_len = strlen(url);
664 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
666 url_len = i + 1;
667 if (4 < i && !strncmp(".git", url + i - 3, 4))
668 url_len = i - 3;
670 strbuf_reset(&note);
671 if (*what) {
672 if (*kind)
673 strbuf_addf(&note, "%s ", kind);
674 strbuf_addf(&note, "'%s' of ", what);
676 switch (rm->fetch_head_status) {
677 case FETCH_HEAD_NOT_FOR_MERGE:
678 merge_status_marker = "not-for-merge";
679 /* fall-through */
680 case FETCH_HEAD_MERGE:
681 fprintf(fp, "%s\t%s\t%s",
682 sha1_to_hex(rm->old_sha1),
683 merge_status_marker,
684 note.buf);
685 for (i = 0; i < url_len; ++i)
686 if ('\n' == url[i])
687 fputs("\\n", fp);
688 else
689 fputc(url[i], fp);
690 fputc('\n', fp);
691 break;
692 default:
693 /* do not write anything to FETCH_HEAD */
694 break;
697 strbuf_reset(&note);
698 if (ref) {
699 rc |= update_local_ref(ref, what, rm, &note);
700 free(ref);
701 } else
702 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
703 TRANSPORT_SUMMARY_WIDTH,
704 *kind ? kind : "branch",
705 REFCOL_WIDTH,
706 *what ? what : "HEAD");
707 if (note.len) {
708 if (verbosity >= 0 && !shown_url) {
709 fprintf(stderr, _("From %.*s\n"),
710 url_len, url);
711 shown_url = 1;
713 if (verbosity >= 0)
714 fprintf(stderr, " %s\n", note.buf);
719 if (rc & STORE_REF_ERROR_DF_CONFLICT)
720 error(_("some local refs could not be updated; try running\n"
721 " 'git remote prune %s' to remove any old, conflicting "
722 "branches"), remote_name);
724 abort:
725 strbuf_release(&note);
726 free(url);
727 fclose(fp);
728 return rc;
732 * We would want to bypass the object transfer altogether if
733 * everything we are going to fetch already exists and is connected
734 * locally.
736 static int quickfetch(struct ref *ref_map)
738 struct ref *rm = ref_map;
741 * If we are deepening a shallow clone we already have these
742 * objects reachable. Running rev-list here will return with
743 * a good (0) exit status and we'll bypass the fetch that we
744 * really need to perform. Claiming failure now will ensure
745 * we perform the network exchange to deepen our history.
747 if (depth)
748 return -1;
749 return check_everything_connected(iterate_ref_map, 1, &rm);
752 static int fetch_refs(struct transport *transport, struct ref *ref_map)
754 int ret = quickfetch(ref_map);
755 if (ret)
756 ret = transport_fetch_refs(transport, ref_map);
757 if (!ret)
758 ret |= store_updated_refs(transport->url,
759 transport->remote->name,
760 ref_map);
761 transport_unlock_pack(transport);
762 return ret;
765 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
766 const char *raw_url)
768 int url_len, i, result = 0;
769 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
770 char *url;
771 const char *dangling_msg = dry_run
772 ? _(" (%s will become dangling)")
773 : _(" (%s has become dangling)");
775 if (raw_url)
776 url = transport_anonymize_url(raw_url);
777 else
778 url = xstrdup("foreign");
780 url_len = strlen(url);
781 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
784 url_len = i + 1;
785 if (4 < i && !strncmp(".git", url + i - 3, 4))
786 url_len = i - 3;
788 for (ref = stale_refs; ref; ref = ref->next) {
789 if (!dry_run)
790 result |= delete_ref(ref->name, NULL, 0);
791 if (verbosity >= 0 && !shown_url) {
792 fprintf(stderr, _("From %.*s\n"), url_len, url);
793 shown_url = 1;
795 if (verbosity >= 0) {
796 fprintf(stderr, " x %-*s %-*s -> %s\n",
797 TRANSPORT_SUMMARY(_("[deleted]")),
798 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
799 warn_dangling_symref(stderr, dangling_msg, ref->name);
802 free(url);
803 free_refs(stale_refs);
804 return result;
807 static void check_not_current_branch(struct ref *ref_map)
809 struct branch *current_branch = branch_get(NULL);
811 if (is_bare_repository() || !current_branch)
812 return;
814 for (; ref_map; ref_map = ref_map->next)
815 if (ref_map->peer_ref && !strcmp(current_branch->refname,
816 ref_map->peer_ref->name))
817 die(_("Refusing to fetch into current branch %s "
818 "of non-bare repository"), current_branch->refname);
821 static int truncate_fetch_head(void)
823 char *filename = git_path("FETCH_HEAD");
824 FILE *fp = fopen(filename, "w");
826 if (!fp)
827 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
828 fclose(fp);
829 return 0;
832 static void set_option(struct transport *transport, const char *name, const char *value)
834 int r = transport_set_option(transport, name, value);
835 if (r < 0)
836 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
837 name, value, transport->url);
838 if (r > 0)
839 warning(_("Option \"%s\" is ignored for %s\n"),
840 name, transport->url);
843 static struct transport *prepare_transport(struct remote *remote)
845 struct transport *transport;
846 transport = transport_get(remote, NULL);
847 transport_set_verbosity(transport, verbosity, progress);
848 if (upload_pack)
849 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
850 if (keep)
851 set_option(transport, TRANS_OPT_KEEP, "yes");
852 if (depth)
853 set_option(transport, TRANS_OPT_DEPTH, depth);
854 if (update_shallow)
855 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
856 return transport;
859 static void backfill_tags(struct transport *transport, struct ref *ref_map)
861 if (transport->cannot_reuse) {
862 gsecondary = prepare_transport(transport->remote);
863 transport = gsecondary;
866 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
867 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
868 fetch_refs(transport, ref_map);
870 if (gsecondary) {
871 transport_disconnect(gsecondary);
872 gsecondary = NULL;
876 static int do_fetch(struct transport *transport,
877 struct refspec *refs, int ref_count)
879 struct string_list existing_refs = STRING_LIST_INIT_DUP;
880 struct ref *ref_map;
881 struct ref *rm;
882 int autotags = (transport->remote->fetch_tags == 1);
883 int retcode = 0;
885 for_each_ref(add_existing, &existing_refs);
887 if (tags == TAGS_DEFAULT) {
888 if (transport->remote->fetch_tags == 2)
889 tags = TAGS_SET;
890 if (transport->remote->fetch_tags == -1)
891 tags = TAGS_UNSET;
894 if (!transport->get_refs_list || !transport->fetch)
895 die(_("Don't know how to fetch from %s"), transport->url);
897 /* if not appending, truncate FETCH_HEAD */
898 if (!append && !dry_run) {
899 retcode = truncate_fetch_head();
900 if (retcode)
901 goto cleanup;
904 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
905 if (!update_head_ok)
906 check_not_current_branch(ref_map);
908 for (rm = ref_map; rm; rm = rm->next) {
909 if (rm->peer_ref) {
910 struct string_list_item *peer_item =
911 string_list_lookup(&existing_refs,
912 rm->peer_ref->name);
913 if (peer_item)
914 hashcpy(rm->peer_ref->old_sha1,
915 peer_item->util);
919 if (tags == TAGS_DEFAULT && autotags)
920 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
921 if (prune) {
923 * We only prune based on refspecs specified
924 * explicitly (via command line or configuration); we
925 * don't care whether --tags was specified.
927 if (ref_count) {
928 prune_refs(refs, ref_count, ref_map, transport->url);
929 } else {
930 prune_refs(transport->remote->fetch,
931 transport->remote->fetch_refspec_nr,
932 ref_map,
933 transport->url);
936 if (fetch_refs(transport, ref_map)) {
937 free_refs(ref_map);
938 retcode = 1;
939 goto cleanup;
941 free_refs(ref_map);
943 /* if neither --no-tags nor --tags was specified, do automated tag
944 * following ... */
945 if (tags == TAGS_DEFAULT && autotags) {
946 struct ref **tail = &ref_map;
947 ref_map = NULL;
948 find_non_local_tags(transport, &ref_map, &tail);
949 if (ref_map)
950 backfill_tags(transport, ref_map);
951 free_refs(ref_map);
954 cleanup:
955 string_list_clear(&existing_refs, 1);
956 return retcode;
959 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
961 struct string_list *list = priv;
962 if (!remote->skip_default_update)
963 string_list_append(list, remote->name);
964 return 0;
967 struct remote_group_data {
968 const char *name;
969 struct string_list *list;
972 static int get_remote_group(const char *key, const char *value, void *priv)
974 struct remote_group_data *g = priv;
976 if (starts_with(key, "remotes.") &&
977 !strcmp(key + 8, g->name)) {
978 /* split list by white space */
979 int space = strcspn(value, " \t\n");
980 while (*value) {
981 if (space > 1) {
982 string_list_append(g->list,
983 xstrndup(value, space));
985 value += space + (value[space] != '\0');
986 space = strcspn(value, " \t\n");
990 return 0;
993 static int add_remote_or_group(const char *name, struct string_list *list)
995 int prev_nr = list->nr;
996 struct remote_group_data g;
997 g.name = name; g.list = list;
999 git_config(get_remote_group, &g);
1000 if (list->nr == prev_nr) {
1001 struct remote *remote;
1002 if (!remote_is_configured(name))
1003 return 0;
1004 remote = remote_get(name);
1005 string_list_append(list, remote->name);
1007 return 1;
1010 static void add_options_to_argv(struct argv_array *argv)
1012 if (dry_run)
1013 argv_array_push(argv, "--dry-run");
1014 if (prune != -1)
1015 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1016 if (update_head_ok)
1017 argv_array_push(argv, "--update-head-ok");
1018 if (force)
1019 argv_array_push(argv, "--force");
1020 if (keep)
1021 argv_array_push(argv, "--keep");
1022 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1023 argv_array_push(argv, "--recurse-submodules");
1024 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1025 argv_array_push(argv, "--recurse-submodules=on-demand");
1026 if (tags == TAGS_SET)
1027 argv_array_push(argv, "--tags");
1028 else if (tags == TAGS_UNSET)
1029 argv_array_push(argv, "--no-tags");
1030 if (verbosity >= 2)
1031 argv_array_push(argv, "-v");
1032 if (verbosity >= 1)
1033 argv_array_push(argv, "-v");
1034 else if (verbosity < 0)
1035 argv_array_push(argv, "-q");
1039 static int fetch_multiple(struct string_list *list)
1041 int i, result = 0;
1042 struct argv_array argv = ARGV_ARRAY_INIT;
1044 if (!append && !dry_run) {
1045 int errcode = truncate_fetch_head();
1046 if (errcode)
1047 return errcode;
1050 argv_array_pushl(&argv, "fetch", "--append", NULL);
1051 add_options_to_argv(&argv);
1053 for (i = 0; i < list->nr; i++) {
1054 const char *name = list->items[i].string;
1055 argv_array_push(&argv, name);
1056 if (verbosity >= 0)
1057 printf(_("Fetching %s\n"), name);
1058 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1059 error(_("Could not fetch %s"), name);
1060 result = 1;
1062 argv_array_pop(&argv);
1065 argv_array_clear(&argv);
1066 return result;
1069 static int fetch_one(struct remote *remote, int argc, const char **argv)
1071 static const char **refs = NULL;
1072 struct refspec *refspec;
1073 int ref_nr = 0;
1074 int exit_code;
1076 if (!remote)
1077 die(_("No remote repository specified. Please, specify either a URL or a\n"
1078 "remote name from which new revisions should be fetched."));
1080 gtransport = prepare_transport(remote);
1082 if (prune < 0) {
1083 /* no command line request */
1084 if (0 <= gtransport->remote->prune)
1085 prune = gtransport->remote->prune;
1086 else if (0 <= fetch_prune_config)
1087 prune = fetch_prune_config;
1088 else
1089 prune = PRUNE_BY_DEFAULT;
1092 if (argc > 0) {
1093 int j = 0;
1094 int i;
1095 refs = xcalloc(argc + 1, sizeof(const char *));
1096 for (i = 0; i < argc; i++) {
1097 if (!strcmp(argv[i], "tag")) {
1098 i++;
1099 if (i >= argc)
1100 die(_("You need to specify a tag name."));
1101 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1102 argv[i], argv[i]);
1103 } else
1104 refs[j++] = argv[i];
1106 refs[j] = NULL;
1107 ref_nr = j;
1110 sigchain_push_common(unlock_pack_on_signal);
1111 atexit(unlock_pack);
1112 refspec = parse_fetch_refspec(ref_nr, refs);
1113 exit_code = do_fetch(gtransport, refspec, ref_nr);
1114 free_refspec(ref_nr, refspec);
1115 transport_disconnect(gtransport);
1116 gtransport = NULL;
1117 return exit_code;
1120 int cmd_fetch(int argc, const char **argv, const char *prefix)
1122 int i;
1123 struct string_list list = STRING_LIST_INIT_NODUP;
1124 struct remote *remote;
1125 int result = 0;
1126 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1128 packet_trace_identity("fetch");
1130 /* Record the command line for the reflog */
1131 strbuf_addstr(&default_rla, "fetch");
1132 for (i = 1; i < argc; i++)
1133 strbuf_addf(&default_rla, " %s", argv[i]);
1135 git_config(git_fetch_config, NULL);
1137 argc = parse_options(argc, argv, prefix,
1138 builtin_fetch_options, builtin_fetch_usage, 0);
1140 if (unshallow) {
1141 if (depth)
1142 die(_("--depth and --unshallow cannot be used together"));
1143 else if (!is_repository_shallow())
1144 die(_("--unshallow on a complete repository does not make sense"));
1145 else {
1146 static char inf_depth[12];
1147 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1148 depth = inf_depth;
1152 /* no need to be strict, transport_set_option() will validate it again */
1153 if (depth && atoi(depth) < 1)
1154 die(_("depth %s is not a positive number"), depth);
1156 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1157 if (recurse_submodules_default) {
1158 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1159 set_config_fetch_recurse_submodules(arg);
1161 gitmodules_config();
1162 git_config(submodule_config, NULL);
1165 if (all) {
1166 if (argc == 1)
1167 die(_("fetch --all does not take a repository argument"));
1168 else if (argc > 1)
1169 die(_("fetch --all does not make sense with refspecs"));
1170 (void) for_each_remote(get_one_remote_for_fetch, &list);
1171 result = fetch_multiple(&list);
1172 } else if (argc == 0) {
1173 /* No arguments -- use default remote */
1174 remote = remote_get(NULL);
1175 result = fetch_one(remote, argc, argv);
1176 } else if (multiple) {
1177 /* All arguments are assumed to be remotes or groups */
1178 for (i = 0; i < argc; i++)
1179 if (!add_remote_or_group(argv[i], &list))
1180 die(_("No such remote or remote group: %s"), argv[i]);
1181 result = fetch_multiple(&list);
1182 } else {
1183 /* Single remote or group */
1184 (void) add_remote_or_group(argv[0], &list);
1185 if (list.nr > 1) {
1186 /* More than one remote */
1187 if (argc > 1)
1188 die(_("Fetching a group and specifying refspecs does not make sense"));
1189 result = fetch_multiple(&list);
1190 } else {
1191 /* Zero or one remotes */
1192 remote = remote_get(argv[0]);
1193 result = fetch_one(remote, argc-1, argv+1);
1197 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1198 struct argv_array options = ARGV_ARRAY_INIT;
1200 add_options_to_argv(&options);
1201 result = fetch_populated_submodules(&options,
1202 submodule_prefix,
1203 recurse_submodules,
1204 verbosity < 0);
1205 argv_array_clear(&options);
1208 /* All names were strdup()ed or strndup()ed */
1209 list.strdup_strings = 1;
1210 string_list_clear(&list, 0);
1212 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1213 if (verbosity < 0)
1214 argv_array_push(&argv_gc_auto, "--quiet");
1215 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1216 argv_array_clear(&argv_gc_auto);
1218 return result;