6 #include "repository.h"
10 #include "string-list.h"
12 #include "transport.h"
13 #include "run-command.h"
14 #include "parse-options.h"
16 #include "submodule-config.h"
17 #include "submodule.h"
18 #include "connected.h"
19 #include "argv-array.h"
22 #include "list-objects-filter-options.h"
24 static const char * const builtin_fetch_usage[] = {
25 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
26 N_("git fetch [<options>] <group>"),
27 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
28 N_("git fetch --all [<options>]"),
38 static int fetch_prune_config = -1; /* unspecified */
39 static int prune = -1; /* unspecified */
40 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
42 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
43 static int progress = -1;
44 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
45 static int max_children = 1;
46 static enum transport_family family;
47 static const char *depth;
48 static const char *deepen_since;
49 static const char *upload_pack;
50 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
51 static struct strbuf default_rla = STRBUF_INIT;
52 static struct transport *gtransport;
53 static struct transport *gsecondary;
54 static const char *submodule_prefix = "";
55 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
56 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
57 static int shown_url = 0;
58 static int refmap_alloc, refmap_nr;
59 static const char **refmap_array;
60 static struct list_objects_filter_options filter_options;
62 static int git_fetch_config(const char *k, const char *v, void *cb)
64 if (!strcmp(k, "fetch.prune")) {
65 fetch_prune_config = git_config_bool(k, v);
69 if (!strcmp(k, "submodule.recurse")) {
70 int r = git_config_bool(k, v) ?
71 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
72 recurse_submodules = r;
75 if (!strcmp(k, "submodule.fetchjobs")) {
76 max_children = parse_submodule_fetchjobs(k, v);
78 } else if (!strcmp(k, "fetch.recursesubmodules")) {
79 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
83 return git_default_config(k, v, cb);
86 static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
88 if (!strcmp(var, "submodule.fetchjobs")) {
89 max_children = parse_submodule_fetchjobs(var, value);
91 } else if (!strcmp(var, "fetch.recursesubmodules")) {
92 recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
99 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
101 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
104 * "git fetch --refmap='' origin foo"
105 * can be used to tell the command not to store anywhere
108 refmap_array[refmap_nr++] = arg;
112 static struct option builtin_fetch_options[] = {
113 OPT__VERBOSITY(&verbosity),
114 OPT_BOOL(0, "all", &all,
115 N_("fetch from all remotes")),
116 OPT_BOOL('a', "append", &append,
117 N_("append to .git/FETCH_HEAD instead of overwriting")),
118 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
119 N_("path to upload pack on remote end")),
120 OPT__FORCE(&force, N_("force overwrite of local branch")),
121 OPT_BOOL('m', "multiple", &multiple,
122 N_("fetch from multiple remotes")),
123 OPT_SET_INT('t', "tags", &tags,
124 N_("fetch all tags and associated objects"), TAGS_SET),
125 OPT_SET_INT('n', NULL, &tags,
126 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
127 OPT_INTEGER('j', "jobs", &max_children,
128 N_("number of submodules fetched in parallel")),
129 OPT_BOOL('p', "prune", &prune,
130 N_("prune remote-tracking branches no longer on remote")),
131 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
132 N_("control recursive fetching of submodules"),
133 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
134 OPT_BOOL(0, "dry-run", &dry_run,
136 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
137 OPT_BOOL('u', "update-head-ok", &update_head_ok,
138 N_("allow updating of HEAD ref")),
139 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
140 OPT_STRING(0, "depth", &depth, N_("depth"),
141 N_("deepen history of shallow clone")),
142 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
143 N_("deepen history of shallow repository based on time")),
144 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
145 N_("deepen history of shallow clone, excluding rev")),
146 OPT_INTEGER(0, "deepen", &deepen_relative,
147 N_("deepen history of shallow clone")),
148 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
149 N_("convert to a complete repository"),
150 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
151 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
152 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
153 { OPTION_CALLBACK, 0, "recurse-submodules-default",
154 &recurse_submodules_default, N_("on-demand"),
155 N_("default for recursive fetching of submodules "
156 "(lower priority than config files)"),
157 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
158 OPT_BOOL(0, "update-shallow", &update_shallow,
159 N_("accept refs that update .git/shallow")),
160 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
161 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
162 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
163 TRANSPORT_FAMILY_IPV4),
164 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
165 TRANSPORT_FAMILY_IPV6),
166 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
170 static void unlock_pack(void)
173 transport_unlock_pack(gtransport);
175 transport_unlock_pack(gsecondary);
178 static void unlock_pack_on_signal(int signo)
185 static void add_merge_config(struct ref **head,
186 const struct ref *remote_refs,
187 struct branch *branch,
192 for (i = 0; i < branch->merge_nr; i++) {
193 struct ref *rm, **old_tail = *tail;
194 struct refspec refspec;
196 for (rm = *head; rm; rm = rm->next) {
197 if (branch_merge_matches(branch, i, rm->name)) {
198 rm->fetch_head_status = FETCH_HEAD_MERGE;
206 * Not fetched to a remote-tracking branch? We need to fetch
207 * it anyway to allow this branch's "branch.$name.merge"
208 * to be honored by 'git pull', but we do not have to
209 * fail if branch.$name.merge is misconfigured to point
210 * at a nonexisting branch. If we were indeed called by
211 * 'git pull', it will notice the misconfiguration because
212 * there is no entry in the resulting FETCH_HEAD marked
215 memset(&refspec, 0, sizeof(refspec));
216 refspec.src = branch->merge[i]->src;
217 get_fetch_map(remote_refs, &refspec, tail, 1);
218 for (rm = *old_tail; rm; rm = rm->next)
219 rm->fetch_head_status = FETCH_HEAD_MERGE;
223 static int add_existing(const char *refname, const struct object_id *oid,
224 int flag, void *cbdata)
226 struct string_list *list = (struct string_list *)cbdata;
227 struct string_list_item *item = string_list_insert(list, refname);
228 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
230 oidcpy(old_oid, oid);
231 item->util = old_oid;
235 static int will_fetch(struct ref **head, const unsigned char *sha1)
237 struct ref *rm = *head;
239 if (!hashcmp(rm->old_oid.hash, sha1))
246 static void find_non_local_tags(struct transport *transport,
250 struct string_list existing_refs = STRING_LIST_INIT_DUP;
251 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
252 const struct ref *ref;
253 struct string_list_item *item = NULL;
255 for_each_ref(add_existing, &existing_refs);
256 for (ref = transport_get_remote_refs(transport, NULL); ref; ref = ref->next) {
257 if (!starts_with(ref->name, "refs/tags/"))
261 * The peeled ref always follows the matching base
262 * ref, so if we see a peeled ref that we don't want
263 * to fetch then we can mark the ref entry in the list
264 * as one to ignore by setting util to NULL.
266 if (ends_with(ref->name, "^{}")) {
268 !has_object_file_with_flags(&ref->old_oid,
269 OBJECT_INFO_QUICK) &&
270 !will_fetch(head, ref->old_oid.hash) &&
271 !has_sha1_file_with_flags(item->util,
272 OBJECT_INFO_QUICK) &&
273 !will_fetch(head, item->util))
280 * If item is non-NULL here, then we previously saw a
281 * ref not followed by a peeled reference, so we need
282 * to check if it is a lightweight tag that we want to
286 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
287 !will_fetch(head, item->util))
292 /* skip duplicates and refs that we already have */
293 if (string_list_has_string(&remote_refs, ref->name) ||
294 string_list_has_string(&existing_refs, ref->name))
297 item = string_list_insert(&remote_refs, ref->name);
298 item->util = (void *)&ref->old_oid;
300 string_list_clear(&existing_refs, 1);
303 * We may have a final lightweight tag that needs to be
304 * checked to see if it needs fetching.
307 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
308 !will_fetch(head, item->util))
312 * For all the tags in the remote_refs string list,
313 * add them to the list of refs to be fetched
315 for_each_string_list_item(item, &remote_refs) {
316 /* Unless we have already decided to ignore this item... */
319 struct ref *rm = alloc_ref(item->string);
320 rm->peer_ref = alloc_ref(item->string);
321 oidcpy(&rm->old_oid, item->util);
327 string_list_clear(&remote_refs, 0);
330 static struct ref *get_ref_map(struct transport *transport,
331 struct refspec *refspecs, int refspec_count,
332 int tags, int *autotags)
336 struct ref *ref_map = NULL;
337 struct ref **tail = &ref_map;
338 struct argv_array ref_patterns = ARGV_ARRAY_INIT;
340 /* opportunistically-updated references: */
341 struct ref *orefs = NULL, **oref_tail = &orefs;
343 const struct ref *remote_refs;
345 for (i = 0; i < refspec_count; i++) {
346 if (!refspecs[i].exact_sha1)
347 argv_array_push(&ref_patterns, refspecs[i].src);
350 remote_refs = transport_get_remote_refs(transport, &ref_patterns);
352 argv_array_clear(&ref_patterns);
355 struct refspec *fetch_refspec;
356 int fetch_refspec_nr;
358 for (i = 0; i < refspec_count; i++) {
359 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
360 if (refspecs[i].dst && refspecs[i].dst[0])
363 /* Merge everything on the command line (but not --tags) */
364 for (rm = ref_map; rm; rm = rm->next)
365 rm->fetch_head_status = FETCH_HEAD_MERGE;
368 * For any refs that we happen to be fetching via
369 * command-line arguments, the destination ref might
370 * have been missing or have been different than the
371 * remote-tracking ref that would be derived from the
372 * configured refspec. In these cases, we want to
373 * take the opportunity to update their configured
374 * remote-tracking reference. However, we do not want
375 * to mention these entries in FETCH_HEAD at all, as
376 * they would simply be duplicates of existing
377 * entries, so we set them FETCH_HEAD_IGNORE below.
379 * We compute these entries now, based only on the
380 * refspecs specified on the command line. But we add
381 * them to the list following the refspecs resulting
382 * from the tags option so that one of the latter,
383 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
384 * by ref_remove_duplicates() in favor of one of these
385 * opportunistic entries with FETCH_HEAD_IGNORE.
388 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
389 fetch_refspec_nr = refmap_nr;
391 fetch_refspec = transport->remote->fetch;
392 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
395 for (i = 0; i < fetch_refspec_nr; i++)
396 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
397 } else if (refmap_array) {
398 die("--refmap option is only meaningful with command-line refspec(s).");
400 /* Use the defaults */
401 struct remote *remote = transport->remote;
402 struct branch *branch = branch_get(NULL);
403 int has_merge = branch_has_merge_config(branch);
405 (remote->fetch_refspec_nr ||
406 /* Note: has_merge implies non-NULL branch->remote_name */
407 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
408 for (i = 0; i < remote->fetch_refspec_nr; i++) {
409 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
410 if (remote->fetch[i].dst &&
411 remote->fetch[i].dst[0])
413 if (!i && !has_merge && ref_map &&
414 !remote->fetch[0].pattern)
415 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
418 * if the remote we're fetching from is the same
419 * as given in branch.<name>.remote, we add the
420 * ref given in branch.<name>.merge, too.
422 * Note: has_merge implies non-NULL branch->remote_name
425 !strcmp(branch->remote_name, remote->name))
426 add_merge_config(&ref_map, remote_refs, branch, &tail);
428 ref_map = get_remote_ref(remote_refs, "HEAD");
430 die(_("Couldn't find remote ref HEAD"));
431 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
432 tail = &ref_map->next;
436 if (tags == TAGS_SET)
437 /* also fetch all tags */
438 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
439 else if (tags == TAGS_DEFAULT && *autotags)
440 find_non_local_tags(transport, &ref_map, &tail);
442 /* Now append any refs to be updated opportunistically: */
444 for (rm = orefs; rm; rm = rm->next) {
445 rm->fetch_head_status = FETCH_HEAD_IGNORE;
449 return ref_remove_duplicates(ref_map);
452 #define STORE_REF_ERROR_OTHER 1
453 #define STORE_REF_ERROR_DF_CONFLICT 2
455 static int s_update_ref(const char *action,
460 char *rla = getenv("GIT_REFLOG_ACTION");
461 struct ref_transaction *transaction;
462 struct strbuf err = STRBUF_INIT;
463 int ret, df_conflict = 0;
468 rla = default_rla.buf;
469 msg = xstrfmt("%s: %s", rla, action);
471 transaction = ref_transaction_begin(&err);
473 ref_transaction_update(transaction, ref->name,
475 check_old ? &ref->old_oid : NULL,
479 ret = ref_transaction_commit(transaction, &err);
481 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
485 ref_transaction_free(transaction);
486 strbuf_release(&err);
490 ref_transaction_free(transaction);
491 error("%s", err.buf);
492 strbuf_release(&err);
494 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
495 : STORE_REF_ERROR_OTHER;
498 static int refcol_width = 10;
499 static int compact_format;
501 static void adjust_refcol_width(const struct ref *ref)
503 int max, rlen, llen, len;
505 /* uptodate lines are only shown on high verbosity level */
506 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
509 max = term_columns();
510 rlen = utf8_strwidth(prettify_refname(ref->name));
512 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
515 * rough estimation to see if the output line is too long and
516 * should not be counted (we can't do precise calculation
517 * anyway because we don't know if the error explanation part
518 * will be printed in update_local_ref)
520 if (compact_format) {
524 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
529 * Not precise calculation for compact mode because '*' can
530 * appear on the left hand side of '->' and shrink the column
533 if (refcol_width < rlen)
537 static void prepare_format_display(struct ref *ref_map)
540 const char *format = "full";
542 git_config_get_string_const("fetch.output", &format);
543 if (!strcasecmp(format, "full"))
545 else if (!strcasecmp(format, "compact"))
548 die(_("configuration fetch.output contains invalid value %s"),
551 for (rm = ref_map; rm; rm = rm->next) {
552 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
554 !strcmp(rm->name, "HEAD"))
557 adjust_refcol_width(rm);
561 static void print_remote_to_local(struct strbuf *display,
562 const char *remote, const char *local)
564 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
567 static int find_and_replace(struct strbuf *haystack,
569 const char *placeholder)
571 const char *p = strstr(haystack->buf, needle);
577 if (p > haystack->buf && p[-1] != '/')
581 nlen = strlen(needle);
582 if (plen > nlen && p[nlen] != '/')
585 strbuf_splice(haystack, p - haystack->buf, nlen,
586 placeholder, strlen(placeholder));
590 static void print_compact(struct strbuf *display,
591 const char *remote, const char *local)
593 struct strbuf r = STRBUF_INIT;
594 struct strbuf l = STRBUF_INIT;
596 if (!strcmp(remote, local)) {
597 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
601 strbuf_addstr(&r, remote);
602 strbuf_addstr(&l, local);
604 if (!find_and_replace(&r, local, "*"))
605 find_and_replace(&l, remote, "*");
606 print_remote_to_local(display, r.buf, l.buf);
612 static void format_display(struct strbuf *display, char code,
613 const char *summary, const char *error,
614 const char *remote, const char *local,
617 int width = (summary_width + strlen(summary) - gettext_width(summary));
619 strbuf_addf(display, "%c %-*s ", code, width, summary);
621 print_remote_to_local(display, remote, local);
623 print_compact(display, remote, local);
625 strbuf_addf(display, " (%s)", error);
628 static int update_local_ref(struct ref *ref,
630 const struct ref *remote_ref,
631 struct strbuf *display,
634 struct commit *current = NULL, *updated;
635 enum object_type type;
636 struct branch *current_branch = branch_get(NULL);
637 const char *pretty_ref = prettify_refname(ref->name);
639 type = sha1_object_info(ref->new_oid.hash, NULL);
641 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
643 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
645 format_display(display, '=', _("[up to date]"), NULL,
646 remote, pretty_ref, summary_width);
650 if (current_branch &&
651 !strcmp(ref->name, current_branch->name) &&
652 !(update_head_ok || is_bare_repository()) &&
653 !is_null_oid(&ref->old_oid)) {
655 * If this is the head, and it's not okay to update
656 * the head, and the old value of the head isn't empty...
658 format_display(display, '!', _("[rejected]"),
659 _("can't fetch in current branch"),
660 remote, pretty_ref, summary_width);
664 if (!is_null_oid(&ref->old_oid) &&
665 starts_with(ref->name, "refs/tags/")) {
667 r = s_update_ref("updating tag", ref, 0);
668 format_display(display, r ? '!' : 't', _("[tag update]"),
669 r ? _("unable to update local ref") : NULL,
670 remote, pretty_ref, summary_width);
674 current = lookup_commit_reference_gently(&ref->old_oid, 1);
675 updated = lookup_commit_reference_gently(&ref->new_oid, 1);
676 if (!current || !updated) {
681 * Nicely describe the new ref we're fetching.
682 * Base this on the remote's ref name, as it's
683 * more likely to follow a standard layout.
685 const char *name = remote_ref ? remote_ref->name : "";
686 if (starts_with(name, "refs/tags/")) {
688 what = _("[new tag]");
689 } else if (starts_with(name, "refs/heads/")) {
690 msg = "storing head";
691 what = _("[new branch]");
694 what = _("[new ref]");
697 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
698 (recurse_submodules != RECURSE_SUBMODULES_ON))
699 check_for_new_submodule_commits(&ref->new_oid);
700 r = s_update_ref(msg, ref, 0);
701 format_display(display, r ? '!' : '*', what,
702 r ? _("unable to update local ref") : NULL,
703 remote, pretty_ref, summary_width);
707 if (in_merge_bases(current, updated)) {
708 struct strbuf quickref = STRBUF_INIT;
710 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
711 strbuf_addstr(&quickref, "..");
712 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
713 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
714 (recurse_submodules != RECURSE_SUBMODULES_ON))
715 check_for_new_submodule_commits(&ref->new_oid);
716 r = s_update_ref("fast-forward", ref, 1);
717 format_display(display, r ? '!' : ' ', quickref.buf,
718 r ? _("unable to update local ref") : NULL,
719 remote, pretty_ref, summary_width);
720 strbuf_release(&quickref);
722 } else if (force || ref->force) {
723 struct strbuf quickref = STRBUF_INIT;
725 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
726 strbuf_addstr(&quickref, "...");
727 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
728 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
729 (recurse_submodules != RECURSE_SUBMODULES_ON))
730 check_for_new_submodule_commits(&ref->new_oid);
731 r = s_update_ref("forced-update", ref, 1);
732 format_display(display, r ? '!' : '+', quickref.buf,
733 r ? _("unable to update local ref") : _("forced update"),
734 remote, pretty_ref, summary_width);
735 strbuf_release(&quickref);
738 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
739 remote, pretty_ref, summary_width);
744 static int iterate_ref_map(void *cb_data, struct object_id *oid)
746 struct ref **rm = cb_data;
747 struct ref *ref = *rm;
749 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
752 return -1; /* end of the list */
754 oidcpy(oid, &ref->old_oid);
758 static int store_updated_refs(const char *raw_url, const char *remote_name,
762 struct commit *commit;
763 int url_len, i, rc = 0;
764 struct strbuf note = STRBUF_INIT;
765 const char *what, *kind;
768 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
770 int summary_width = transport_summary_width(ref_map);
772 fp = fopen(filename, "a");
774 return error_errno(_("cannot open %s"), filename);
777 url = transport_anonymize_url(raw_url);
779 url = xstrdup("foreign");
782 if (check_connected(iterate_ref_map, &rm, NULL)) {
783 rc = error(_("%s did not send all necessary objects\n"), url);
787 prepare_format_display(ref_map);
790 * We do a pass for each fetch_head_status type in their enum order, so
791 * merged entries are written before not-for-merge. That lets readers
792 * use FETCH_HEAD as a refname to refer to the ref to be merged.
794 for (want_status = FETCH_HEAD_MERGE;
795 want_status <= FETCH_HEAD_IGNORE;
797 for (rm = ref_map; rm; rm = rm->next) {
798 struct ref *ref = NULL;
799 const char *merge_status_marker = "";
801 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
802 if (want_status == FETCH_HEAD_MERGE)
803 warning(_("reject %s because shallow roots are not allowed to be updated"),
804 rm->peer_ref ? rm->peer_ref->name : rm->name);
808 commit = lookup_commit_reference_gently(&rm->old_oid,
811 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
813 if (rm->fetch_head_status != want_status)
817 ref = alloc_ref(rm->peer_ref->name);
818 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
819 oidcpy(&ref->new_oid, &rm->old_oid);
820 ref->force = rm->peer_ref->force;
824 if (!strcmp(rm->name, "HEAD")) {
828 else if (starts_with(rm->name, "refs/heads/")) {
830 what = rm->name + 11;
832 else if (starts_with(rm->name, "refs/tags/")) {
834 what = rm->name + 10;
836 else if (starts_with(rm->name, "refs/remotes/")) {
837 kind = "remote-tracking branch";
838 what = rm->name + 13;
845 url_len = strlen(url);
846 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
849 if (4 < i && !strncmp(".git", url + i - 3, 4))
855 strbuf_addf(¬e, "%s ", kind);
856 strbuf_addf(¬e, "'%s' of ", what);
858 switch (rm->fetch_head_status) {
859 case FETCH_HEAD_NOT_FOR_MERGE:
860 merge_status_marker = "not-for-merge";
862 case FETCH_HEAD_MERGE:
863 fprintf(fp, "%s\t%s\t%s",
864 oid_to_hex(&rm->old_oid),
867 for (i = 0; i < url_len; ++i)
875 /* do not write anything to FETCH_HEAD */
881 rc |= update_local_ref(ref, what, rm, ¬e,
885 format_display(¬e, '*',
886 *kind ? kind : "branch", NULL,
887 *what ? what : "HEAD",
888 "FETCH_HEAD", summary_width);
890 if (verbosity >= 0 && !shown_url) {
891 fprintf(stderr, _("From %.*s\n"),
896 fprintf(stderr, " %s\n", note.buf);
901 if (rc & STORE_REF_ERROR_DF_CONFLICT)
902 error(_("some local refs could not be updated; try running\n"
903 " 'git remote prune %s' to remove any old, conflicting "
904 "branches"), remote_name);
907 strbuf_release(¬e);
914 * We would want to bypass the object transfer altogether if
915 * everything we are going to fetch already exists and is connected
918 static int quickfetch(struct ref *ref_map)
920 struct ref *rm = ref_map;
921 struct check_connected_options opt = CHECK_CONNECTED_INIT;
924 * If we are deepening a shallow clone we already have these
925 * objects reachable. Running rev-list here will return with
926 * a good (0) exit status and we'll bypass the fetch that we
927 * really need to perform. Claiming failure now will ensure
928 * we perform the network exchange to deepen our history.
933 return check_connected(iterate_ref_map, &rm, &opt);
936 static int fetch_refs(struct transport *transport, struct ref *ref_map)
938 int ret = quickfetch(ref_map);
940 ret = transport_fetch_refs(transport, ref_map);
942 ret |= store_updated_refs(transport->url,
943 transport->remote->name,
945 transport_unlock_pack(transport);
949 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
952 int url_len, i, result = 0;
953 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
955 int summary_width = transport_summary_width(stale_refs);
956 const char *dangling_msg = dry_run
957 ? _(" (%s will become dangling)")
958 : _(" (%s has become dangling)");
961 url = transport_anonymize_url(raw_url);
963 url = xstrdup("foreign");
965 url_len = strlen(url);
966 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
970 if (4 < i && !strncmp(".git", url + i - 3, 4))
974 struct string_list refnames = STRING_LIST_INIT_NODUP;
976 for (ref = stale_refs; ref; ref = ref->next)
977 string_list_append(&refnames, ref->name);
979 result = delete_refs("fetch: prune", &refnames, 0);
980 string_list_clear(&refnames, 0);
983 if (verbosity >= 0) {
984 for (ref = stale_refs; ref; ref = ref->next) {
985 struct strbuf sb = STRBUF_INIT;
987 fprintf(stderr, _("From %.*s\n"), url_len, url);
990 format_display(&sb, '-', _("[deleted]"), NULL,
991 _("(none)"), prettify_refname(ref->name),
993 fprintf(stderr, " %s\n",sb.buf);
995 warn_dangling_symref(stderr, dangling_msg, ref->name);
1000 free_refs(stale_refs);
1004 static void check_not_current_branch(struct ref *ref_map)
1006 struct branch *current_branch = branch_get(NULL);
1008 if (is_bare_repository() || !current_branch)
1011 for (; ref_map; ref_map = ref_map->next)
1012 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1013 ref_map->peer_ref->name))
1014 die(_("Refusing to fetch into current branch %s "
1015 "of non-bare repository"), current_branch->refname);
1018 static int truncate_fetch_head(void)
1020 const char *filename = git_path_fetch_head();
1021 FILE *fp = fopen_for_writing(filename);
1024 return error_errno(_("cannot open %s"), filename);
1029 static void set_option(struct transport *transport, const char *name, const char *value)
1031 int r = transport_set_option(transport, name, value);
1033 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1034 name, value, transport->url);
1036 warning(_("Option \"%s\" is ignored for %s\n"),
1037 name, transport->url);
1040 static struct transport *prepare_transport(struct remote *remote, int deepen)
1042 struct transport *transport;
1043 transport = transport_get(remote, NULL);
1044 transport_set_verbosity(transport, verbosity, progress);
1045 transport->family = family;
1047 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1049 set_option(transport, TRANS_OPT_KEEP, "yes");
1051 set_option(transport, TRANS_OPT_DEPTH, depth);
1052 if (deepen && deepen_since)
1053 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1054 if (deepen && deepen_not.nr)
1055 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1056 (const char *)&deepen_not);
1057 if (deepen_relative)
1058 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1060 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1061 if (filter_options.choice) {
1062 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1063 filter_options.filter_spec);
1064 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1069 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1074 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1075 * when remote helper is used (setting it to an empty string
1076 * is not unsetting). We could extend the remote helper
1077 * protocol for that, but for now, just force a new connection
1078 * without deepen-since. Similar story for deepen-not.
1080 cannot_reuse = transport->cannot_reuse ||
1081 deepen_since || deepen_not.nr;
1083 gsecondary = prepare_transport(transport->remote, 0);
1084 transport = gsecondary;
1087 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1088 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1089 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1090 fetch_refs(transport, ref_map);
1093 transport_disconnect(gsecondary);
1098 static int do_fetch(struct transport *transport,
1099 struct refspec *refs, int ref_count)
1101 struct string_list existing_refs = STRING_LIST_INIT_DUP;
1102 struct ref *ref_map;
1104 int autotags = (transport->remote->fetch_tags == 1);
1107 for_each_ref(add_existing, &existing_refs);
1109 if (tags == TAGS_DEFAULT) {
1110 if (transport->remote->fetch_tags == 2)
1112 if (transport->remote->fetch_tags == -1)
1116 /* if not appending, truncate FETCH_HEAD */
1117 if (!append && !dry_run) {
1118 retcode = truncate_fetch_head();
1123 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1124 if (!update_head_ok)
1125 check_not_current_branch(ref_map);
1127 for (rm = ref_map; rm; rm = rm->next) {
1129 struct string_list_item *peer_item =
1130 string_list_lookup(&existing_refs,
1131 rm->peer_ref->name);
1133 struct object_id *old_oid = peer_item->util;
1134 oidcpy(&rm->peer_ref->old_oid, old_oid);
1139 if (tags == TAGS_DEFAULT && autotags)
1140 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1143 * We only prune based on refspecs specified
1144 * explicitly (via command line or configuration); we
1145 * don't care whether --tags was specified.
1148 prune_refs(refs, ref_count, ref_map, transport->url);
1150 prune_refs(transport->remote->fetch,
1151 transport->remote->fetch_refspec_nr,
1156 if (fetch_refs(transport, ref_map)) {
1163 /* if neither --no-tags nor --tags was specified, do automated tag
1165 if (tags == TAGS_DEFAULT && autotags) {
1166 struct ref **tail = &ref_map;
1168 find_non_local_tags(transport, &ref_map, &tail);
1170 backfill_tags(transport, ref_map);
1175 string_list_clear(&existing_refs, 1);
1179 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1181 struct string_list *list = priv;
1182 if (!remote->skip_default_update)
1183 string_list_append(list, remote->name);
1187 struct remote_group_data {
1189 struct string_list *list;
1192 static int get_remote_group(const char *key, const char *value, void *priv)
1194 struct remote_group_data *g = priv;
1196 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1197 /* split list by white space */
1199 size_t wordlen = strcspn(value, " \t\n");
1202 string_list_append_nodup(g->list,
1203 xstrndup(value, wordlen));
1204 value += wordlen + (value[wordlen] != '\0');
1211 static int add_remote_or_group(const char *name, struct string_list *list)
1213 int prev_nr = list->nr;
1214 struct remote_group_data g;
1215 g.name = name; g.list = list;
1217 git_config(get_remote_group, &g);
1218 if (list->nr == prev_nr) {
1219 struct remote *remote = remote_get(name);
1220 if (!remote_is_configured(remote, 0))
1222 string_list_append(list, remote->name);
1227 static void add_options_to_argv(struct argv_array *argv)
1230 argv_array_push(argv, "--dry-run");
1232 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1234 argv_array_push(argv, "--update-head-ok");
1236 argv_array_push(argv, "--force");
1238 argv_array_push(argv, "--keep");
1239 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1240 argv_array_push(argv, "--recurse-submodules");
1241 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1242 argv_array_push(argv, "--recurse-submodules=on-demand");
1243 if (tags == TAGS_SET)
1244 argv_array_push(argv, "--tags");
1245 else if (tags == TAGS_UNSET)
1246 argv_array_push(argv, "--no-tags");
1248 argv_array_push(argv, "-v");
1250 argv_array_push(argv, "-v");
1251 else if (verbosity < 0)
1252 argv_array_push(argv, "-q");
1256 static int fetch_multiple(struct string_list *list)
1259 struct argv_array argv = ARGV_ARRAY_INIT;
1261 if (!append && !dry_run) {
1262 int errcode = truncate_fetch_head();
1267 argv_array_pushl(&argv, "fetch", "--append", NULL);
1268 add_options_to_argv(&argv);
1270 for (i = 0; i < list->nr; i++) {
1271 const char *name = list->items[i].string;
1272 argv_array_push(&argv, name);
1274 printf(_("Fetching %s\n"), name);
1275 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1276 error(_("Could not fetch %s"), name);
1279 argv_array_pop(&argv);
1282 argv_array_clear(&argv);
1287 * Fetching from the promisor remote should use the given filter-spec
1288 * or inherit the default filter-spec from the config.
1290 static inline void fetch_one_setup_partial(struct remote *remote)
1293 * Explicit --no-filter argument overrides everything, regardless
1294 * of any prior partial clones and fetches.
1296 if (filter_options.no_filter)
1300 * If no prior partial clone/fetch and the current fetch DID NOT
1301 * request a partial-fetch, do a normal fetch.
1303 if (!repository_format_partial_clone && !filter_options.choice)
1307 * If this is the FIRST partial-fetch request, we enable partial
1308 * on this repo and remember the given filter-spec as the default
1309 * for subsequent fetches to this remote.
1311 if (!repository_format_partial_clone && filter_options.choice) {
1312 partial_clone_register(remote->name, &filter_options);
1317 * We are currently limited to only ONE promisor remote and only
1318 * allow partial-fetches from the promisor remote.
1320 if (strcmp(remote->name, repository_format_partial_clone)) {
1321 if (filter_options.choice)
1322 die(_("--filter can only be used with the remote configured in core.partialClone"));
1327 * Do a partial-fetch from the promisor remote using either the
1328 * explicitly given filter-spec or inherit the filter-spec from
1331 if (!filter_options.choice)
1332 partial_clone_get_default_filter_spec(&filter_options);
1336 static int fetch_one(struct remote *remote, int argc, const char **argv)
1338 static const char **refs = NULL;
1339 struct refspec *refspec;
1344 die(_("No remote repository specified. Please, specify either a URL or a\n"
1345 "remote name from which new revisions should be fetched."));
1347 gtransport = prepare_transport(remote, 1);
1350 /* no command line request */
1351 if (0 <= gtransport->remote->prune)
1352 prune = gtransport->remote->prune;
1353 else if (0 <= fetch_prune_config)
1354 prune = fetch_prune_config;
1356 prune = PRUNE_BY_DEFAULT;
1362 refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1363 for (i = 0; i < argc; i++) {
1364 if (!strcmp(argv[i], "tag")) {
1367 die(_("You need to specify a tag name."));
1368 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1371 refs[j++] = argv[i];
1377 sigchain_push_common(unlock_pack_on_signal);
1378 atexit(unlock_pack);
1379 refspec = parse_fetch_refspec(ref_nr, refs);
1380 exit_code = do_fetch(gtransport, refspec, ref_nr);
1381 free_refspec(ref_nr, refspec);
1382 transport_disconnect(gtransport);
1387 int cmd_fetch(int argc, const char **argv, const char *prefix)
1390 struct string_list list = STRING_LIST_INIT_DUP;
1391 struct remote *remote = NULL;
1393 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1395 packet_trace_identity("fetch");
1397 fetch_if_missing = 0;
1399 /* Record the command line for the reflog */
1400 strbuf_addstr(&default_rla, "fetch");
1401 for (i = 1; i < argc; i++)
1402 strbuf_addf(&default_rla, " %s", argv[i]);
1404 config_from_gitmodules(gitmodules_fetch_config, NULL);
1405 git_config(git_fetch_config, NULL);
1407 argc = parse_options(argc, argv, prefix,
1408 builtin_fetch_options, builtin_fetch_usage, 0);
1410 if (deepen_relative) {
1411 if (deepen_relative < 0)
1412 die(_("Negative depth in --deepen is not supported"));
1414 die(_("--deepen and --depth are mutually exclusive"));
1415 depth = xstrfmt("%d", deepen_relative);
1419 die(_("--depth and --unshallow cannot be used together"));
1420 else if (!is_repository_shallow())
1421 die(_("--unshallow on a complete repository does not make sense"));
1423 depth = xstrfmt("%d", INFINITE_DEPTH);
1426 /* no need to be strict, transport_set_option() will validate it again */
1427 if (depth && atoi(depth) < 1)
1428 die(_("depth %s is not a positive number"), depth);
1429 if (depth || deepen_since || deepen_not.nr)
1432 if (filter_options.choice && !repository_format_partial_clone)
1433 die("--filter can only be used when extensions.partialClone is set");
1437 die(_("fetch --all does not take a repository argument"));
1439 die(_("fetch --all does not make sense with refspecs"));
1440 (void) for_each_remote(get_one_remote_for_fetch, &list);
1441 } else if (argc == 0) {
1442 /* No arguments -- use default remote */
1443 remote = remote_get(NULL);
1444 } else if (multiple) {
1445 /* All arguments are assumed to be remotes or groups */
1446 for (i = 0; i < argc; i++)
1447 if (!add_remote_or_group(argv[i], &list))
1448 die(_("No such remote or remote group: %s"), argv[i]);
1450 /* Single remote or group */
1451 (void) add_remote_or_group(argv[0], &list);
1453 /* More than one remote */
1455 die(_("Fetching a group and specifying refspecs does not make sense"));
1457 /* Zero or one remotes */
1458 remote = remote_get(argv[0]);
1465 if (filter_options.choice || repository_format_partial_clone)
1466 fetch_one_setup_partial(remote);
1467 result = fetch_one(remote, argc, argv);
1469 if (filter_options.choice)
1470 die(_("--filter can only be used with the remote configured in core.partialClone"));
1471 /* TODO should this also die if we have a previous partial-clone? */
1472 result = fetch_multiple(&list);
1475 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1476 struct argv_array options = ARGV_ARRAY_INIT;
1478 add_options_to_argv(&options);
1479 result = fetch_populated_submodules(the_repository,
1483 recurse_submodules_default,
1486 argv_array_clear(&options);
1489 string_list_clear(&list, 0);
1493 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1495 argv_array_push(&argv_gc_auto, "--quiet");
1496 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1497 argv_array_clear(&argv_gc_auto);