8 #include "string-list.h"
10 #include "transport.h"
11 #include "run-command.h"
12 #include "parse-options.h"
14 #include "submodule-config.h"
15 #include "submodule.h"
16 #include "connected.h"
17 #include "argv-array.h"
20 #define TRANSPORT_SUMMARY(x) \
21 (int)(TRANSPORT_SUMMARY_WIDTH + strlen(x) - gettext_width(x)), (x)
23 static const char * const builtin_fetch_usage[] = {
24 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
25 N_("git fetch [<options>] <group>"),
26 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
27 N_("git fetch --all [<options>]"),
37 static int fetch_prune_config = -1; /* unspecified */
38 static int prune = -1; /* unspecified */
39 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
41 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
42 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
43 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
44 static int max_children = -1;
45 static enum transport_family family;
46 static const char *depth;
47 static const char *deepen_since;
48 static const char *upload_pack;
49 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
50 static struct strbuf default_rla = STRBUF_INIT;
51 static struct transport *gtransport;
52 static struct transport *gsecondary;
53 static const char *submodule_prefix = "";
54 static const char *recurse_submodules_default;
55 static int shown_url = 0;
56 static int refmap_alloc, refmap_nr;
57 static const char **refmap_array;
59 static int option_parse_recurse_submodules(const struct option *opt,
60 const char *arg, int unset)
63 recurse_submodules = RECURSE_SUBMODULES_OFF;
66 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
68 recurse_submodules = RECURSE_SUBMODULES_ON;
73 static int git_fetch_config(const char *k, const char *v, void *cb)
75 if (!strcmp(k, "fetch.prune")) {
76 fetch_prune_config = git_config_bool(k, v);
79 return git_default_config(k, v, cb);
82 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
84 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
87 * "git fetch --refmap='' origin foo"
88 * can be used to tell the command not to store anywhere
91 refmap_array[refmap_nr++] = arg;
95 static struct option builtin_fetch_options[] = {
96 OPT__VERBOSITY(&verbosity),
97 OPT_BOOL(0, "all", &all,
98 N_("fetch from all remotes")),
99 OPT_BOOL('a', "append", &append,
100 N_("append to .git/FETCH_HEAD instead of overwriting")),
101 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
102 N_("path to upload pack on remote end")),
103 OPT__FORCE(&force, N_("force overwrite of local branch")),
104 OPT_BOOL('m', "multiple", &multiple,
105 N_("fetch from multiple remotes")),
106 OPT_SET_INT('t', "tags", &tags,
107 N_("fetch all tags and associated objects"), TAGS_SET),
108 OPT_SET_INT('n', NULL, &tags,
109 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
110 OPT_INTEGER('j', "jobs", &max_children,
111 N_("number of submodules fetched in parallel")),
112 OPT_BOOL('p', "prune", &prune,
113 N_("prune remote-tracking branches no longer on remote")),
114 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
115 N_("control recursive fetching of submodules"),
116 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
117 OPT_BOOL(0, "dry-run", &dry_run,
119 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
120 OPT_BOOL('u', "update-head-ok", &update_head_ok,
121 N_("allow updating of HEAD ref")),
122 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
123 OPT_STRING(0, "depth", &depth, N_("depth"),
124 N_("deepen history of shallow clone")),
125 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
126 N_("deepen history of shallow repository based on time")),
127 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
128 N_("deepen history of shallow clone by excluding rev")),
129 OPT_INTEGER(0, "deepen", &deepen_relative,
130 N_("deepen history of shallow clone")),
131 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
132 N_("convert to a complete repository"),
133 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
134 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
135 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
136 { OPTION_STRING, 0, "recurse-submodules-default",
137 &recurse_submodules_default, NULL,
138 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
139 OPT_BOOL(0, "update-shallow", &update_shallow,
140 N_("accept refs that update .git/shallow")),
141 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
142 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
143 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
144 TRANSPORT_FAMILY_IPV4),
145 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
146 TRANSPORT_FAMILY_IPV6),
150 static void unlock_pack(void)
153 transport_unlock_pack(gtransport);
155 transport_unlock_pack(gsecondary);
158 static void unlock_pack_on_signal(int signo)
165 static void add_merge_config(struct ref **head,
166 const struct ref *remote_refs,
167 struct branch *branch,
172 for (i = 0; i < branch->merge_nr; i++) {
173 struct ref *rm, **old_tail = *tail;
174 struct refspec refspec;
176 for (rm = *head; rm; rm = rm->next) {
177 if (branch_merge_matches(branch, i, rm->name)) {
178 rm->fetch_head_status = FETCH_HEAD_MERGE;
186 * Not fetched to a remote-tracking branch? We need to fetch
187 * it anyway to allow this branch's "branch.$name.merge"
188 * to be honored by 'git pull', but we do not have to
189 * fail if branch.$name.merge is misconfigured to point
190 * at a nonexisting branch. If we were indeed called by
191 * 'git pull', it will notice the misconfiguration because
192 * there is no entry in the resulting FETCH_HEAD marked
195 memset(&refspec, 0, sizeof(refspec));
196 refspec.src = branch->merge[i]->src;
197 get_fetch_map(remote_refs, &refspec, tail, 1);
198 for (rm = *old_tail; rm; rm = rm->next)
199 rm->fetch_head_status = FETCH_HEAD_MERGE;
203 static int add_existing(const char *refname, const struct object_id *oid,
204 int flag, void *cbdata)
206 struct string_list *list = (struct string_list *)cbdata;
207 struct string_list_item *item = string_list_insert(list, refname);
208 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
210 oidcpy(old_oid, oid);
211 item->util = old_oid;
215 static int will_fetch(struct ref **head, const unsigned char *sha1)
217 struct ref *rm = *head;
219 if (!hashcmp(rm->old_oid.hash, sha1))
226 static void find_non_local_tags(struct transport *transport,
230 struct string_list existing_refs = STRING_LIST_INIT_DUP;
231 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
232 const struct ref *ref;
233 struct string_list_item *item = NULL;
235 for_each_ref(add_existing, &existing_refs);
236 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
237 if (!starts_with(ref->name, "refs/tags/"))
241 * The peeled ref always follows the matching base
242 * ref, so if we see a peeled ref that we don't want
243 * to fetch then we can mark the ref entry in the list
244 * as one to ignore by setting util to NULL.
246 if (ends_with(ref->name, "^{}")) {
248 !has_object_file_with_flags(&ref->old_oid, HAS_SHA1_QUICK) &&
249 !will_fetch(head, ref->old_oid.hash) &&
250 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
251 !will_fetch(head, item->util))
258 * If item is non-NULL here, then we previously saw a
259 * ref not followed by a peeled reference, so we need
260 * to check if it is a lightweight tag that we want to
264 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
265 !will_fetch(head, item->util))
270 /* skip duplicates and refs that we already have */
271 if (string_list_has_string(&remote_refs, ref->name) ||
272 string_list_has_string(&existing_refs, ref->name))
275 item = string_list_insert(&remote_refs, ref->name);
276 item->util = (void *)&ref->old_oid;
278 string_list_clear(&existing_refs, 1);
281 * We may have a final lightweight tag that needs to be
282 * checked to see if it needs fetching.
285 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
286 !will_fetch(head, item->util))
290 * For all the tags in the remote_refs string list,
291 * add them to the list of refs to be fetched
293 for_each_string_list_item(item, &remote_refs) {
294 /* Unless we have already decided to ignore this item... */
297 struct ref *rm = alloc_ref(item->string);
298 rm->peer_ref = alloc_ref(item->string);
299 oidcpy(&rm->old_oid, item->util);
305 string_list_clear(&remote_refs, 0);
308 static struct ref *get_ref_map(struct transport *transport,
309 struct refspec *refspecs, int refspec_count,
310 int tags, int *autotags)
314 struct ref *ref_map = NULL;
315 struct ref **tail = &ref_map;
317 /* opportunistically-updated references: */
318 struct ref *orefs = NULL, **oref_tail = &orefs;
320 const struct ref *remote_refs = transport_get_remote_refs(transport);
323 struct refspec *fetch_refspec;
324 int fetch_refspec_nr;
326 for (i = 0; i < refspec_count; i++) {
327 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
328 if (refspecs[i].dst && refspecs[i].dst[0])
331 /* Merge everything on the command line (but not --tags) */
332 for (rm = ref_map; rm; rm = rm->next)
333 rm->fetch_head_status = FETCH_HEAD_MERGE;
336 * For any refs that we happen to be fetching via
337 * command-line arguments, the destination ref might
338 * have been missing or have been different than the
339 * remote-tracking ref that would be derived from the
340 * configured refspec. In these cases, we want to
341 * take the opportunity to update their configured
342 * remote-tracking reference. However, we do not want
343 * to mention these entries in FETCH_HEAD at all, as
344 * they would simply be duplicates of existing
345 * entries, so we set them FETCH_HEAD_IGNORE below.
347 * We compute these entries now, based only on the
348 * refspecs specified on the command line. But we add
349 * them to the list following the refspecs resulting
350 * from the tags option so that one of the latter,
351 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
352 * by ref_remove_duplicates() in favor of one of these
353 * opportunistic entries with FETCH_HEAD_IGNORE.
356 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
357 fetch_refspec_nr = refmap_nr;
359 fetch_refspec = transport->remote->fetch;
360 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
363 for (i = 0; i < fetch_refspec_nr; i++)
364 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
366 if (tags == TAGS_SET)
367 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
368 } else if (refmap_array) {
369 die("--refmap option is only meaningful with command-line refspec(s).");
371 /* Use the defaults */
372 struct remote *remote = transport->remote;
373 struct branch *branch = branch_get(NULL);
374 int has_merge = branch_has_merge_config(branch);
376 (remote->fetch_refspec_nr ||
377 /* Note: has_merge implies non-NULL branch->remote_name */
378 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
379 for (i = 0; i < remote->fetch_refspec_nr; i++) {
380 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
381 if (remote->fetch[i].dst &&
382 remote->fetch[i].dst[0])
384 if (!i && !has_merge && ref_map &&
385 !remote->fetch[0].pattern)
386 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
389 * if the remote we're fetching from is the same
390 * as given in branch.<name>.remote, we add the
391 * ref given in branch.<name>.merge, too.
393 * Note: has_merge implies non-NULL branch->remote_name
396 !strcmp(branch->remote_name, remote->name))
397 add_merge_config(&ref_map, remote_refs, branch, &tail);
399 ref_map = get_remote_ref(remote_refs, "HEAD");
401 die(_("Couldn't find remote ref HEAD"));
402 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
403 tail = &ref_map->next;
407 if (tags == TAGS_SET)
408 /* also fetch all tags */
409 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
410 else if (tags == TAGS_DEFAULT && *autotags)
411 find_non_local_tags(transport, &ref_map, &tail);
413 /* Now append any refs to be updated opportunistically: */
415 for (rm = orefs; rm; rm = rm->next) {
416 rm->fetch_head_status = FETCH_HEAD_IGNORE;
420 return ref_remove_duplicates(ref_map);
423 #define STORE_REF_ERROR_OTHER 1
424 #define STORE_REF_ERROR_DF_CONFLICT 2
426 static int s_update_ref(const char *action,
431 char *rla = getenv("GIT_REFLOG_ACTION");
432 struct ref_transaction *transaction;
433 struct strbuf err = STRBUF_INIT;
434 int ret, df_conflict = 0;
439 rla = default_rla.buf;
440 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
442 transaction = ref_transaction_begin(&err);
444 ref_transaction_update(transaction, ref->name,
446 check_old ? ref->old_oid.hash : NULL,
450 ret = ref_transaction_commit(transaction, &err);
452 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
456 ref_transaction_free(transaction);
457 strbuf_release(&err);
460 ref_transaction_free(transaction);
461 error("%s", err.buf);
462 strbuf_release(&err);
463 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
464 : STORE_REF_ERROR_OTHER;
467 static int refcol_width = 10;
468 static int compact_format;
470 static void adjust_refcol_width(const struct ref *ref)
472 int max, rlen, llen, len;
474 /* uptodate lines are only shown on high verbosity level */
475 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
478 max = term_columns();
479 rlen = utf8_strwidth(prettify_refname(ref->name));
481 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
484 * rough estimation to see if the output line is too long and
485 * should not be counted (we can't do precise calculation
486 * anyway because we don't know if the error explanation part
487 * will be printed in update_local_ref)
489 if (compact_format) {
493 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
498 * Not precise calculation for compact mode because '*' can
499 * appear on the left hand side of '->' and shrink the column
502 if (refcol_width < rlen)
506 static void prepare_format_display(struct ref *ref_map)
509 const char *format = "full";
511 git_config_get_string_const("fetch.output", &format);
512 if (!strcasecmp(format, "full"))
514 else if (!strcasecmp(format, "compact"))
517 die(_("configuration fetch.output contains invalid value %s"),
520 for (rm = ref_map; rm; rm = rm->next) {
521 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
523 !strcmp(rm->name, "HEAD"))
526 adjust_refcol_width(rm);
530 static void print_remote_to_local(struct strbuf *display,
531 const char *remote, const char *local)
533 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
536 static int find_and_replace(struct strbuf *haystack,
538 const char *placeholder)
540 const char *p = strstr(haystack->buf, needle);
546 if (p > haystack->buf && p[-1] != '/')
550 nlen = strlen(needle);
551 if (plen > nlen && p[nlen] != '/')
554 strbuf_splice(haystack, p - haystack->buf, nlen,
555 placeholder, strlen(placeholder));
559 static void print_compact(struct strbuf *display,
560 const char *remote, const char *local)
562 struct strbuf r = STRBUF_INIT;
563 struct strbuf l = STRBUF_INIT;
565 if (!strcmp(remote, local)) {
566 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
570 strbuf_addstr(&r, remote);
571 strbuf_addstr(&l, local);
573 if (!find_and_replace(&r, local, "*"))
574 find_and_replace(&l, remote, "*");
575 print_remote_to_local(display, r.buf, l.buf);
581 static void format_display(struct strbuf *display, char code,
582 const char *summary, const char *error,
583 const char *remote, const char *local)
585 strbuf_addf(display, "%c %-*s ", code, TRANSPORT_SUMMARY(summary));
587 print_remote_to_local(display, remote, local);
589 print_compact(display, remote, local);
591 strbuf_addf(display, " (%s)", error);
594 static int update_local_ref(struct ref *ref,
596 const struct ref *remote_ref,
597 struct strbuf *display)
599 struct commit *current = NULL, *updated;
600 enum object_type type;
601 struct branch *current_branch = branch_get(NULL);
602 const char *pretty_ref = prettify_refname(ref->name);
604 type = sha1_object_info(ref->new_oid.hash, NULL);
606 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
608 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
610 format_display(display, '=', _("[up to date]"), NULL,
615 if (current_branch &&
616 !strcmp(ref->name, current_branch->name) &&
617 !(update_head_ok || is_bare_repository()) &&
618 !is_null_oid(&ref->old_oid)) {
620 * If this is the head, and it's not okay to update
621 * the head, and the old value of the head isn't empty...
623 format_display(display, '!', _("[rejected]"),
624 _("can't fetch in current branch"),
629 if (!is_null_oid(&ref->old_oid) &&
630 starts_with(ref->name, "refs/tags/")) {
632 r = s_update_ref("updating tag", ref, 0);
633 format_display(display, r ? '!' : 't', _("[tag update]"),
634 r ? _("unable to update local ref") : NULL,
639 current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
640 updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
641 if (!current || !updated) {
646 * Nicely describe the new ref we're fetching.
647 * Base this on the remote's ref name, as it's
648 * more likely to follow a standard layout.
650 const char *name = remote_ref ? remote_ref->name : "";
651 if (starts_with(name, "refs/tags/")) {
653 what = _("[new tag]");
654 } else if (starts_with(name, "refs/heads/")) {
655 msg = "storing head";
656 what = _("[new branch]");
659 what = _("[new ref]");
662 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
663 (recurse_submodules != RECURSE_SUBMODULES_ON))
664 check_for_new_submodule_commits(ref->new_oid.hash);
665 r = s_update_ref(msg, ref, 0);
666 format_display(display, r ? '!' : '*', what,
667 r ? _("unable to update local ref") : NULL,
672 if (in_merge_bases(current, updated)) {
673 struct strbuf quickref = STRBUF_INIT;
675 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
676 strbuf_addstr(&quickref, "..");
677 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
678 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
679 (recurse_submodules != RECURSE_SUBMODULES_ON))
680 check_for_new_submodule_commits(ref->new_oid.hash);
681 r = s_update_ref("fast-forward", ref, 1);
682 format_display(display, r ? '!' : ' ', quickref.buf,
683 r ? _("unable to update local ref") : NULL,
685 strbuf_release(&quickref);
687 } else if (force || ref->force) {
688 struct strbuf quickref = STRBUF_INIT;
690 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
691 strbuf_addstr(&quickref, "...");
692 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
693 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
694 (recurse_submodules != RECURSE_SUBMODULES_ON))
695 check_for_new_submodule_commits(ref->new_oid.hash);
696 r = s_update_ref("forced-update", ref, 1);
697 format_display(display, r ? '!' : '+', quickref.buf,
698 r ? _("unable to update local ref") : _("forced update"),
700 strbuf_release(&quickref);
703 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
709 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
711 struct ref **rm = cb_data;
712 struct ref *ref = *rm;
714 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
717 return -1; /* end of the list */
719 hashcpy(sha1, ref->old_oid.hash);
723 static int store_updated_refs(const char *raw_url, const char *remote_name,
727 struct commit *commit;
728 int url_len, i, rc = 0;
729 struct strbuf note = STRBUF_INIT;
730 const char *what, *kind;
733 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
736 fp = fopen(filename, "a");
738 return error_errno(_("cannot open %s"), filename);
741 url = transport_anonymize_url(raw_url);
743 url = xstrdup("foreign");
746 if (check_connected(iterate_ref_map, &rm, NULL)) {
747 rc = error(_("%s did not send all necessary objects\n"), url);
751 prepare_format_display(ref_map);
754 * We do a pass for each fetch_head_status type in their enum order, so
755 * merged entries are written before not-for-merge. That lets readers
756 * use FETCH_HEAD as a refname to refer to the ref to be merged.
758 for (want_status = FETCH_HEAD_MERGE;
759 want_status <= FETCH_HEAD_IGNORE;
761 for (rm = ref_map; rm; rm = rm->next) {
762 struct ref *ref = NULL;
763 const char *merge_status_marker = "";
765 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
766 if (want_status == FETCH_HEAD_MERGE)
767 warning(_("reject %s because shallow roots are not allowed to be updated"),
768 rm->peer_ref ? rm->peer_ref->name : rm->name);
772 commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
774 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
776 if (rm->fetch_head_status != want_status)
780 ref = alloc_ref(rm->peer_ref->name);
781 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
782 oidcpy(&ref->new_oid, &rm->old_oid);
783 ref->force = rm->peer_ref->force;
787 if (!strcmp(rm->name, "HEAD")) {
791 else if (starts_with(rm->name, "refs/heads/")) {
793 what = rm->name + 11;
795 else if (starts_with(rm->name, "refs/tags/")) {
797 what = rm->name + 10;
799 else if (starts_with(rm->name, "refs/remotes/")) {
800 kind = "remote-tracking branch";
801 what = rm->name + 13;
808 url_len = strlen(url);
809 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
812 if (4 < i && !strncmp(".git", url + i - 3, 4))
818 strbuf_addf(¬e, "%s ", kind);
819 strbuf_addf(¬e, "'%s' of ", what);
821 switch (rm->fetch_head_status) {
822 case FETCH_HEAD_NOT_FOR_MERGE:
823 merge_status_marker = "not-for-merge";
825 case FETCH_HEAD_MERGE:
826 fprintf(fp, "%s\t%s\t%s",
827 oid_to_hex(&rm->old_oid),
830 for (i = 0; i < url_len; ++i)
838 /* do not write anything to FETCH_HEAD */
844 rc |= update_local_ref(ref, what, rm, ¬e);
847 format_display(¬e, '*',
848 *kind ? kind : "branch", NULL,
849 *what ? what : "HEAD",
852 if (verbosity >= 0 && !shown_url) {
853 fprintf(stderr, _("From %.*s\n"),
858 fprintf(stderr, " %s\n", note.buf);
863 if (rc & STORE_REF_ERROR_DF_CONFLICT)
864 error(_("some local refs could not be updated; try running\n"
865 " 'git remote prune %s' to remove any old, conflicting "
866 "branches"), remote_name);
869 strbuf_release(¬e);
876 * We would want to bypass the object transfer altogether if
877 * everything we are going to fetch already exists and is connected
880 static int quickfetch(struct ref *ref_map)
882 struct ref *rm = ref_map;
883 struct check_connected_options opt = CHECK_CONNECTED_INIT;
886 * If we are deepening a shallow clone we already have these
887 * objects reachable. Running rev-list here will return with
888 * a good (0) exit status and we'll bypass the fetch that we
889 * really need to perform. Claiming failure now will ensure
890 * we perform the network exchange to deepen our history.
895 return check_connected(iterate_ref_map, &rm, &opt);
898 static int fetch_refs(struct transport *transport, struct ref *ref_map)
900 int ret = quickfetch(ref_map);
902 ret = transport_fetch_refs(transport, ref_map);
904 ret |= store_updated_refs(transport->url,
905 transport->remote->name,
907 transport_unlock_pack(transport);
911 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
914 int url_len, i, result = 0;
915 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
917 const char *dangling_msg = dry_run
918 ? _(" (%s will become dangling)")
919 : _(" (%s has become dangling)");
922 url = transport_anonymize_url(raw_url);
924 url = xstrdup("foreign");
926 url_len = strlen(url);
927 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
931 if (4 < i && !strncmp(".git", url + i - 3, 4))
935 struct string_list refnames = STRING_LIST_INIT_NODUP;
937 for (ref = stale_refs; ref; ref = ref->next)
938 string_list_append(&refnames, ref->name);
940 result = delete_refs(&refnames, 0);
941 string_list_clear(&refnames, 0);
944 if (verbosity >= 0) {
945 for (ref = stale_refs; ref; ref = ref->next) {
946 struct strbuf sb = STRBUF_INIT;
948 fprintf(stderr, _("From %.*s\n"), url_len, url);
951 format_display(&sb, '-', _("[deleted]"), NULL,
952 _("(none)"), prettify_refname(ref->name));
953 fprintf(stderr, " %s\n",sb.buf);
955 warn_dangling_symref(stderr, dangling_msg, ref->name);
960 free_refs(stale_refs);
964 static void check_not_current_branch(struct ref *ref_map)
966 struct branch *current_branch = branch_get(NULL);
968 if (is_bare_repository() || !current_branch)
971 for (; ref_map; ref_map = ref_map->next)
972 if (ref_map->peer_ref && !strcmp(current_branch->refname,
973 ref_map->peer_ref->name))
974 die(_("Refusing to fetch into current branch %s "
975 "of non-bare repository"), current_branch->refname);
978 static int truncate_fetch_head(void)
980 const char *filename = git_path_fetch_head();
981 FILE *fp = fopen_for_writing(filename);
984 return error_errno(_("cannot open %s"), filename);
989 static void set_option(struct transport *transport, const char *name, const char *value)
991 int r = transport_set_option(transport, name, value);
993 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
994 name, value, transport->url);
996 warning(_("Option \"%s\" is ignored for %s\n"),
997 name, transport->url);
1000 static struct transport *prepare_transport(struct remote *remote, int deepen)
1002 struct transport *transport;
1003 transport = transport_get(remote, NULL);
1004 transport_set_verbosity(transport, verbosity, progress);
1005 transport->family = family;
1007 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1009 set_option(transport, TRANS_OPT_KEEP, "yes");
1011 set_option(transport, TRANS_OPT_DEPTH, depth);
1012 if (deepen && deepen_since)
1013 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1014 if (deepen && deepen_not.nr)
1015 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1016 (const char *)&deepen_not);
1017 if (deepen_relative)
1018 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1020 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1024 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1029 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1030 * when remote helper is used (setting it to an empty string
1031 * is not unsetting). We could extend the remote helper
1032 * protocol for that, but for now, just force a new connection
1033 * without deepen-since. Similar story for deepen-not.
1035 cannot_reuse = transport->cannot_reuse ||
1036 deepen_since || deepen_not.nr;
1038 gsecondary = prepare_transport(transport->remote, 0);
1039 transport = gsecondary;
1042 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1043 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1044 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1045 fetch_refs(transport, ref_map);
1048 transport_disconnect(gsecondary);
1053 static int do_fetch(struct transport *transport,
1054 struct refspec *refs, int ref_count)
1056 struct string_list existing_refs = STRING_LIST_INIT_DUP;
1057 struct ref *ref_map;
1059 int autotags = (transport->remote->fetch_tags == 1);
1062 for_each_ref(add_existing, &existing_refs);
1064 if (tags == TAGS_DEFAULT) {
1065 if (transport->remote->fetch_tags == 2)
1067 if (transport->remote->fetch_tags == -1)
1071 if (!transport->get_refs_list || !transport->fetch)
1072 die(_("Don't know how to fetch from %s"), transport->url);
1074 /* if not appending, truncate FETCH_HEAD */
1075 if (!append && !dry_run) {
1076 retcode = truncate_fetch_head();
1081 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1082 if (!update_head_ok)
1083 check_not_current_branch(ref_map);
1085 for (rm = ref_map; rm; rm = rm->next) {
1087 struct string_list_item *peer_item =
1088 string_list_lookup(&existing_refs,
1089 rm->peer_ref->name);
1091 struct object_id *old_oid = peer_item->util;
1092 oidcpy(&rm->peer_ref->old_oid, old_oid);
1097 if (tags == TAGS_DEFAULT && autotags)
1098 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1101 * We only prune based on refspecs specified
1102 * explicitly (via command line or configuration); we
1103 * don't care whether --tags was specified.
1106 prune_refs(refs, ref_count, ref_map, transport->url);
1108 prune_refs(transport->remote->fetch,
1109 transport->remote->fetch_refspec_nr,
1114 if (fetch_refs(transport, ref_map)) {
1121 /* if neither --no-tags nor --tags was specified, do automated tag
1123 if (tags == TAGS_DEFAULT && autotags) {
1124 struct ref **tail = &ref_map;
1126 find_non_local_tags(transport, &ref_map, &tail);
1128 backfill_tags(transport, ref_map);
1133 string_list_clear(&existing_refs, 1);
1137 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1139 struct string_list *list = priv;
1140 if (!remote->skip_default_update)
1141 string_list_append(list, remote->name);
1145 struct remote_group_data {
1147 struct string_list *list;
1150 static int get_remote_group(const char *key, const char *value, void *priv)
1152 struct remote_group_data *g = priv;
1154 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1155 /* split list by white space */
1157 size_t wordlen = strcspn(value, " \t\n");
1160 string_list_append_nodup(g->list,
1161 xstrndup(value, wordlen));
1162 value += wordlen + (value[wordlen] != '\0');
1169 static int add_remote_or_group(const char *name, struct string_list *list)
1171 int prev_nr = list->nr;
1172 struct remote_group_data g;
1173 g.name = name; g.list = list;
1175 git_config(get_remote_group, &g);
1176 if (list->nr == prev_nr) {
1177 struct remote *remote = remote_get(name);
1178 if (!remote_is_configured(remote))
1180 string_list_append(list, remote->name);
1185 static void add_options_to_argv(struct argv_array *argv)
1188 argv_array_push(argv, "--dry-run");
1190 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1192 argv_array_push(argv, "--update-head-ok");
1194 argv_array_push(argv, "--force");
1196 argv_array_push(argv, "--keep");
1197 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1198 argv_array_push(argv, "--recurse-submodules");
1199 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1200 argv_array_push(argv, "--recurse-submodules=on-demand");
1201 if (tags == TAGS_SET)
1202 argv_array_push(argv, "--tags");
1203 else if (tags == TAGS_UNSET)
1204 argv_array_push(argv, "--no-tags");
1206 argv_array_push(argv, "-v");
1208 argv_array_push(argv, "-v");
1209 else if (verbosity < 0)
1210 argv_array_push(argv, "-q");
1214 static int fetch_multiple(struct string_list *list)
1217 struct argv_array argv = ARGV_ARRAY_INIT;
1219 if (!append && !dry_run) {
1220 int errcode = truncate_fetch_head();
1225 argv_array_pushl(&argv, "fetch", "--append", NULL);
1226 add_options_to_argv(&argv);
1228 for (i = 0; i < list->nr; i++) {
1229 const char *name = list->items[i].string;
1230 argv_array_push(&argv, name);
1232 printf(_("Fetching %s\n"), name);
1233 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1234 error(_("Could not fetch %s"), name);
1237 argv_array_pop(&argv);
1240 argv_array_clear(&argv);
1244 static int fetch_one(struct remote *remote, int argc, const char **argv)
1246 static const char **refs = NULL;
1247 struct refspec *refspec;
1252 die(_("No remote repository specified. Please, specify either a URL or a\n"
1253 "remote name from which new revisions should be fetched."));
1255 gtransport = prepare_transport(remote, 1);
1258 /* no command line request */
1259 if (0 <= gtransport->remote->prune)
1260 prune = gtransport->remote->prune;
1261 else if (0 <= fetch_prune_config)
1262 prune = fetch_prune_config;
1264 prune = PRUNE_BY_DEFAULT;
1270 refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1271 for (i = 0; i < argc; i++) {
1272 if (!strcmp(argv[i], "tag")) {
1275 die(_("You need to specify a tag name."));
1276 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1279 refs[j++] = argv[i];
1285 sigchain_push_common(unlock_pack_on_signal);
1286 atexit(unlock_pack);
1287 refspec = parse_fetch_refspec(ref_nr, refs);
1288 exit_code = do_fetch(gtransport, refspec, ref_nr);
1289 free_refspec(ref_nr, refspec);
1290 transport_disconnect(gtransport);
1295 int cmd_fetch(int argc, const char **argv, const char *prefix)
1298 struct string_list list = STRING_LIST_INIT_DUP;
1299 struct remote *remote;
1301 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1303 packet_trace_identity("fetch");
1305 /* Record the command line for the reflog */
1306 strbuf_addstr(&default_rla, "fetch");
1307 for (i = 1; i < argc; i++)
1308 strbuf_addf(&default_rla, " %s", argv[i]);
1310 git_config(git_fetch_config, NULL);
1312 argc = parse_options(argc, argv, prefix,
1313 builtin_fetch_options, builtin_fetch_usage, 0);
1315 if (deepen_relative) {
1316 if (deepen_relative < 0)
1317 die(_("Negative depth in --deepen is not supported"));
1319 die(_("--deepen and --depth are mutually exclusive"));
1320 depth = xstrfmt("%d", deepen_relative);
1324 die(_("--depth and --unshallow cannot be used together"));
1325 else if (!is_repository_shallow())
1326 die(_("--unshallow on a complete repository does not make sense"));
1328 depth = xstrfmt("%d", INFINITE_DEPTH);
1331 /* no need to be strict, transport_set_option() will validate it again */
1332 if (depth && atoi(depth) < 1)
1333 die(_("depth %s is not a positive number"), depth);
1334 if (depth || deepen_since || deepen_not.nr)
1337 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1338 if (recurse_submodules_default) {
1339 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1340 set_config_fetch_recurse_submodules(arg);
1342 gitmodules_config();
1343 git_config(submodule_config, NULL);
1348 die(_("fetch --all does not take a repository argument"));
1350 die(_("fetch --all does not make sense with refspecs"));
1351 (void) for_each_remote(get_one_remote_for_fetch, &list);
1352 result = fetch_multiple(&list);
1353 } else if (argc == 0) {
1354 /* No arguments -- use default remote */
1355 remote = remote_get(NULL);
1356 result = fetch_one(remote, argc, argv);
1357 } else if (multiple) {
1358 /* All arguments are assumed to be remotes or groups */
1359 for (i = 0; i < argc; i++)
1360 if (!add_remote_or_group(argv[i], &list))
1361 die(_("No such remote or remote group: %s"), argv[i]);
1362 result = fetch_multiple(&list);
1364 /* Single remote or group */
1365 (void) add_remote_or_group(argv[0], &list);
1367 /* More than one remote */
1369 die(_("Fetching a group and specifying refspecs does not make sense"));
1370 result = fetch_multiple(&list);
1372 /* Zero or one remotes */
1373 remote = remote_get(argv[0]);
1374 result = fetch_one(remote, argc-1, argv+1);
1378 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1379 struct argv_array options = ARGV_ARRAY_INIT;
1381 add_options_to_argv(&options);
1382 result = fetch_populated_submodules(&options,
1387 argv_array_clear(&options);
1390 string_list_clear(&list, 0);
1394 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1396 argv_array_push(&argv_gc_auto, "--quiet");
1397 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1398 argv_array_clear(&argv_gc_auto);