6 #include "repository.h"
11 #include "string-list.h"
13 #include "transport.h"
14 #include "run-command.h"
15 #include "parse-options.h"
17 #include "submodule-config.h"
18 #include "submodule.h"
19 #include "connected.h"
20 #include "argv-array.h"
23 #include "list-objects-filter-options.h"
25 static const char * const builtin_fetch_usage[] = {
26 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
27 N_("git fetch [<options>] <group>"),
28 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
29 N_("git fetch --all [<options>]"),
39 static int fetch_prune_config = -1; /* unspecified */
40 static int prune = -1; /* unspecified */
41 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
43 static int fetch_prune_tags_config = -1; /* unspecified */
44 static int prune_tags = -1; /* unspecified */
45 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
47 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
48 static int progress = -1;
49 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
50 static int max_children = 1;
51 static enum transport_family family;
52 static const char *depth;
53 static const char *deepen_since;
54 static const char *upload_pack;
55 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
56 static struct strbuf default_rla = STRBUF_INIT;
57 static struct transport *gtransport;
58 static struct transport *gsecondary;
59 static const char *submodule_prefix = "";
60 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
61 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
62 static int shown_url = 0;
63 static struct refspec refmap = REFSPEC_INIT_FETCH;
64 static struct list_objects_filter_options filter_options;
65 static struct string_list server_options = STRING_LIST_INIT_DUP;
67 static int git_fetch_config(const char *k, const char *v, void *cb)
69 if (!strcmp(k, "fetch.prune")) {
70 fetch_prune_config = git_config_bool(k, v);
74 if (!strcmp(k, "fetch.prunetags")) {
75 fetch_prune_tags_config = git_config_bool(k, v);
79 if (!strcmp(k, "submodule.recurse")) {
80 int r = git_config_bool(k, v) ?
81 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
82 recurse_submodules = r;
85 if (!strcmp(k, "submodule.fetchjobs")) {
86 max_children = parse_submodule_fetchjobs(k, v);
88 } else if (!strcmp(k, "fetch.recursesubmodules")) {
89 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
93 return git_default_config(k, v, cb);
96 static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
98 if (!strcmp(var, "submodule.fetchjobs")) {
99 max_children = parse_submodule_fetchjobs(var, value);
101 } else if (!strcmp(var, "fetch.recursesubmodules")) {
102 recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
109 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
112 * "git fetch --refmap='' origin foo"
113 * can be used to tell the command not to store anywhere
115 refspec_append(&refmap, arg);
120 static struct option builtin_fetch_options[] = {
121 OPT__VERBOSITY(&verbosity),
122 OPT_BOOL(0, "all", &all,
123 N_("fetch from all remotes")),
124 OPT_BOOL('a', "append", &append,
125 N_("append to .git/FETCH_HEAD instead of overwriting")),
126 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
127 N_("path to upload pack on remote end")),
128 OPT__FORCE(&force, N_("force overwrite of local branch"), 0),
129 OPT_BOOL('m', "multiple", &multiple,
130 N_("fetch from multiple remotes")),
131 OPT_SET_INT('t', "tags", &tags,
132 N_("fetch all tags and associated objects"), TAGS_SET),
133 OPT_SET_INT('n', NULL, &tags,
134 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
135 OPT_INTEGER('j', "jobs", &max_children,
136 N_("number of submodules fetched in parallel")),
137 OPT_BOOL('p', "prune", &prune,
138 N_("prune remote-tracking branches no longer on remote")),
139 OPT_BOOL('P', "prune-tags", &prune_tags,
140 N_("prune local tags no longer on remote and clobber changed tags")),
141 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
142 N_("control recursive fetching of submodules"),
143 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
144 OPT_BOOL(0, "dry-run", &dry_run,
146 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
147 OPT_BOOL('u', "update-head-ok", &update_head_ok,
148 N_("allow updating of HEAD ref")),
149 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
150 OPT_STRING(0, "depth", &depth, N_("depth"),
151 N_("deepen history of shallow clone")),
152 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
153 N_("deepen history of shallow repository based on time")),
154 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
155 N_("deepen history of shallow clone, excluding rev")),
156 OPT_INTEGER(0, "deepen", &deepen_relative,
157 N_("deepen history of shallow clone")),
158 OPT_SET_INT_F(0, "unshallow", &unshallow,
159 N_("convert to a complete repository"),
161 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
162 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
163 { OPTION_CALLBACK, 0, "recurse-submodules-default",
164 &recurse_submodules_default, N_("on-demand"),
165 N_("default for recursive fetching of submodules "
166 "(lower priority than config files)"),
167 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
168 OPT_BOOL(0, "update-shallow", &update_shallow,
169 N_("accept refs that update .git/shallow")),
170 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
171 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
172 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
173 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
174 TRANSPORT_FAMILY_IPV4),
175 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
176 TRANSPORT_FAMILY_IPV6),
177 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
181 static void unlock_pack(void)
184 transport_unlock_pack(gtransport);
186 transport_unlock_pack(gsecondary);
189 static void unlock_pack_on_signal(int signo)
196 static void add_merge_config(struct ref **head,
197 const struct ref *remote_refs,
198 struct branch *branch,
203 for (i = 0; i < branch->merge_nr; i++) {
204 struct ref *rm, **old_tail = *tail;
205 struct refspec_item refspec;
207 for (rm = *head; rm; rm = rm->next) {
208 if (branch_merge_matches(branch, i, rm->name)) {
209 rm->fetch_head_status = FETCH_HEAD_MERGE;
217 * Not fetched to a remote-tracking branch? We need to fetch
218 * it anyway to allow this branch's "branch.$name.merge"
219 * to be honored by 'git pull', but we do not have to
220 * fail if branch.$name.merge is misconfigured to point
221 * at a nonexisting branch. If we were indeed called by
222 * 'git pull', it will notice the misconfiguration because
223 * there is no entry in the resulting FETCH_HEAD marked
226 memset(&refspec, 0, sizeof(refspec));
227 refspec.src = branch->merge[i]->src;
228 get_fetch_map(remote_refs, &refspec, tail, 1);
229 for (rm = *old_tail; rm; rm = rm->next)
230 rm->fetch_head_status = FETCH_HEAD_MERGE;
234 static int add_existing(const char *refname, const struct object_id *oid,
235 int flag, void *cbdata)
237 struct string_list *list = (struct string_list *)cbdata;
238 struct string_list_item *item = string_list_insert(list, refname);
239 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
241 oidcpy(old_oid, oid);
242 item->util = old_oid;
246 static int will_fetch(struct ref **head, const unsigned char *sha1)
248 struct ref *rm = *head;
250 if (!hashcmp(rm->old_oid.hash, sha1))
257 static void find_non_local_tags(struct transport *transport,
261 struct string_list existing_refs = STRING_LIST_INIT_DUP;
262 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
263 const struct ref *ref;
264 struct string_list_item *item = NULL;
266 for_each_ref(add_existing, &existing_refs);
267 for (ref = transport_get_remote_refs(transport, NULL); ref; ref = ref->next) {
268 if (!starts_with(ref->name, "refs/tags/"))
272 * The peeled ref always follows the matching base
273 * ref, so if we see a peeled ref that we don't want
274 * to fetch then we can mark the ref entry in the list
275 * as one to ignore by setting util to NULL.
277 if (ends_with(ref->name, "^{}")) {
279 !has_object_file_with_flags(&ref->old_oid,
280 OBJECT_INFO_QUICK) &&
281 !will_fetch(head, ref->old_oid.hash) &&
282 !has_sha1_file_with_flags(item->util,
283 OBJECT_INFO_QUICK) &&
284 !will_fetch(head, item->util))
291 * If item is non-NULL here, then we previously saw a
292 * ref not followed by a peeled reference, so we need
293 * to check if it is a lightweight tag that we want to
297 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
298 !will_fetch(head, item->util))
303 /* skip duplicates and refs that we already have */
304 if (string_list_has_string(&remote_refs, ref->name) ||
305 string_list_has_string(&existing_refs, ref->name))
308 item = string_list_insert(&remote_refs, ref->name);
309 item->util = (void *)&ref->old_oid;
311 string_list_clear(&existing_refs, 1);
314 * We may have a final lightweight tag that needs to be
315 * checked to see if it needs fetching.
318 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
319 !will_fetch(head, item->util))
323 * For all the tags in the remote_refs string list,
324 * add them to the list of refs to be fetched
326 for_each_string_list_item(item, &remote_refs) {
327 /* Unless we have already decided to ignore this item... */
330 struct ref *rm = alloc_ref(item->string);
331 rm->peer_ref = alloc_ref(item->string);
332 oidcpy(&rm->old_oid, item->util);
338 string_list_clear(&remote_refs, 0);
341 static struct ref *get_ref_map(struct transport *transport,
343 int tags, int *autotags)
347 struct ref *ref_map = NULL;
348 struct ref **tail = &ref_map;
349 struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
351 /* opportunistically-updated references: */
352 struct ref *orefs = NULL, **oref_tail = &orefs;
354 struct string_list existing_refs = STRING_LIST_INIT_DUP;
355 const struct ref *remote_refs;
358 refspec_ref_prefixes(rs, &ref_prefixes);
359 else if (transport->remote && transport->remote->fetch.nr)
360 refspec_ref_prefixes(&transport->remote->fetch, &ref_prefixes);
362 if (ref_prefixes.argc &&
363 (tags == TAGS_SET || (tags == TAGS_DEFAULT && !rs->nr))) {
364 argv_array_push(&ref_prefixes, "refs/tags/");
367 remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
369 argv_array_clear(&ref_prefixes);
372 struct refspec *fetch_refspec;
374 for (i = 0; i < rs->nr; i++) {
375 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
376 if (rs->items[i].dst && rs->items[i].dst[0])
379 /* Merge everything on the command line (but not --tags) */
380 for (rm = ref_map; rm; rm = rm->next)
381 rm->fetch_head_status = FETCH_HEAD_MERGE;
384 * For any refs that we happen to be fetching via
385 * command-line arguments, the destination ref might
386 * have been missing or have been different than the
387 * remote-tracking ref that would be derived from the
388 * configured refspec. In these cases, we want to
389 * take the opportunity to update their configured
390 * remote-tracking reference. However, we do not want
391 * to mention these entries in FETCH_HEAD at all, as
392 * they would simply be duplicates of existing
393 * entries, so we set them FETCH_HEAD_IGNORE below.
395 * We compute these entries now, based only on the
396 * refspecs specified on the command line. But we add
397 * them to the list following the refspecs resulting
398 * from the tags option so that one of the latter,
399 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
400 * by ref_remove_duplicates() in favor of one of these
401 * opportunistic entries with FETCH_HEAD_IGNORE.
404 fetch_refspec = &refmap;
406 fetch_refspec = &transport->remote->fetch;
408 for (i = 0; i < fetch_refspec->nr; i++)
409 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
410 } else if (refmap.nr) {
411 die("--refmap option is only meaningful with command-line refspec(s).");
413 /* Use the defaults */
414 struct remote *remote = transport->remote;
415 struct branch *branch = branch_get(NULL);
416 int has_merge = branch_has_merge_config(branch);
419 /* Note: has_merge implies non-NULL branch->remote_name */
420 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
421 for (i = 0; i < remote->fetch.nr; i++) {
422 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
423 if (remote->fetch.items[i].dst &&
424 remote->fetch.items[i].dst[0])
426 if (!i && !has_merge && ref_map &&
427 !remote->fetch.items[0].pattern)
428 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
431 * if the remote we're fetching from is the same
432 * as given in branch.<name>.remote, we add the
433 * ref given in branch.<name>.merge, too.
435 * Note: has_merge implies non-NULL branch->remote_name
438 !strcmp(branch->remote_name, remote->name))
439 add_merge_config(&ref_map, remote_refs, branch, &tail);
441 ref_map = get_remote_ref(remote_refs, "HEAD");
443 die(_("Couldn't find remote ref HEAD"));
444 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
445 tail = &ref_map->next;
449 if (tags == TAGS_SET)
450 /* also fetch all tags */
451 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
452 else if (tags == TAGS_DEFAULT && *autotags)
453 find_non_local_tags(transport, &ref_map, &tail);
455 /* Now append any refs to be updated opportunistically: */
457 for (rm = orefs; rm; rm = rm->next) {
458 rm->fetch_head_status = FETCH_HEAD_IGNORE;
462 ref_map = ref_remove_duplicates(ref_map);
464 for_each_ref(add_existing, &existing_refs);
465 for (rm = ref_map; rm; rm = rm->next) {
467 struct string_list_item *peer_item =
468 string_list_lookup(&existing_refs,
471 struct object_id *old_oid = peer_item->util;
472 oidcpy(&rm->peer_ref->old_oid, old_oid);
476 string_list_clear(&existing_refs, 1);
481 #define STORE_REF_ERROR_OTHER 1
482 #define STORE_REF_ERROR_DF_CONFLICT 2
484 static int s_update_ref(const char *action,
489 char *rla = getenv("GIT_REFLOG_ACTION");
490 struct ref_transaction *transaction;
491 struct strbuf err = STRBUF_INIT;
492 int ret, df_conflict = 0;
497 rla = default_rla.buf;
498 msg = xstrfmt("%s: %s", rla, action);
500 transaction = ref_transaction_begin(&err);
502 ref_transaction_update(transaction, ref->name,
504 check_old ? &ref->old_oid : NULL,
508 ret = ref_transaction_commit(transaction, &err);
510 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
514 ref_transaction_free(transaction);
515 strbuf_release(&err);
519 ref_transaction_free(transaction);
520 error("%s", err.buf);
521 strbuf_release(&err);
523 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
524 : STORE_REF_ERROR_OTHER;
527 static int refcol_width = 10;
528 static int compact_format;
530 static void adjust_refcol_width(const struct ref *ref)
532 int max, rlen, llen, len;
534 /* uptodate lines are only shown on high verbosity level */
535 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
538 max = term_columns();
539 rlen = utf8_strwidth(prettify_refname(ref->name));
541 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
544 * rough estimation to see if the output line is too long and
545 * should not be counted (we can't do precise calculation
546 * anyway because we don't know if the error explanation part
547 * will be printed in update_local_ref)
549 if (compact_format) {
553 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
558 * Not precise calculation for compact mode because '*' can
559 * appear on the left hand side of '->' and shrink the column
562 if (refcol_width < rlen)
566 static void prepare_format_display(struct ref *ref_map)
569 const char *format = "full";
571 git_config_get_string_const("fetch.output", &format);
572 if (!strcasecmp(format, "full"))
574 else if (!strcasecmp(format, "compact"))
577 die(_("configuration fetch.output contains invalid value %s"),
580 for (rm = ref_map; rm; rm = rm->next) {
581 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
583 !strcmp(rm->name, "HEAD"))
586 adjust_refcol_width(rm);
590 static void print_remote_to_local(struct strbuf *display,
591 const char *remote, const char *local)
593 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
596 static int find_and_replace(struct strbuf *haystack,
598 const char *placeholder)
600 const char *p = strstr(haystack->buf, needle);
606 if (p > haystack->buf && p[-1] != '/')
610 nlen = strlen(needle);
611 if (plen > nlen && p[nlen] != '/')
614 strbuf_splice(haystack, p - haystack->buf, nlen,
615 placeholder, strlen(placeholder));
619 static void print_compact(struct strbuf *display,
620 const char *remote, const char *local)
622 struct strbuf r = STRBUF_INIT;
623 struct strbuf l = STRBUF_INIT;
625 if (!strcmp(remote, local)) {
626 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
630 strbuf_addstr(&r, remote);
631 strbuf_addstr(&l, local);
633 if (!find_and_replace(&r, local, "*"))
634 find_and_replace(&l, remote, "*");
635 print_remote_to_local(display, r.buf, l.buf);
641 static void format_display(struct strbuf *display, char code,
642 const char *summary, const char *error,
643 const char *remote, const char *local,
646 int width = (summary_width + strlen(summary) - gettext_width(summary));
648 strbuf_addf(display, "%c %-*s ", code, width, summary);
650 print_remote_to_local(display, remote, local);
652 print_compact(display, remote, local);
654 strbuf_addf(display, " (%s)", error);
657 static int update_local_ref(struct ref *ref,
659 const struct ref *remote_ref,
660 struct strbuf *display,
663 struct commit *current = NULL, *updated;
664 enum object_type type;
665 struct branch *current_branch = branch_get(NULL);
666 const char *pretty_ref = prettify_refname(ref->name);
668 type = oid_object_info(the_repository, &ref->new_oid, NULL);
670 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
672 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
674 format_display(display, '=', _("[up to date]"), NULL,
675 remote, pretty_ref, summary_width);
679 if (current_branch &&
680 !strcmp(ref->name, current_branch->name) &&
681 !(update_head_ok || is_bare_repository()) &&
682 !is_null_oid(&ref->old_oid)) {
684 * If this is the head, and it's not okay to update
685 * the head, and the old value of the head isn't empty...
687 format_display(display, '!', _("[rejected]"),
688 _("can't fetch in current branch"),
689 remote, pretty_ref, summary_width);
693 if (!is_null_oid(&ref->old_oid) &&
694 starts_with(ref->name, "refs/tags/")) {
696 r = s_update_ref("updating tag", ref, 0);
697 format_display(display, r ? '!' : 't', _("[tag update]"),
698 r ? _("unable to update local ref") : NULL,
699 remote, pretty_ref, summary_width);
703 current = lookup_commit_reference_gently(&ref->old_oid, 1);
704 updated = lookup_commit_reference_gently(&ref->new_oid, 1);
705 if (!current || !updated) {
710 * Nicely describe the new ref we're fetching.
711 * Base this on the remote's ref name, as it's
712 * more likely to follow a standard layout.
714 const char *name = remote_ref ? remote_ref->name : "";
715 if (starts_with(name, "refs/tags/")) {
717 what = _("[new tag]");
718 } else if (starts_with(name, "refs/heads/")) {
719 msg = "storing head";
720 what = _("[new branch]");
723 what = _("[new ref]");
726 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
727 (recurse_submodules != RECURSE_SUBMODULES_ON))
728 check_for_new_submodule_commits(&ref->new_oid);
729 r = s_update_ref(msg, ref, 0);
730 format_display(display, r ? '!' : '*', what,
731 r ? _("unable to update local ref") : NULL,
732 remote, pretty_ref, summary_width);
736 if (in_merge_bases(current, updated)) {
737 struct strbuf quickref = STRBUF_INIT;
739 strbuf_add_unique_abbrev(&quickref, ¤t->object.oid, DEFAULT_ABBREV);
740 strbuf_addstr(&quickref, "..");
741 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
742 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
743 (recurse_submodules != RECURSE_SUBMODULES_ON))
744 check_for_new_submodule_commits(&ref->new_oid);
745 r = s_update_ref("fast-forward", ref, 1);
746 format_display(display, r ? '!' : ' ', quickref.buf,
747 r ? _("unable to update local ref") : NULL,
748 remote, pretty_ref, summary_width);
749 strbuf_release(&quickref);
751 } else if (force || ref->force) {
752 struct strbuf quickref = STRBUF_INIT;
754 strbuf_add_unique_abbrev(&quickref, ¤t->object.oid, DEFAULT_ABBREV);
755 strbuf_addstr(&quickref, "...");
756 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
757 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
758 (recurse_submodules != RECURSE_SUBMODULES_ON))
759 check_for_new_submodule_commits(&ref->new_oid);
760 r = s_update_ref("forced-update", ref, 1);
761 format_display(display, r ? '!' : '+', quickref.buf,
762 r ? _("unable to update local ref") : _("forced update"),
763 remote, pretty_ref, summary_width);
764 strbuf_release(&quickref);
767 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
768 remote, pretty_ref, summary_width);
773 static int iterate_ref_map(void *cb_data, struct object_id *oid)
775 struct ref **rm = cb_data;
776 struct ref *ref = *rm;
778 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
781 return -1; /* end of the list */
783 oidcpy(oid, &ref->old_oid);
787 static int store_updated_refs(const char *raw_url, const char *remote_name,
791 struct commit *commit;
792 int url_len, i, rc = 0;
793 struct strbuf note = STRBUF_INIT;
794 const char *what, *kind;
797 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
799 int summary_width = transport_summary_width(ref_map);
801 fp = fopen(filename, "a");
803 return error_errno(_("cannot open %s"), filename);
806 url = transport_anonymize_url(raw_url);
808 url = xstrdup("foreign");
811 if (check_connected(iterate_ref_map, &rm, NULL)) {
812 rc = error(_("%s did not send all necessary objects\n"), url);
816 prepare_format_display(ref_map);
819 * We do a pass for each fetch_head_status type in their enum order, so
820 * merged entries are written before not-for-merge. That lets readers
821 * use FETCH_HEAD as a refname to refer to the ref to be merged.
823 for (want_status = FETCH_HEAD_MERGE;
824 want_status <= FETCH_HEAD_IGNORE;
826 for (rm = ref_map; rm; rm = rm->next) {
827 struct ref *ref = NULL;
828 const char *merge_status_marker = "";
830 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
831 if (want_status == FETCH_HEAD_MERGE)
832 warning(_("reject %s because shallow roots are not allowed to be updated"),
833 rm->peer_ref ? rm->peer_ref->name : rm->name);
837 commit = lookup_commit_reference_gently(&rm->old_oid,
840 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
842 if (rm->fetch_head_status != want_status)
846 ref = alloc_ref(rm->peer_ref->name);
847 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
848 oidcpy(&ref->new_oid, &rm->old_oid);
849 ref->force = rm->peer_ref->force;
853 if (!strcmp(rm->name, "HEAD")) {
857 else if (starts_with(rm->name, "refs/heads/")) {
859 what = rm->name + 11;
861 else if (starts_with(rm->name, "refs/tags/")) {
863 what = rm->name + 10;
865 else if (starts_with(rm->name, "refs/remotes/")) {
866 kind = "remote-tracking branch";
867 what = rm->name + 13;
874 url_len = strlen(url);
875 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
878 if (4 < i && !strncmp(".git", url + i - 3, 4))
884 strbuf_addf(¬e, "%s ", kind);
885 strbuf_addf(¬e, "'%s' of ", what);
887 switch (rm->fetch_head_status) {
888 case FETCH_HEAD_NOT_FOR_MERGE:
889 merge_status_marker = "not-for-merge";
891 case FETCH_HEAD_MERGE:
892 fprintf(fp, "%s\t%s\t%s",
893 oid_to_hex(&rm->old_oid),
896 for (i = 0; i < url_len; ++i)
904 /* do not write anything to FETCH_HEAD */
910 rc |= update_local_ref(ref, what, rm, ¬e,
914 format_display(¬e, '*',
915 *kind ? kind : "branch", NULL,
916 *what ? what : "HEAD",
917 "FETCH_HEAD", summary_width);
919 if (verbosity >= 0 && !shown_url) {
920 fprintf(stderr, _("From %.*s\n"),
925 fprintf(stderr, " %s\n", note.buf);
930 if (rc & STORE_REF_ERROR_DF_CONFLICT)
931 error(_("some local refs could not be updated; try running\n"
932 " 'git remote prune %s' to remove any old, conflicting "
933 "branches"), remote_name);
936 strbuf_release(¬e);
943 * We would want to bypass the object transfer altogether if
944 * everything we are going to fetch already exists and is connected
947 static int quickfetch(struct ref *ref_map)
949 struct ref *rm = ref_map;
950 struct check_connected_options opt = CHECK_CONNECTED_INIT;
953 * If we are deepening a shallow clone we already have these
954 * objects reachable. Running rev-list here will return with
955 * a good (0) exit status and we'll bypass the fetch that we
956 * really need to perform. Claiming failure now will ensure
957 * we perform the network exchange to deepen our history.
962 return check_connected(iterate_ref_map, &rm, &opt);
965 static int fetch_refs(struct transport *transport, struct ref *ref_map)
967 int ret = quickfetch(ref_map);
969 ret = transport_fetch_refs(transport, ref_map);
971 ret |= store_updated_refs(transport->url,
972 transport->remote->name,
974 transport_unlock_pack(transport);
978 static int prune_refs(struct refspec *rs, struct ref *ref_map,
981 int url_len, i, result = 0;
982 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
984 int summary_width = transport_summary_width(stale_refs);
985 const char *dangling_msg = dry_run
986 ? _(" (%s will become dangling)")
987 : _(" (%s has become dangling)");
990 url = transport_anonymize_url(raw_url);
992 url = xstrdup("foreign");
994 url_len = strlen(url);
995 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
999 if (4 < i && !strncmp(".git", url + i - 3, 4))
1003 struct string_list refnames = STRING_LIST_INIT_NODUP;
1005 for (ref = stale_refs; ref; ref = ref->next)
1006 string_list_append(&refnames, ref->name);
1008 result = delete_refs("fetch: prune", &refnames, 0);
1009 string_list_clear(&refnames, 0);
1012 if (verbosity >= 0) {
1013 for (ref = stale_refs; ref; ref = ref->next) {
1014 struct strbuf sb = STRBUF_INIT;
1016 fprintf(stderr, _("From %.*s\n"), url_len, url);
1019 format_display(&sb, '-', _("[deleted]"), NULL,
1020 _("(none)"), prettify_refname(ref->name),
1022 fprintf(stderr, " %s\n",sb.buf);
1023 strbuf_release(&sb);
1024 warn_dangling_symref(stderr, dangling_msg, ref->name);
1029 free_refs(stale_refs);
1033 static void check_not_current_branch(struct ref *ref_map)
1035 struct branch *current_branch = branch_get(NULL);
1037 if (is_bare_repository() || !current_branch)
1040 for (; ref_map; ref_map = ref_map->next)
1041 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1042 ref_map->peer_ref->name))
1043 die(_("Refusing to fetch into current branch %s "
1044 "of non-bare repository"), current_branch->refname);
1047 static int truncate_fetch_head(void)
1049 const char *filename = git_path_fetch_head();
1050 FILE *fp = fopen_for_writing(filename);
1053 return error_errno(_("cannot open %s"), filename);
1058 static void set_option(struct transport *transport, const char *name, const char *value)
1060 int r = transport_set_option(transport, name, value);
1062 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1063 name, value, transport->url);
1065 warning(_("Option \"%s\" is ignored for %s\n"),
1066 name, transport->url);
1069 static struct transport *prepare_transport(struct remote *remote, int deepen)
1071 struct transport *transport;
1072 transport = transport_get(remote, NULL);
1073 transport_set_verbosity(transport, verbosity, progress);
1074 transport->family = family;
1076 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1078 set_option(transport, TRANS_OPT_KEEP, "yes");
1080 set_option(transport, TRANS_OPT_DEPTH, depth);
1081 if (deepen && deepen_since)
1082 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1083 if (deepen && deepen_not.nr)
1084 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1085 (const char *)&deepen_not);
1086 if (deepen_relative)
1087 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1089 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1090 if (filter_options.choice) {
1091 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1092 filter_options.filter_spec);
1093 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1098 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1103 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1104 * when remote helper is used (setting it to an empty string
1105 * is not unsetting). We could extend the remote helper
1106 * protocol for that, but for now, just force a new connection
1107 * without deepen-since. Similar story for deepen-not.
1109 cannot_reuse = transport->cannot_reuse ||
1110 deepen_since || deepen_not.nr;
1112 gsecondary = prepare_transport(transport->remote, 0);
1113 transport = gsecondary;
1116 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1117 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1118 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1119 fetch_refs(transport, ref_map);
1122 transport_disconnect(gsecondary);
1127 static int do_fetch(struct transport *transport,
1130 struct ref *ref_map;
1131 int autotags = (transport->remote->fetch_tags == 1);
1134 if (tags == TAGS_DEFAULT) {
1135 if (transport->remote->fetch_tags == 2)
1137 if (transport->remote->fetch_tags == -1)
1141 /* if not appending, truncate FETCH_HEAD */
1142 if (!append && !dry_run) {
1143 retcode = truncate_fetch_head();
1148 ref_map = get_ref_map(transport, rs, tags, &autotags);
1149 if (!update_head_ok)
1150 check_not_current_branch(ref_map);
1152 if (tags == TAGS_DEFAULT && autotags)
1153 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1156 * We only prune based on refspecs specified
1157 * explicitly (via command line or configuration); we
1158 * don't care whether --tags was specified.
1161 prune_refs(rs, ref_map, transport->url);
1163 prune_refs(&transport->remote->fetch,
1168 if (fetch_refs(transport, ref_map)) {
1175 /* if neither --no-tags nor --tags was specified, do automated tag
1177 if (tags == TAGS_DEFAULT && autotags) {
1178 struct ref **tail = &ref_map;
1180 find_non_local_tags(transport, &ref_map, &tail);
1182 backfill_tags(transport, ref_map);
1190 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1192 struct string_list *list = priv;
1193 if (!remote->skip_default_update)
1194 string_list_append(list, remote->name);
1198 struct remote_group_data {
1200 struct string_list *list;
1203 static int get_remote_group(const char *key, const char *value, void *priv)
1205 struct remote_group_data *g = priv;
1207 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1208 /* split list by white space */
1210 size_t wordlen = strcspn(value, " \t\n");
1213 string_list_append_nodup(g->list,
1214 xstrndup(value, wordlen));
1215 value += wordlen + (value[wordlen] != '\0');
1222 static int add_remote_or_group(const char *name, struct string_list *list)
1224 int prev_nr = list->nr;
1225 struct remote_group_data g;
1226 g.name = name; g.list = list;
1228 git_config(get_remote_group, &g);
1229 if (list->nr == prev_nr) {
1230 struct remote *remote = remote_get(name);
1231 if (!remote_is_configured(remote, 0))
1233 string_list_append(list, remote->name);
1238 static void add_options_to_argv(struct argv_array *argv)
1241 argv_array_push(argv, "--dry-run");
1243 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1244 if (prune_tags != -1)
1245 argv_array_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1247 argv_array_push(argv, "--update-head-ok");
1249 argv_array_push(argv, "--force");
1251 argv_array_push(argv, "--keep");
1252 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1253 argv_array_push(argv, "--recurse-submodules");
1254 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1255 argv_array_push(argv, "--recurse-submodules=on-demand");
1256 if (tags == TAGS_SET)
1257 argv_array_push(argv, "--tags");
1258 else if (tags == TAGS_UNSET)
1259 argv_array_push(argv, "--no-tags");
1261 argv_array_push(argv, "-v");
1263 argv_array_push(argv, "-v");
1264 else if (verbosity < 0)
1265 argv_array_push(argv, "-q");
1269 static int fetch_multiple(struct string_list *list)
1272 struct argv_array argv = ARGV_ARRAY_INIT;
1274 if (!append && !dry_run) {
1275 int errcode = truncate_fetch_head();
1280 argv_array_pushl(&argv, "fetch", "--append", NULL);
1281 add_options_to_argv(&argv);
1283 for (i = 0; i < list->nr; i++) {
1284 const char *name = list->items[i].string;
1285 argv_array_push(&argv, name);
1287 printf(_("Fetching %s\n"), name);
1288 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1289 error(_("Could not fetch %s"), name);
1292 argv_array_pop(&argv);
1295 argv_array_clear(&argv);
1300 * Fetching from the promisor remote should use the given filter-spec
1301 * or inherit the default filter-spec from the config.
1303 static inline void fetch_one_setup_partial(struct remote *remote)
1306 * Explicit --no-filter argument overrides everything, regardless
1307 * of any prior partial clones and fetches.
1309 if (filter_options.no_filter)
1313 * If no prior partial clone/fetch and the current fetch DID NOT
1314 * request a partial-fetch, do a normal fetch.
1316 if (!repository_format_partial_clone && !filter_options.choice)
1320 * If this is the FIRST partial-fetch request, we enable partial
1321 * on this repo and remember the given filter-spec as the default
1322 * for subsequent fetches to this remote.
1324 if (!repository_format_partial_clone && filter_options.choice) {
1325 partial_clone_register(remote->name, &filter_options);
1330 * We are currently limited to only ONE promisor remote and only
1331 * allow partial-fetches from the promisor remote.
1333 if (strcmp(remote->name, repository_format_partial_clone)) {
1334 if (filter_options.choice)
1335 die(_("--filter can only be used with the remote configured in core.partialClone"));
1340 * Do a partial-fetch from the promisor remote using either the
1341 * explicitly given filter-spec or inherit the filter-spec from
1344 if (!filter_options.choice)
1345 partial_clone_get_default_filter_spec(&filter_options);
1349 static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
1351 struct refspec rs = REFSPEC_INIT_FETCH;
1354 int maybe_prune_tags;
1355 int remote_via_config = remote_is_configured(remote, 0);
1358 die(_("No remote repository specified. Please, specify either a URL or a\n"
1359 "remote name from which new revisions should be fetched."));
1361 gtransport = prepare_transport(remote, 1);
1364 /* no command line request */
1365 if (0 <= remote->prune)
1366 prune = remote->prune;
1367 else if (0 <= fetch_prune_config)
1368 prune = fetch_prune_config;
1370 prune = PRUNE_BY_DEFAULT;
1373 if (prune_tags < 0) {
1374 /* no command line request */
1375 if (0 <= remote->prune_tags)
1376 prune_tags = remote->prune_tags;
1377 else if (0 <= fetch_prune_tags_config)
1378 prune_tags = fetch_prune_tags_config;
1380 prune_tags = PRUNE_TAGS_BY_DEFAULT;
1383 maybe_prune_tags = prune_tags_ok && prune_tags;
1384 if (maybe_prune_tags && remote_via_config)
1385 refspec_append(&remote->fetch, TAG_REFSPEC);
1387 if (maybe_prune_tags && (argc || !remote_via_config))
1388 refspec_append(&rs, TAG_REFSPEC);
1390 for (i = 0; i < argc; i++) {
1391 if (!strcmp(argv[i], "tag")) {
1395 die(_("You need to specify a tag name."));
1397 tag = xstrfmt("refs/tags/%s:refs/tags/%s",
1399 refspec_append(&rs, tag);
1402 refspec_append(&rs, argv[i]);
1406 if (server_options.nr)
1407 gtransport->server_options = &server_options;
1409 sigchain_push_common(unlock_pack_on_signal);
1410 atexit(unlock_pack);
1411 exit_code = do_fetch(gtransport, &rs);
1413 transport_disconnect(gtransport);
1418 int cmd_fetch(int argc, const char **argv, const char *prefix)
1421 struct string_list list = STRING_LIST_INIT_DUP;
1422 struct remote *remote = NULL;
1424 int prune_tags_ok = 1;
1425 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1427 packet_trace_identity("fetch");
1429 fetch_if_missing = 0;
1431 /* Record the command line for the reflog */
1432 strbuf_addstr(&default_rla, "fetch");
1433 for (i = 1; i < argc; i++)
1434 strbuf_addf(&default_rla, " %s", argv[i]);
1436 config_from_gitmodules(gitmodules_fetch_config, NULL);
1437 git_config(git_fetch_config, NULL);
1439 argc = parse_options(argc, argv, prefix,
1440 builtin_fetch_options, builtin_fetch_usage, 0);
1442 if (deepen_relative) {
1443 if (deepen_relative < 0)
1444 die(_("Negative depth in --deepen is not supported"));
1446 die(_("--deepen and --depth are mutually exclusive"));
1447 depth = xstrfmt("%d", deepen_relative);
1451 die(_("--depth and --unshallow cannot be used together"));
1452 else if (!is_repository_shallow())
1453 die(_("--unshallow on a complete repository does not make sense"));
1455 depth = xstrfmt("%d", INFINITE_DEPTH);
1458 /* no need to be strict, transport_set_option() will validate it again */
1459 if (depth && atoi(depth) < 1)
1460 die(_("depth %s is not a positive number"), depth);
1461 if (depth || deepen_since || deepen_not.nr)
1464 if (filter_options.choice && !repository_format_partial_clone)
1465 die("--filter can only be used when extensions.partialClone is set");
1469 die(_("fetch --all does not take a repository argument"));
1471 die(_("fetch --all does not make sense with refspecs"));
1472 (void) for_each_remote(get_one_remote_for_fetch, &list);
1473 } else if (argc == 0) {
1474 /* No arguments -- use default remote */
1475 remote = remote_get(NULL);
1476 } else if (multiple) {
1477 /* All arguments are assumed to be remotes or groups */
1478 for (i = 0; i < argc; i++)
1479 if (!add_remote_or_group(argv[i], &list))
1480 die(_("No such remote or remote group: %s"), argv[i]);
1482 /* Single remote or group */
1483 (void) add_remote_or_group(argv[0], &list);
1485 /* More than one remote */
1487 die(_("Fetching a group and specifying refspecs does not make sense"));
1489 /* Zero or one remotes */
1490 remote = remote_get(argv[0]);
1491 prune_tags_ok = (argc == 1);
1498 if (filter_options.choice || repository_format_partial_clone)
1499 fetch_one_setup_partial(remote);
1500 result = fetch_one(remote, argc, argv, prune_tags_ok);
1502 if (filter_options.choice)
1503 die(_("--filter can only be used with the remote configured in core.partialClone"));
1504 /* TODO should this also die if we have a previous partial-clone? */
1505 result = fetch_multiple(&list);
1508 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1509 struct argv_array options = ARGV_ARRAY_INIT;
1511 add_options_to_argv(&options);
1512 result = fetch_populated_submodules(the_repository,
1516 recurse_submodules_default,
1519 argv_array_clear(&options);
1522 string_list_clear(&list, 0);
1524 close_all_packs(the_repository->objects);
1526 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1528 argv_array_push(&argv_gc_auto, "--quiet");
1529 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1530 argv_array_clear(&argv_gc_auto);