notes.c: use designated initializers for clarity
[git/debian.git] / builtin / fetch.c
blob85bd2801036a8401a096043e26db1aeadc44d325
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "gettext.h"
7 #include "environment.h"
8 #include "hex.h"
9 #include "repository.h"
10 #include "refs.h"
11 #include "refspec.h"
12 #include "object-store.h"
13 #include "oidset.h"
14 #include "commit.h"
15 #include "builtin.h"
16 #include "string-list.h"
17 #include "remote.h"
18 #include "transport.h"
19 #include "run-command.h"
20 #include "parse-options.h"
21 #include "sigchain.h"
22 #include "submodule-config.h"
23 #include "submodule.h"
24 #include "connected.h"
25 #include "strvec.h"
26 #include "utf8.h"
27 #include "packfile.h"
28 #include "list-objects-filter-options.h"
29 #include "commit-reach.h"
30 #include "branch.h"
31 #include "promisor-remote.h"
32 #include "commit-graph.h"
33 #include "shallow.h"
34 #include "worktree.h"
35 #include "bundle-uri.h"
37 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
39 static const char * const builtin_fetch_usage[] = {
40 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
41 N_("git fetch [<options>] <group>"),
42 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
43 N_("git fetch --all [<options>]"),
44 NULL
47 enum {
48 TAGS_UNSET = 0,
49 TAGS_DEFAULT = 1,
50 TAGS_SET = 2
53 struct display_state {
54 struct strbuf buf;
56 int refcol_width;
57 int compact_format;
59 char *url;
60 int url_len, shown_url;
63 static int fetch_prune_config = -1; /* unspecified */
64 static int fetch_show_forced_updates = 1;
65 static uint64_t forced_updates_ms = 0;
66 static int prefetch = 0;
67 static int prune = -1; /* unspecified */
68 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
70 static int fetch_prune_tags_config = -1; /* unspecified */
71 static int prune_tags = -1; /* unspecified */
72 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
74 static int all, append, dry_run, force, keep, multiple, update_head_ok;
75 static int write_fetch_head = 1;
76 static int verbosity, deepen_relative, set_upstream, refetch;
77 static int progress = -1;
78 static int enable_auto_gc = 1;
79 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
80 static int max_jobs = -1, submodule_fetch_jobs_config = -1;
81 static int fetch_parallel_config = 1;
82 static int atomic_fetch;
83 static enum transport_family family;
84 static const char *depth;
85 static const char *deepen_since;
86 static const char *upload_pack;
87 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
88 static struct strbuf default_rla = STRBUF_INIT;
89 static struct transport *gtransport;
90 static struct transport *gsecondary;
91 static const char *submodule_prefix = "";
92 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
93 static int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
94 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
95 static struct refspec refmap = REFSPEC_INIT_FETCH;
96 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
97 static struct string_list server_options = STRING_LIST_INIT_DUP;
98 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
99 static int fetch_write_commit_graph = -1;
100 static int stdin_refspecs = 0;
101 static int negotiate_only;
103 static int git_fetch_config(const char *k, const char *v, void *cb)
105 if (!strcmp(k, "fetch.prune")) {
106 fetch_prune_config = git_config_bool(k, v);
107 return 0;
110 if (!strcmp(k, "fetch.prunetags")) {
111 fetch_prune_tags_config = git_config_bool(k, v);
112 return 0;
115 if (!strcmp(k, "fetch.showforcedupdates")) {
116 fetch_show_forced_updates = git_config_bool(k, v);
117 return 0;
120 if (!strcmp(k, "submodule.recurse")) {
121 int r = git_config_bool(k, v) ?
122 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
123 recurse_submodules = r;
126 if (!strcmp(k, "submodule.fetchjobs")) {
127 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
128 return 0;
129 } else if (!strcmp(k, "fetch.recursesubmodules")) {
130 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
131 return 0;
134 if (!strcmp(k, "fetch.parallel")) {
135 fetch_parallel_config = git_config_int(k, v);
136 if (fetch_parallel_config < 0)
137 die(_("fetch.parallel cannot be negative"));
138 if (!fetch_parallel_config)
139 fetch_parallel_config = online_cpus();
140 return 0;
143 return git_default_config(k, v, cb);
146 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
148 BUG_ON_OPT_NEG(unset);
151 * "git fetch --refmap='' origin foo"
152 * can be used to tell the command not to store anywhere
154 refspec_append(&refmap, arg);
156 return 0;
159 static struct option builtin_fetch_options[] = {
160 OPT__VERBOSITY(&verbosity),
161 OPT_BOOL(0, "all", &all,
162 N_("fetch from all remotes")),
163 OPT_BOOL(0, "set-upstream", &set_upstream,
164 N_("set upstream for git pull/fetch")),
165 OPT_BOOL('a', "append", &append,
166 N_("append to .git/FETCH_HEAD instead of overwriting")),
167 OPT_BOOL(0, "atomic", &atomic_fetch,
168 N_("use atomic transaction to update references")),
169 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
170 N_("path to upload pack on remote end")),
171 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
172 OPT_BOOL('m', "multiple", &multiple,
173 N_("fetch from multiple remotes")),
174 OPT_SET_INT('t', "tags", &tags,
175 N_("fetch all tags and associated objects"), TAGS_SET),
176 OPT_SET_INT('n', NULL, &tags,
177 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
178 OPT_INTEGER('j', "jobs", &max_jobs,
179 N_("number of submodules fetched in parallel")),
180 OPT_BOOL(0, "prefetch", &prefetch,
181 N_("modify the refspec to place all refs within refs/prefetch/")),
182 OPT_BOOL('p', "prune", &prune,
183 N_("prune remote-tracking branches no longer on remote")),
184 OPT_BOOL('P', "prune-tags", &prune_tags,
185 N_("prune local tags no longer on remote and clobber changed tags")),
186 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
187 N_("control recursive fetching of submodules"),
188 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
189 OPT_BOOL(0, "dry-run", &dry_run,
190 N_("dry run")),
191 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
192 N_("write fetched references to the FETCH_HEAD file")),
193 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
194 OPT_BOOL('u', "update-head-ok", &update_head_ok,
195 N_("allow updating of HEAD ref")),
196 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
197 OPT_STRING(0, "depth", &depth, N_("depth"),
198 N_("deepen history of shallow clone")),
199 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
200 N_("deepen history of shallow repository based on time")),
201 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
202 N_("deepen history of shallow clone, excluding rev")),
203 OPT_INTEGER(0, "deepen", &deepen_relative,
204 N_("deepen history of shallow clone")),
205 OPT_SET_INT_F(0, "unshallow", &unshallow,
206 N_("convert to a complete repository"),
207 1, PARSE_OPT_NONEG),
208 OPT_SET_INT_F(0, "refetch", &refetch,
209 N_("re-fetch without negotiating common commits"),
210 1, PARSE_OPT_NONEG),
211 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
212 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
213 OPT_CALLBACK_F(0, "recurse-submodules-default",
214 &recurse_submodules_default, N_("on-demand"),
215 N_("default for recursive fetching of submodules "
216 "(lower priority than config files)"),
217 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
218 OPT_BOOL(0, "update-shallow", &update_shallow,
219 N_("accept refs that update .git/shallow")),
220 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
221 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
222 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
223 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
224 TRANSPORT_FAMILY_IPV4),
225 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
226 TRANSPORT_FAMILY_IPV6),
227 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
228 N_("report that we have only objects reachable from this object")),
229 OPT_BOOL(0, "negotiate-only", &negotiate_only,
230 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
231 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
232 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
233 N_("run 'maintenance --auto' after fetching")),
234 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
235 N_("run 'maintenance --auto' after fetching")),
236 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
237 N_("check for forced-updates on all updated branches")),
238 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
239 N_("write the commit-graph after fetching")),
240 OPT_BOOL(0, "stdin", &stdin_refspecs,
241 N_("accept refspecs from stdin")),
242 OPT_END()
245 static void unlock_pack(unsigned int flags)
247 if (gtransport)
248 transport_unlock_pack(gtransport, flags);
249 if (gsecondary)
250 transport_unlock_pack(gsecondary, flags);
253 static void unlock_pack_atexit(void)
255 unlock_pack(0);
258 static void unlock_pack_on_signal(int signo)
260 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
261 sigchain_pop(signo);
262 raise(signo);
265 static void add_merge_config(struct ref **head,
266 const struct ref *remote_refs,
267 struct branch *branch,
268 struct ref ***tail)
270 int i;
272 for (i = 0; i < branch->merge_nr; i++) {
273 struct ref *rm, **old_tail = *tail;
274 struct refspec_item refspec;
276 for (rm = *head; rm; rm = rm->next) {
277 if (branch_merge_matches(branch, i, rm->name)) {
278 rm->fetch_head_status = FETCH_HEAD_MERGE;
279 break;
282 if (rm)
283 continue;
286 * Not fetched to a remote-tracking branch? We need to fetch
287 * it anyway to allow this branch's "branch.$name.merge"
288 * to be honored by 'git pull', but we do not have to
289 * fail if branch.$name.merge is misconfigured to point
290 * at a nonexisting branch. If we were indeed called by
291 * 'git pull', it will notice the misconfiguration because
292 * there is no entry in the resulting FETCH_HEAD marked
293 * for merging.
295 memset(&refspec, 0, sizeof(refspec));
296 refspec.src = branch->merge[i]->src;
297 get_fetch_map(remote_refs, &refspec, tail, 1);
298 for (rm = *old_tail; rm; rm = rm->next)
299 rm->fetch_head_status = FETCH_HEAD_MERGE;
303 static void create_fetch_oidset(struct ref **head, struct oidset *out)
305 struct ref *rm = *head;
306 while (rm) {
307 oidset_insert(out, &rm->old_oid);
308 rm = rm->next;
312 struct refname_hash_entry {
313 struct hashmap_entry ent;
314 struct object_id oid;
315 int ignore;
316 char refname[FLEX_ARRAY];
319 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
320 const struct hashmap_entry *eptr,
321 const struct hashmap_entry *entry_or_key,
322 const void *keydata)
324 const struct refname_hash_entry *e1, *e2;
326 e1 = container_of(eptr, const struct refname_hash_entry, ent);
327 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
328 return strcmp(e1->refname, keydata ? keydata : e2->refname);
331 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
332 const char *refname,
333 const struct object_id *oid)
335 struct refname_hash_entry *ent;
336 size_t len = strlen(refname);
338 FLEX_ALLOC_MEM(ent, refname, refname, len);
339 hashmap_entry_init(&ent->ent, strhash(refname));
340 oidcpy(&ent->oid, oid);
341 hashmap_add(map, &ent->ent);
342 return ent;
345 static int add_one_refname(const char *refname,
346 const struct object_id *oid,
347 int flag UNUSED, void *cbdata)
349 struct hashmap *refname_map = cbdata;
351 (void) refname_hash_add(refname_map, refname, oid);
352 return 0;
355 static void refname_hash_init(struct hashmap *map)
357 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
360 static int refname_hash_exists(struct hashmap *map, const char *refname)
362 return !!hashmap_get_from_hash(map, strhash(refname), refname);
365 static void clear_item(struct refname_hash_entry *item)
367 item->ignore = 1;
371 static void add_already_queued_tags(const char *refname,
372 const struct object_id *old_oid,
373 const struct object_id *new_oid,
374 void *cb_data)
376 struct hashmap *queued_tags = cb_data;
377 if (starts_with(refname, "refs/tags/") && new_oid)
378 (void) refname_hash_add(queued_tags, refname, new_oid);
381 static void find_non_local_tags(const struct ref *refs,
382 struct ref_transaction *transaction,
383 struct ref **head,
384 struct ref ***tail)
386 struct hashmap existing_refs;
387 struct hashmap remote_refs;
388 struct oidset fetch_oids = OIDSET_INIT;
389 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
390 struct string_list_item *remote_ref_item;
391 const struct ref *ref;
392 struct refname_hash_entry *item = NULL;
393 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
395 refname_hash_init(&existing_refs);
396 refname_hash_init(&remote_refs);
397 create_fetch_oidset(head, &fetch_oids);
399 for_each_ref(add_one_refname, &existing_refs);
402 * If we already have a transaction, then we need to filter out all
403 * tags which have already been queued up.
405 if (transaction)
406 ref_transaction_for_each_queued_update(transaction,
407 add_already_queued_tags,
408 &existing_refs);
410 for (ref = refs; ref; ref = ref->next) {
411 if (!starts_with(ref->name, "refs/tags/"))
412 continue;
415 * The peeled ref always follows the matching base
416 * ref, so if we see a peeled ref that we don't want
417 * to fetch then we can mark the ref entry in the list
418 * as one to ignore by setting util to NULL.
420 if (ends_with(ref->name, "^{}")) {
421 if (item &&
422 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
423 !oidset_contains(&fetch_oids, &ref->old_oid) &&
424 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
425 !oidset_contains(&fetch_oids, &item->oid))
426 clear_item(item);
427 item = NULL;
428 continue;
432 * If item is non-NULL here, then we previously saw a
433 * ref not followed by a peeled reference, so we need
434 * to check if it is a lightweight tag that we want to
435 * fetch.
437 if (item &&
438 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
439 !oidset_contains(&fetch_oids, &item->oid))
440 clear_item(item);
442 item = NULL;
444 /* skip duplicates and refs that we already have */
445 if (refname_hash_exists(&remote_refs, ref->name) ||
446 refname_hash_exists(&existing_refs, ref->name))
447 continue;
449 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
450 string_list_insert(&remote_refs_list, ref->name);
452 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
455 * We may have a final lightweight tag that needs to be
456 * checked to see if it needs fetching.
458 if (item &&
459 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
460 !oidset_contains(&fetch_oids, &item->oid))
461 clear_item(item);
464 * For all the tags in the remote_refs_list,
465 * add them to the list of refs to be fetched
467 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
468 const char *refname = remote_ref_item->string;
469 struct ref *rm;
470 unsigned int hash = strhash(refname);
472 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
473 struct refname_hash_entry, ent);
474 if (!item)
475 BUG("unseen remote ref?");
477 /* Unless we have already decided to ignore this item... */
478 if (item->ignore)
479 continue;
481 rm = alloc_ref(item->refname);
482 rm->peer_ref = alloc_ref(item->refname);
483 oidcpy(&rm->old_oid, &item->oid);
484 **tail = rm;
485 *tail = &rm->next;
487 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
488 string_list_clear(&remote_refs_list, 0);
489 oidset_clear(&fetch_oids);
492 static void filter_prefetch_refspec(struct refspec *rs)
494 int i;
496 if (!prefetch)
497 return;
499 for (i = 0; i < rs->nr; i++) {
500 struct strbuf new_dst = STRBUF_INIT;
501 char *old_dst;
502 const char *sub = NULL;
504 if (rs->items[i].negative)
505 continue;
506 if (!rs->items[i].dst ||
507 (rs->items[i].src &&
508 !strncmp(rs->items[i].src,
509 ref_namespace[NAMESPACE_TAGS].ref,
510 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
511 int j;
513 free(rs->items[i].src);
514 free(rs->items[i].dst);
516 for (j = i + 1; j < rs->nr; j++) {
517 rs->items[j - 1] = rs->items[j];
518 rs->raw[j - 1] = rs->raw[j];
520 rs->nr--;
521 i--;
522 continue;
525 old_dst = rs->items[i].dst;
526 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
529 * If old_dst starts with "refs/", then place
530 * sub after that prefix. Otherwise, start at
531 * the beginning of the string.
533 if (!skip_prefix(old_dst, "refs/", &sub))
534 sub = old_dst;
535 strbuf_addstr(&new_dst, sub);
537 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
538 rs->items[i].force = 1;
540 free(old_dst);
544 static struct ref *get_ref_map(struct remote *remote,
545 const struct ref *remote_refs,
546 struct refspec *rs,
547 int tags, int *autotags)
549 int i;
550 struct ref *rm;
551 struct ref *ref_map = NULL;
552 struct ref **tail = &ref_map;
554 /* opportunistically-updated references: */
555 struct ref *orefs = NULL, **oref_tail = &orefs;
557 struct hashmap existing_refs;
558 int existing_refs_populated = 0;
560 filter_prefetch_refspec(rs);
561 if (remote)
562 filter_prefetch_refspec(&remote->fetch);
564 if (rs->nr) {
565 struct refspec *fetch_refspec;
567 for (i = 0; i < rs->nr; i++) {
568 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
569 if (rs->items[i].dst && rs->items[i].dst[0])
570 *autotags = 1;
572 /* Merge everything on the command line (but not --tags) */
573 for (rm = ref_map; rm; rm = rm->next)
574 rm->fetch_head_status = FETCH_HEAD_MERGE;
577 * For any refs that we happen to be fetching via
578 * command-line arguments, the destination ref might
579 * have been missing or have been different than the
580 * remote-tracking ref that would be derived from the
581 * configured refspec. In these cases, we want to
582 * take the opportunity to update their configured
583 * remote-tracking reference. However, we do not want
584 * to mention these entries in FETCH_HEAD at all, as
585 * they would simply be duplicates of existing
586 * entries, so we set them FETCH_HEAD_IGNORE below.
588 * We compute these entries now, based only on the
589 * refspecs specified on the command line. But we add
590 * them to the list following the refspecs resulting
591 * from the tags option so that one of the latter,
592 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
593 * by ref_remove_duplicates() in favor of one of these
594 * opportunistic entries with FETCH_HEAD_IGNORE.
596 if (refmap.nr)
597 fetch_refspec = &refmap;
598 else
599 fetch_refspec = &remote->fetch;
601 for (i = 0; i < fetch_refspec->nr; i++)
602 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
603 } else if (refmap.nr) {
604 die("--refmap option is only meaningful with command-line refspec(s)");
605 } else {
606 /* Use the defaults */
607 struct branch *branch = branch_get(NULL);
608 int has_merge = branch_has_merge_config(branch);
609 if (remote &&
610 (remote->fetch.nr ||
611 /* Note: has_merge implies non-NULL branch->remote_name */
612 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
613 for (i = 0; i < remote->fetch.nr; i++) {
614 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
615 if (remote->fetch.items[i].dst &&
616 remote->fetch.items[i].dst[0])
617 *autotags = 1;
618 if (!i && !has_merge && ref_map &&
619 !remote->fetch.items[0].pattern)
620 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
623 * if the remote we're fetching from is the same
624 * as given in branch.<name>.remote, we add the
625 * ref given in branch.<name>.merge, too.
627 * Note: has_merge implies non-NULL branch->remote_name
629 if (has_merge &&
630 !strcmp(branch->remote_name, remote->name))
631 add_merge_config(&ref_map, remote_refs, branch, &tail);
632 } else if (!prefetch) {
633 ref_map = get_remote_ref(remote_refs, "HEAD");
634 if (!ref_map)
635 die(_("couldn't find remote ref HEAD"));
636 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
637 tail = &ref_map->next;
641 if (tags == TAGS_SET)
642 /* also fetch all tags */
643 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
644 else if (tags == TAGS_DEFAULT && *autotags)
645 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
647 /* Now append any refs to be updated opportunistically: */
648 *tail = orefs;
649 for (rm = orefs; rm; rm = rm->next) {
650 rm->fetch_head_status = FETCH_HEAD_IGNORE;
651 tail = &rm->next;
655 * apply negative refspecs first, before we remove duplicates. This is
656 * necessary as negative refspecs might remove an otherwise conflicting
657 * duplicate.
659 if (rs->nr)
660 ref_map = apply_negative_refspecs(ref_map, rs);
661 else
662 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
664 ref_map = ref_remove_duplicates(ref_map);
666 for (rm = ref_map; rm; rm = rm->next) {
667 if (rm->peer_ref) {
668 const char *refname = rm->peer_ref->name;
669 struct refname_hash_entry *peer_item;
670 unsigned int hash = strhash(refname);
672 if (!existing_refs_populated) {
673 refname_hash_init(&existing_refs);
674 for_each_ref(add_one_refname, &existing_refs);
675 existing_refs_populated = 1;
678 peer_item = hashmap_get_entry_from_hash(&existing_refs,
679 hash, refname,
680 struct refname_hash_entry, ent);
681 if (peer_item) {
682 struct object_id *old_oid = &peer_item->oid;
683 oidcpy(&rm->peer_ref->old_oid, old_oid);
687 if (existing_refs_populated)
688 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
690 return ref_map;
693 #define STORE_REF_ERROR_OTHER 1
694 #define STORE_REF_ERROR_DF_CONFLICT 2
696 static int s_update_ref(const char *action,
697 struct ref *ref,
698 struct ref_transaction *transaction,
699 int check_old)
701 char *msg;
702 char *rla = getenv("GIT_REFLOG_ACTION");
703 struct ref_transaction *our_transaction = NULL;
704 struct strbuf err = STRBUF_INIT;
705 int ret;
707 if (dry_run)
708 return 0;
709 if (!rla)
710 rla = default_rla.buf;
711 msg = xstrfmt("%s: %s", rla, action);
714 * If no transaction was passed to us, we manage the transaction
715 * ourselves. Otherwise, we trust the caller to handle the transaction
716 * lifecycle.
718 if (!transaction) {
719 transaction = our_transaction = ref_transaction_begin(&err);
720 if (!transaction) {
721 ret = STORE_REF_ERROR_OTHER;
722 goto out;
726 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
727 check_old ? &ref->old_oid : NULL,
728 0, msg, &err);
729 if (ret) {
730 ret = STORE_REF_ERROR_OTHER;
731 goto out;
734 if (our_transaction) {
735 switch (ref_transaction_commit(our_transaction, &err)) {
736 case 0:
737 break;
738 case TRANSACTION_NAME_CONFLICT:
739 ret = STORE_REF_ERROR_DF_CONFLICT;
740 goto out;
741 default:
742 ret = STORE_REF_ERROR_OTHER;
743 goto out;
747 out:
748 ref_transaction_free(our_transaction);
749 if (ret)
750 error("%s", err.buf);
751 strbuf_release(&err);
752 free(msg);
753 return ret;
756 static int refcol_width(const struct ref *ref, int compact_format)
758 int max, rlen, llen, len;
760 /* uptodate lines are only shown on high verbosity level */
761 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
762 return 0;
764 max = term_columns();
765 rlen = utf8_strwidth(prettify_refname(ref->name));
767 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
770 * rough estimation to see if the output line is too long and
771 * should not be counted (we can't do precise calculation
772 * anyway because we don't know if the error explanation part
773 * will be printed in update_local_ref)
775 if (compact_format) {
776 llen = 0;
777 max = max * 2 / 3;
779 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
780 if (len >= max)
781 return 0;
783 return rlen;
786 static void display_state_init(struct display_state *display_state, struct ref *ref_map,
787 const char *raw_url)
789 struct ref *rm;
790 const char *format = "full";
791 int i;
793 memset(display_state, 0, sizeof(*display_state));
795 strbuf_init(&display_state->buf, 0);
797 if (raw_url)
798 display_state->url = transport_anonymize_url(raw_url);
799 else
800 display_state->url = xstrdup("foreign");
802 display_state->url_len = strlen(display_state->url);
803 for (i = display_state->url_len - 1; display_state->url[i] == '/' && 0 <= i; i--)
805 display_state->url_len = i + 1;
806 if (4 < i && !strncmp(".git", display_state->url + i - 3, 4))
807 display_state->url_len = i - 3;
809 if (verbosity < 0)
810 return;
812 git_config_get_string_tmp("fetch.output", &format);
813 if (!strcasecmp(format, "full"))
814 display_state->compact_format = 0;
815 else if (!strcasecmp(format, "compact"))
816 display_state->compact_format = 1;
817 else
818 die(_("invalid value for '%s': '%s'"),
819 "fetch.output", format);
821 display_state->refcol_width = 10;
822 for (rm = ref_map; rm; rm = rm->next) {
823 int width;
825 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
826 !rm->peer_ref ||
827 !strcmp(rm->name, "HEAD"))
828 continue;
830 width = refcol_width(rm, display_state->compact_format);
833 * Not precise calculation for compact mode because '*' can
834 * appear on the left hand side of '->' and shrink the column
835 * back.
837 if (display_state->refcol_width < width)
838 display_state->refcol_width = width;
842 static void display_state_release(struct display_state *display_state)
844 strbuf_release(&display_state->buf);
845 free(display_state->url);
848 static void print_remote_to_local(struct display_state *display_state,
849 const char *remote, const char *local)
851 strbuf_addf(&display_state->buf, "%-*s -> %s",
852 display_state->refcol_width, remote, local);
855 static int find_and_replace(struct strbuf *haystack,
856 const char *needle,
857 const char *placeholder)
859 const char *p = NULL;
860 int plen, nlen;
862 nlen = strlen(needle);
863 if (ends_with(haystack->buf, needle))
864 p = haystack->buf + haystack->len - nlen;
865 else
866 p = strstr(haystack->buf, needle);
867 if (!p)
868 return 0;
870 if (p > haystack->buf && p[-1] != '/')
871 return 0;
873 plen = strlen(p);
874 if (plen > nlen && p[nlen] != '/')
875 return 0;
877 strbuf_splice(haystack, p - haystack->buf, nlen,
878 placeholder, strlen(placeholder));
879 return 1;
882 static void print_compact(struct display_state *display_state,
883 const char *remote, const char *local)
885 struct strbuf r = STRBUF_INIT;
886 struct strbuf l = STRBUF_INIT;
888 if (!strcmp(remote, local)) {
889 strbuf_addf(&display_state->buf, "%-*s -> *", display_state->refcol_width, remote);
890 return;
893 strbuf_addstr(&r, remote);
894 strbuf_addstr(&l, local);
896 if (!find_and_replace(&r, local, "*"))
897 find_and_replace(&l, remote, "*");
898 print_remote_to_local(display_state, r.buf, l.buf);
900 strbuf_release(&r);
901 strbuf_release(&l);
904 static void display_ref_update(struct display_state *display_state, char code,
905 const char *summary, const char *error,
906 const char *remote, const char *local,
907 int summary_width)
909 int width;
911 if (verbosity < 0)
912 return;
914 strbuf_reset(&display_state->buf);
916 if (!display_state->shown_url) {
917 strbuf_addf(&display_state->buf, _("From %.*s\n"),
918 display_state->url_len, display_state->url);
919 display_state->shown_url = 1;
922 width = (summary_width + strlen(summary) - gettext_width(summary));
924 strbuf_addf(&display_state->buf, " %c %-*s ", code, width, summary);
925 if (!display_state->compact_format)
926 print_remote_to_local(display_state, remote, prettify_refname(local));
927 else
928 print_compact(display_state, remote, prettify_refname(local));
929 if (error)
930 strbuf_addf(&display_state->buf, " (%s)", error);
931 strbuf_addch(&display_state->buf, '\n');
933 fputs(display_state->buf.buf, stderr);
936 static int update_local_ref(struct ref *ref,
937 struct ref_transaction *transaction,
938 struct display_state *display_state,
939 const char *remote, const struct ref *remote_ref,
940 int summary_width)
942 struct commit *current = NULL, *updated;
943 int fast_forward = 0;
945 if (!repo_has_object_file(the_repository, &ref->new_oid))
946 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
948 if (oideq(&ref->old_oid, &ref->new_oid)) {
949 if (verbosity > 0)
950 display_ref_update(display_state, '=', _("[up to date]"), NULL,
951 remote, ref->name, summary_width);
952 return 0;
955 if (!update_head_ok &&
956 !is_null_oid(&ref->old_oid) &&
957 branch_checked_out(ref->name)) {
959 * If this is the head, and it's not okay to update
960 * the head, and the old value of the head isn't empty...
962 display_ref_update(display_state, '!', _("[rejected]"),
963 _("can't fetch into checked-out branch"),
964 remote, ref->name, summary_width);
965 return 1;
968 if (!is_null_oid(&ref->old_oid) &&
969 starts_with(ref->name, "refs/tags/")) {
970 if (force || ref->force) {
971 int r;
972 r = s_update_ref("updating tag", ref, transaction, 0);
973 display_ref_update(display_state, r ? '!' : 't', _("[tag update]"),
974 r ? _("unable to update local ref") : NULL,
975 remote, ref->name, summary_width);
976 return r;
977 } else {
978 display_ref_update(display_state, '!', _("[rejected]"),
979 _("would clobber existing tag"),
980 remote, ref->name, summary_width);
981 return 1;
985 current = lookup_commit_reference_gently(the_repository,
986 &ref->old_oid, 1);
987 updated = lookup_commit_reference_gently(the_repository,
988 &ref->new_oid, 1);
989 if (!current || !updated) {
990 const char *msg;
991 const char *what;
992 int r;
994 * Nicely describe the new ref we're fetching.
995 * Base this on the remote's ref name, as it's
996 * more likely to follow a standard layout.
998 const char *name = remote_ref ? remote_ref->name : "";
999 if (starts_with(name, "refs/tags/")) {
1000 msg = "storing tag";
1001 what = _("[new tag]");
1002 } else if (starts_with(name, "refs/heads/")) {
1003 msg = "storing head";
1004 what = _("[new branch]");
1005 } else {
1006 msg = "storing ref";
1007 what = _("[new ref]");
1010 r = s_update_ref(msg, ref, transaction, 0);
1011 display_ref_update(display_state, r ? '!' : '*', what,
1012 r ? _("unable to update local ref") : NULL,
1013 remote, ref->name, summary_width);
1014 return r;
1017 if (fetch_show_forced_updates) {
1018 uint64_t t_before = getnanotime();
1019 fast_forward = repo_in_merge_bases(the_repository, current,
1020 updated);
1021 forced_updates_ms += (getnanotime() - t_before) / 1000000;
1022 } else {
1023 fast_forward = 1;
1026 if (fast_forward) {
1027 struct strbuf quickref = STRBUF_INIT;
1028 int r;
1030 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1031 strbuf_addstr(&quickref, "..");
1032 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1033 r = s_update_ref("fast-forward", ref, transaction, 1);
1034 display_ref_update(display_state, r ? '!' : ' ', quickref.buf,
1035 r ? _("unable to update local ref") : NULL,
1036 remote, ref->name, summary_width);
1037 strbuf_release(&quickref);
1038 return r;
1039 } else if (force || ref->force) {
1040 struct strbuf quickref = STRBUF_INIT;
1041 int r;
1042 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1043 strbuf_addstr(&quickref, "...");
1044 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1045 r = s_update_ref("forced-update", ref, transaction, 1);
1046 display_ref_update(display_state, r ? '!' : '+', quickref.buf,
1047 r ? _("unable to update local ref") : _("forced update"),
1048 remote, ref->name, summary_width);
1049 strbuf_release(&quickref);
1050 return r;
1051 } else {
1052 display_ref_update(display_state, '!', _("[rejected]"), _("non-fast-forward"),
1053 remote, ref->name, summary_width);
1054 return 1;
1058 static const struct object_id *iterate_ref_map(void *cb_data)
1060 struct ref **rm = cb_data;
1061 struct ref *ref = *rm;
1063 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1064 ref = ref->next;
1065 if (!ref)
1066 return NULL;
1067 *rm = ref->next;
1068 return &ref->old_oid;
1071 struct fetch_head {
1072 FILE *fp;
1073 struct strbuf buf;
1076 static int open_fetch_head(struct fetch_head *fetch_head)
1078 const char *filename = git_path_fetch_head(the_repository);
1080 if (write_fetch_head) {
1081 fetch_head->fp = fopen(filename, "a");
1082 if (!fetch_head->fp)
1083 return error_errno(_("cannot open '%s'"), filename);
1084 strbuf_init(&fetch_head->buf, 0);
1085 } else {
1086 fetch_head->fp = NULL;
1089 return 0;
1092 static void append_fetch_head(struct fetch_head *fetch_head,
1093 const struct object_id *old_oid,
1094 enum fetch_head_status fetch_head_status,
1095 const char *note,
1096 const char *url, size_t url_len)
1098 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1099 const char *merge_status_marker;
1100 size_t i;
1102 if (!fetch_head->fp)
1103 return;
1105 switch (fetch_head_status) {
1106 case FETCH_HEAD_NOT_FOR_MERGE:
1107 merge_status_marker = "not-for-merge";
1108 break;
1109 case FETCH_HEAD_MERGE:
1110 merge_status_marker = "";
1111 break;
1112 default:
1113 /* do not write anything to FETCH_HEAD */
1114 return;
1117 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1118 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1119 for (i = 0; i < url_len; ++i)
1120 if ('\n' == url[i])
1121 strbuf_addstr(&fetch_head->buf, "\\n");
1122 else
1123 strbuf_addch(&fetch_head->buf, url[i]);
1124 strbuf_addch(&fetch_head->buf, '\n');
1127 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1128 * any of the reference updates fails. We thus have to write all
1129 * updates to a buffer first and only commit it as soon as all
1130 * references have been successfully updated.
1132 if (!atomic_fetch) {
1133 strbuf_write(&fetch_head->buf, fetch_head->fp);
1134 strbuf_reset(&fetch_head->buf);
1138 static void commit_fetch_head(struct fetch_head *fetch_head)
1140 if (!fetch_head->fp || !atomic_fetch)
1141 return;
1142 strbuf_write(&fetch_head->buf, fetch_head->fp);
1145 static void close_fetch_head(struct fetch_head *fetch_head)
1147 if (!fetch_head->fp)
1148 return;
1150 fclose(fetch_head->fp);
1151 strbuf_release(&fetch_head->buf);
1154 static const char warn_show_forced_updates[] =
1155 N_("fetch normally indicates which branches had a forced update,\n"
1156 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1157 "flag or run 'git config fetch.showForcedUpdates true'");
1158 static const char warn_time_show_forced_updates[] =
1159 N_("it took %.2f seconds to check forced updates; you can use\n"
1160 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1161 "to avoid this check\n");
1163 static int store_updated_refs(struct display_state *display_state,
1164 const char *remote_name,
1165 int connectivity_checked,
1166 struct ref_transaction *transaction, struct ref *ref_map,
1167 struct fetch_head *fetch_head)
1169 int rc = 0;
1170 struct strbuf note = STRBUF_INIT;
1171 const char *what, *kind;
1172 struct ref *rm;
1173 int want_status;
1174 int summary_width = 0;
1176 if (verbosity >= 0)
1177 summary_width = transport_summary_width(ref_map);
1179 if (!connectivity_checked) {
1180 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1182 opt.exclude_hidden_refs_section = "fetch";
1183 rm = ref_map;
1184 if (check_connected(iterate_ref_map, &rm, &opt)) {
1185 rc = error(_("%s did not send all necessary objects\n"),
1186 display_state->url);
1187 goto abort;
1192 * We do a pass for each fetch_head_status type in their enum order, so
1193 * merged entries are written before not-for-merge. That lets readers
1194 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1196 for (want_status = FETCH_HEAD_MERGE;
1197 want_status <= FETCH_HEAD_IGNORE;
1198 want_status++) {
1199 for (rm = ref_map; rm; rm = rm->next) {
1200 struct ref *ref = NULL;
1202 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1203 if (want_status == FETCH_HEAD_MERGE)
1204 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1205 rm->peer_ref ? rm->peer_ref->name : rm->name);
1206 continue;
1210 * When writing FETCH_HEAD we need to determine whether
1211 * we already have the commit or not. If not, then the
1212 * reference is not for merge and needs to be written
1213 * to the reflog after other commits which we already
1214 * have. We're not interested in this property though
1215 * in case FETCH_HEAD is not to be updated, so we can
1216 * skip the classification in that case.
1218 if (fetch_head->fp) {
1219 struct commit *commit = NULL;
1222 * References in "refs/tags/" are often going to point
1223 * to annotated tags, which are not part of the
1224 * commit-graph. We thus only try to look up refs in
1225 * the graph which are not in that namespace to not
1226 * regress performance in repositories with many
1227 * annotated tags.
1229 if (!starts_with(rm->name, "refs/tags/"))
1230 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1231 if (!commit) {
1232 commit = lookup_commit_reference_gently(the_repository,
1233 &rm->old_oid,
1235 if (!commit)
1236 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1240 if (rm->fetch_head_status != want_status)
1241 continue;
1243 if (rm->peer_ref) {
1244 ref = alloc_ref(rm->peer_ref->name);
1245 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1246 oidcpy(&ref->new_oid, &rm->old_oid);
1247 ref->force = rm->peer_ref->force;
1250 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1251 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1252 check_for_new_submodule_commits(&rm->old_oid);
1255 if (!strcmp(rm->name, "HEAD")) {
1256 kind = "";
1257 what = "";
1259 else if (skip_prefix(rm->name, "refs/heads/", &what))
1260 kind = "branch";
1261 else if (skip_prefix(rm->name, "refs/tags/", &what))
1262 kind = "tag";
1263 else if (skip_prefix(rm->name, "refs/remotes/", &what))
1264 kind = "remote-tracking branch";
1265 else {
1266 kind = "";
1267 what = rm->name;
1270 strbuf_reset(&note);
1271 if (*what) {
1272 if (*kind)
1273 strbuf_addf(&note, "%s ", kind);
1274 strbuf_addf(&note, "'%s' of ", what);
1277 append_fetch_head(fetch_head, &rm->old_oid,
1278 rm->fetch_head_status,
1279 note.buf, display_state->url,
1280 display_state->url_len);
1282 if (ref) {
1283 rc |= update_local_ref(ref, transaction, display_state, what,
1284 rm, summary_width);
1285 free(ref);
1286 } else if (write_fetch_head || dry_run) {
1288 * Display fetches written to FETCH_HEAD (or
1289 * would be written to FETCH_HEAD, if --dry-run
1290 * is set).
1292 display_ref_update(display_state, '*',
1293 *kind ? kind : "branch", NULL,
1294 *what ? what : "HEAD",
1295 "FETCH_HEAD", summary_width);
1300 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1301 error(_("some local refs could not be updated; try running\n"
1302 " 'git remote prune %s' to remove any old, conflicting "
1303 "branches"), remote_name);
1305 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1306 if (!fetch_show_forced_updates) {
1307 warning(_(warn_show_forced_updates));
1308 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1309 warning(_(warn_time_show_forced_updates),
1310 forced_updates_ms / 1000.0);
1314 abort:
1315 strbuf_release(&note);
1316 return rc;
1320 * We would want to bypass the object transfer altogether if
1321 * everything we are going to fetch already exists and is connected
1322 * locally.
1324 static int check_exist_and_connected(struct ref *ref_map)
1326 struct ref *rm = ref_map;
1327 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1328 struct ref *r;
1331 * If we are deepening a shallow clone we already have these
1332 * objects reachable. Running rev-list here will return with
1333 * a good (0) exit status and we'll bypass the fetch that we
1334 * really need to perform. Claiming failure now will ensure
1335 * we perform the network exchange to deepen our history.
1337 if (deepen)
1338 return -1;
1341 * Similarly, if we need to refetch, we always want to perform a full
1342 * fetch ignoring existing objects.
1344 if (refetch)
1345 return -1;
1349 * check_connected() allows objects to merely be promised, but
1350 * we need all direct targets to exist.
1352 for (r = rm; r; r = r->next) {
1353 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1354 OBJECT_INFO_SKIP_FETCH_OBJECT))
1355 return -1;
1358 opt.quiet = 1;
1359 opt.exclude_hidden_refs_section = "fetch";
1360 return check_connected(iterate_ref_map, &rm, &opt);
1363 static int fetch_and_consume_refs(struct display_state *display_state,
1364 struct transport *transport,
1365 struct ref_transaction *transaction,
1366 struct ref *ref_map,
1367 struct fetch_head *fetch_head)
1369 int connectivity_checked = 1;
1370 int ret;
1373 * We don't need to perform a fetch in case we can already satisfy all
1374 * refs.
1376 ret = check_exist_and_connected(ref_map);
1377 if (ret) {
1378 trace2_region_enter("fetch", "fetch_refs", the_repository);
1379 ret = transport_fetch_refs(transport, ref_map);
1380 trace2_region_leave("fetch", "fetch_refs", the_repository);
1381 if (ret)
1382 goto out;
1383 connectivity_checked = transport->smart_options ?
1384 transport->smart_options->connectivity_checked : 0;
1387 trace2_region_enter("fetch", "consume_refs", the_repository);
1388 ret = store_updated_refs(display_state, transport->remote->name,
1389 connectivity_checked, transaction, ref_map,
1390 fetch_head);
1391 trace2_region_leave("fetch", "consume_refs", the_repository);
1393 out:
1394 transport_unlock_pack(transport, 0);
1395 return ret;
1398 static int prune_refs(struct display_state *display_state,
1399 struct refspec *rs,
1400 struct ref_transaction *transaction,
1401 struct ref *ref_map)
1403 int result = 0;
1404 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1405 struct strbuf err = STRBUF_INIT;
1406 const char *dangling_msg = dry_run
1407 ? _(" (%s will become dangling)")
1408 : _(" (%s has become dangling)");
1410 if (!dry_run) {
1411 if (transaction) {
1412 for (ref = stale_refs; ref; ref = ref->next) {
1413 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1414 "fetch: prune", &err);
1415 if (result)
1416 goto cleanup;
1418 } else {
1419 struct string_list refnames = STRING_LIST_INIT_NODUP;
1421 for (ref = stale_refs; ref; ref = ref->next)
1422 string_list_append(&refnames, ref->name);
1424 result = delete_refs("fetch: prune", &refnames, 0);
1425 string_list_clear(&refnames, 0);
1429 if (verbosity >= 0) {
1430 int summary_width = transport_summary_width(stale_refs);
1432 for (ref = stale_refs; ref; ref = ref->next) {
1433 display_ref_update(display_state, '-', _("[deleted]"), NULL,
1434 _("(none)"), ref->name,
1435 summary_width);
1436 warn_dangling_symref(stderr, dangling_msg, ref->name);
1440 cleanup:
1441 strbuf_release(&err);
1442 free_refs(stale_refs);
1443 return result;
1446 static void check_not_current_branch(struct ref *ref_map)
1448 const char *path;
1449 for (; ref_map; ref_map = ref_map->next)
1450 if (ref_map->peer_ref &&
1451 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1452 (path = branch_checked_out(ref_map->peer_ref->name)))
1453 die(_("refusing to fetch into branch '%s' "
1454 "checked out at '%s'"),
1455 ref_map->peer_ref->name, path);
1458 static int truncate_fetch_head(void)
1460 const char *filename = git_path_fetch_head(the_repository);
1461 FILE *fp = fopen_for_writing(filename);
1463 if (!fp)
1464 return error_errno(_("cannot open '%s'"), filename);
1465 fclose(fp);
1466 return 0;
1469 static void set_option(struct transport *transport, const char *name, const char *value)
1471 int r = transport_set_option(transport, name, value);
1472 if (r < 0)
1473 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1474 name, value, transport->url);
1475 if (r > 0)
1476 warning(_("option \"%s\" is ignored for %s\n"),
1477 name, transport->url);
1481 static int add_oid(const char *refname UNUSED,
1482 const struct object_id *oid,
1483 int flags UNUSED, void *cb_data)
1485 struct oid_array *oids = cb_data;
1487 oid_array_append(oids, oid);
1488 return 0;
1491 static void add_negotiation_tips(struct git_transport_options *smart_options)
1493 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1494 int i;
1496 for (i = 0; i < negotiation_tip.nr; i++) {
1497 const char *s = negotiation_tip.items[i].string;
1498 int old_nr;
1499 if (!has_glob_specials(s)) {
1500 struct object_id oid;
1501 if (repo_get_oid(the_repository, s, &oid))
1502 die(_("%s is not a valid object"), s);
1503 if (!has_object(the_repository, &oid, 0))
1504 die(_("the object %s does not exist"), s);
1505 oid_array_append(oids, &oid);
1506 continue;
1508 old_nr = oids->nr;
1509 for_each_glob_ref(add_oid, s, oids);
1510 if (old_nr == oids->nr)
1511 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1514 smart_options->negotiation_tips = oids;
1517 static struct transport *prepare_transport(struct remote *remote, int deepen)
1519 struct transport *transport;
1521 transport = transport_get(remote, NULL);
1522 transport_set_verbosity(transport, verbosity, progress);
1523 transport->family = family;
1524 if (upload_pack)
1525 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1526 if (keep)
1527 set_option(transport, TRANS_OPT_KEEP, "yes");
1528 if (depth)
1529 set_option(transport, TRANS_OPT_DEPTH, depth);
1530 if (deepen && deepen_since)
1531 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1532 if (deepen && deepen_not.nr)
1533 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1534 (const char *)&deepen_not);
1535 if (deepen_relative)
1536 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1537 if (update_shallow)
1538 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1539 if (refetch)
1540 set_option(transport, TRANS_OPT_REFETCH, "yes");
1541 if (filter_options.choice) {
1542 const char *spec =
1543 expand_list_objects_filter_spec(&filter_options);
1544 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1545 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1547 if (negotiation_tip.nr) {
1548 if (transport->smart_options)
1549 add_negotiation_tips(transport->smart_options);
1550 else
1551 warning("ignoring --negotiation-tip because the protocol does not support it");
1553 return transport;
1556 static int backfill_tags(struct display_state *display_state,
1557 struct transport *transport,
1558 struct ref_transaction *transaction,
1559 struct ref *ref_map,
1560 struct fetch_head *fetch_head)
1562 int retcode, cannot_reuse;
1565 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1566 * when remote helper is used (setting it to an empty string
1567 * is not unsetting). We could extend the remote helper
1568 * protocol for that, but for now, just force a new connection
1569 * without deepen-since. Similar story for deepen-not.
1571 cannot_reuse = transport->cannot_reuse ||
1572 deepen_since || deepen_not.nr;
1573 if (cannot_reuse) {
1574 gsecondary = prepare_transport(transport->remote, 0);
1575 transport = gsecondary;
1578 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1579 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1580 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1581 retcode = fetch_and_consume_refs(display_state, transport, transaction, ref_map, fetch_head);
1583 if (gsecondary) {
1584 transport_disconnect(gsecondary);
1585 gsecondary = NULL;
1588 return retcode;
1591 static int do_fetch(struct transport *transport,
1592 struct refspec *rs)
1594 struct ref_transaction *transaction = NULL;
1595 struct ref *ref_map = NULL;
1596 struct display_state display_state = { 0 };
1597 int autotags = (transport->remote->fetch_tags == 1);
1598 int retcode = 0;
1599 const struct ref *remote_refs;
1600 struct transport_ls_refs_options transport_ls_refs_options =
1601 TRANSPORT_LS_REFS_OPTIONS_INIT;
1602 int must_list_refs = 1;
1603 struct fetch_head fetch_head = { 0 };
1604 struct strbuf err = STRBUF_INIT;
1606 if (tags == TAGS_DEFAULT) {
1607 if (transport->remote->fetch_tags == 2)
1608 tags = TAGS_SET;
1609 if (transport->remote->fetch_tags == -1)
1610 tags = TAGS_UNSET;
1613 /* if not appending, truncate FETCH_HEAD */
1614 if (!append && write_fetch_head) {
1615 retcode = truncate_fetch_head();
1616 if (retcode)
1617 goto cleanup;
1620 if (rs->nr) {
1621 int i;
1623 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1626 * We can avoid listing refs if all of them are exact
1627 * OIDs
1629 must_list_refs = 0;
1630 for (i = 0; i < rs->nr; i++) {
1631 if (!rs->items[i].exact_sha1) {
1632 must_list_refs = 1;
1633 break;
1636 } else {
1637 struct branch *branch = branch_get(NULL);
1639 if (transport->remote->fetch.nr)
1640 refspec_ref_prefixes(&transport->remote->fetch,
1641 &transport_ls_refs_options.ref_prefixes);
1642 if (branch_has_merge_config(branch) &&
1643 !strcmp(branch->remote_name, transport->remote->name)) {
1644 int i;
1645 for (i = 0; i < branch->merge_nr; i++) {
1646 strvec_push(&transport_ls_refs_options.ref_prefixes,
1647 branch->merge[i]->src);
1652 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1653 must_list_refs = 1;
1654 if (transport_ls_refs_options.ref_prefixes.nr)
1655 strvec_push(&transport_ls_refs_options.ref_prefixes,
1656 "refs/tags/");
1659 if (must_list_refs) {
1660 trace2_region_enter("fetch", "remote_refs", the_repository);
1661 remote_refs = transport_get_remote_refs(transport,
1662 &transport_ls_refs_options);
1663 trace2_region_leave("fetch", "remote_refs", the_repository);
1664 } else
1665 remote_refs = NULL;
1667 transport_ls_refs_options_release(&transport_ls_refs_options);
1669 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1670 tags, &autotags);
1671 if (!update_head_ok)
1672 check_not_current_branch(ref_map);
1674 retcode = open_fetch_head(&fetch_head);
1675 if (retcode)
1676 goto cleanup;
1678 display_state_init(&display_state, ref_map, transport->url);
1680 if (atomic_fetch) {
1681 transaction = ref_transaction_begin(&err);
1682 if (!transaction) {
1683 retcode = error("%s", err.buf);
1684 goto cleanup;
1688 if (tags == TAGS_DEFAULT && autotags)
1689 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1690 if (prune) {
1692 * We only prune based on refspecs specified
1693 * explicitly (via command line or configuration); we
1694 * don't care whether --tags was specified.
1696 if (rs->nr) {
1697 retcode = prune_refs(&display_state, rs, transaction, ref_map);
1698 } else {
1699 retcode = prune_refs(&display_state, &transport->remote->fetch,
1700 transaction, ref_map);
1702 if (retcode != 0)
1703 retcode = 1;
1706 if (fetch_and_consume_refs(&display_state, transport, transaction, ref_map, &fetch_head)) {
1707 retcode = 1;
1708 goto cleanup;
1712 * If neither --no-tags nor --tags was specified, do automated tag
1713 * following.
1715 if (tags == TAGS_DEFAULT && autotags) {
1716 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1718 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1719 if (tags_ref_map) {
1721 * If backfilling of tags fails then we want to tell
1722 * the user so, but we have to continue regardless to
1723 * populate upstream information of the references we
1724 * have already fetched above. The exception though is
1725 * when `--atomic` is passed: in that case we'll abort
1726 * the transaction and don't commit anything.
1728 if (backfill_tags(&display_state, transport, transaction, tags_ref_map,
1729 &fetch_head))
1730 retcode = 1;
1733 free_refs(tags_ref_map);
1736 if (transaction) {
1737 if (retcode)
1738 goto cleanup;
1740 retcode = ref_transaction_commit(transaction, &err);
1741 if (retcode) {
1742 error("%s", err.buf);
1743 ref_transaction_free(transaction);
1744 transaction = NULL;
1745 goto cleanup;
1749 commit_fetch_head(&fetch_head);
1751 if (set_upstream) {
1752 struct branch *branch = branch_get("HEAD");
1753 struct ref *rm;
1754 struct ref *source_ref = NULL;
1757 * We're setting the upstream configuration for the
1758 * current branch. The relevant upstream is the
1759 * fetched branch that is meant to be merged with the
1760 * current one, i.e. the one fetched to FETCH_HEAD.
1762 * When there are several such branches, consider the
1763 * request ambiguous and err on the safe side by doing
1764 * nothing and just emit a warning.
1766 for (rm = ref_map; rm; rm = rm->next) {
1767 if (!rm->peer_ref) {
1768 if (source_ref) {
1769 warning(_("multiple branches detected, incompatible with --set-upstream"));
1770 goto cleanup;
1771 } else {
1772 source_ref = rm;
1776 if (source_ref) {
1777 if (!branch) {
1778 const char *shortname = source_ref->name;
1779 skip_prefix(shortname, "refs/heads/", &shortname);
1781 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1782 "it does not point to any branch."),
1783 shortname, transport->remote->name);
1784 goto cleanup;
1787 if (!strcmp(source_ref->name, "HEAD") ||
1788 starts_with(source_ref->name, "refs/heads/"))
1789 install_branch_config(0,
1790 branch->name,
1791 transport->remote->name,
1792 source_ref->name);
1793 else if (starts_with(source_ref->name, "refs/remotes/"))
1794 warning(_("not setting upstream for a remote remote-tracking branch"));
1795 else if (starts_with(source_ref->name, "refs/tags/"))
1796 warning(_("not setting upstream for a remote tag"));
1797 else
1798 warning(_("unknown branch type"));
1799 } else {
1800 warning(_("no source branch found;\n"
1801 "you need to specify exactly one branch with the --set-upstream option"));
1805 cleanup:
1806 if (retcode && transaction) {
1807 ref_transaction_abort(transaction, &err);
1808 error("%s", err.buf);
1811 display_state_release(&display_state);
1812 close_fetch_head(&fetch_head);
1813 strbuf_release(&err);
1814 free_refs(ref_map);
1815 return retcode;
1818 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1820 struct string_list *list = priv;
1821 if (!remote->skip_default_update)
1822 string_list_append(list, remote->name);
1823 return 0;
1826 struct remote_group_data {
1827 const char *name;
1828 struct string_list *list;
1831 static int get_remote_group(const char *key, const char *value, void *priv)
1833 struct remote_group_data *g = priv;
1835 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1836 /* split list by white space */
1837 while (*value) {
1838 size_t wordlen = strcspn(value, " \t\n");
1840 if (wordlen >= 1)
1841 string_list_append_nodup(g->list,
1842 xstrndup(value, wordlen));
1843 value += wordlen + (value[wordlen] != '\0');
1847 return 0;
1850 static int add_remote_or_group(const char *name, struct string_list *list)
1852 int prev_nr = list->nr;
1853 struct remote_group_data g;
1854 g.name = name; g.list = list;
1856 git_config(get_remote_group, &g);
1857 if (list->nr == prev_nr) {
1858 struct remote *remote = remote_get(name);
1859 if (!remote_is_configured(remote, 0))
1860 return 0;
1861 string_list_append(list, remote->name);
1863 return 1;
1866 static void add_options_to_argv(struct strvec *argv)
1868 if (dry_run)
1869 strvec_push(argv, "--dry-run");
1870 if (prune != -1)
1871 strvec_push(argv, prune ? "--prune" : "--no-prune");
1872 if (prune_tags != -1)
1873 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1874 if (update_head_ok)
1875 strvec_push(argv, "--update-head-ok");
1876 if (force)
1877 strvec_push(argv, "--force");
1878 if (keep)
1879 strvec_push(argv, "--keep");
1880 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1881 strvec_push(argv, "--recurse-submodules");
1882 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1883 strvec_push(argv, "--recurse-submodules=on-demand");
1884 if (tags == TAGS_SET)
1885 strvec_push(argv, "--tags");
1886 else if (tags == TAGS_UNSET)
1887 strvec_push(argv, "--no-tags");
1888 if (verbosity >= 2)
1889 strvec_push(argv, "-v");
1890 if (verbosity >= 1)
1891 strvec_push(argv, "-v");
1892 else if (verbosity < 0)
1893 strvec_push(argv, "-q");
1894 if (family == TRANSPORT_FAMILY_IPV4)
1895 strvec_push(argv, "--ipv4");
1896 else if (family == TRANSPORT_FAMILY_IPV6)
1897 strvec_push(argv, "--ipv6");
1898 if (!write_fetch_head)
1899 strvec_push(argv, "--no-write-fetch-head");
1902 /* Fetch multiple remotes in parallel */
1904 struct parallel_fetch_state {
1905 const char **argv;
1906 struct string_list *remotes;
1907 int next, result;
1910 static int fetch_next_remote(struct child_process *cp,
1911 struct strbuf *out UNUSED,
1912 void *cb, void **task_cb)
1914 struct parallel_fetch_state *state = cb;
1915 char *remote;
1917 if (state->next < 0 || state->next >= state->remotes->nr)
1918 return 0;
1920 remote = state->remotes->items[state->next++].string;
1921 *task_cb = remote;
1923 strvec_pushv(&cp->args, state->argv);
1924 strvec_push(&cp->args, remote);
1925 cp->git_cmd = 1;
1927 if (verbosity >= 0)
1928 printf(_("Fetching %s\n"), remote);
1930 return 1;
1933 static int fetch_failed_to_start(struct strbuf *out UNUSED,
1934 void *cb, void *task_cb)
1936 struct parallel_fetch_state *state = cb;
1937 const char *remote = task_cb;
1939 state->result = error(_("could not fetch %s"), remote);
1941 return 0;
1944 static int fetch_finished(int result, struct strbuf *out,
1945 void *cb, void *task_cb)
1947 struct parallel_fetch_state *state = cb;
1948 const char *remote = task_cb;
1950 if (result) {
1951 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1952 remote, result);
1953 state->result = -1;
1956 return 0;
1959 static int fetch_multiple(struct string_list *list, int max_children)
1961 int i, result = 0;
1962 struct strvec argv = STRVEC_INIT;
1964 if (!append && write_fetch_head) {
1965 int errcode = truncate_fetch_head();
1966 if (errcode)
1967 return errcode;
1971 * Cancel out the fetch.bundleURI config when running subprocesses,
1972 * to avoid fetching from the same bundle list multiple times.
1974 strvec_pushl(&argv, "-c", "fetch.bundleURI=",
1975 "fetch", "--append", "--no-auto-gc",
1976 "--no-write-commit-graph", NULL);
1977 add_options_to_argv(&argv);
1979 if (max_children != 1 && list->nr != 1) {
1980 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1981 const struct run_process_parallel_opts opts = {
1982 .tr2_category = "fetch",
1983 .tr2_label = "parallel/fetch",
1985 .processes = max_children,
1987 .get_next_task = &fetch_next_remote,
1988 .start_failure = &fetch_failed_to_start,
1989 .task_finished = &fetch_finished,
1990 .data = &state,
1993 strvec_push(&argv, "--end-of-options");
1995 run_processes_parallel(&opts);
1996 result = state.result;
1997 } else
1998 for (i = 0; i < list->nr; i++) {
1999 const char *name = list->items[i].string;
2000 struct child_process cmd = CHILD_PROCESS_INIT;
2002 strvec_pushv(&cmd.args, argv.v);
2003 strvec_push(&cmd.args, name);
2004 if (verbosity >= 0)
2005 printf(_("Fetching %s\n"), name);
2006 cmd.git_cmd = 1;
2007 if (run_command(&cmd)) {
2008 error(_("could not fetch %s"), name);
2009 result = 1;
2013 strvec_clear(&argv);
2014 return !!result;
2018 * Fetching from the promisor remote should use the given filter-spec
2019 * or inherit the default filter-spec from the config.
2021 static inline void fetch_one_setup_partial(struct remote *remote)
2024 * Explicit --no-filter argument overrides everything, regardless
2025 * of any prior partial clones and fetches.
2027 if (filter_options.no_filter)
2028 return;
2031 * If no prior partial clone/fetch and the current fetch DID NOT
2032 * request a partial-fetch, do a normal fetch.
2034 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
2035 return;
2038 * If this is a partial-fetch request, we enable partial on
2039 * this repo if not already enabled and remember the given
2040 * filter-spec as the default for subsequent fetches to this
2041 * remote if there is currently no default filter-spec.
2043 if (filter_options.choice) {
2044 partial_clone_register(remote->name, &filter_options);
2045 return;
2049 * Do a partial-fetch from the promisor remote using either the
2050 * explicitly given filter-spec or inherit the filter-spec from
2051 * the config.
2053 if (!filter_options.choice)
2054 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2055 return;
2058 static int fetch_one(struct remote *remote, int argc, const char **argv,
2059 int prune_tags_ok, int use_stdin_refspecs)
2061 struct refspec rs = REFSPEC_INIT_FETCH;
2062 int i;
2063 int exit_code;
2064 int maybe_prune_tags;
2065 int remote_via_config = remote_is_configured(remote, 0);
2067 if (!remote)
2068 die(_("no remote repository specified; please specify either a URL or a\n"
2069 "remote name from which new revisions should be fetched"));
2071 gtransport = prepare_transport(remote, 1);
2073 if (prune < 0) {
2074 /* no command line request */
2075 if (0 <= remote->prune)
2076 prune = remote->prune;
2077 else if (0 <= fetch_prune_config)
2078 prune = fetch_prune_config;
2079 else
2080 prune = PRUNE_BY_DEFAULT;
2083 if (prune_tags < 0) {
2084 /* no command line request */
2085 if (0 <= remote->prune_tags)
2086 prune_tags = remote->prune_tags;
2087 else if (0 <= fetch_prune_tags_config)
2088 prune_tags = fetch_prune_tags_config;
2089 else
2090 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2093 maybe_prune_tags = prune_tags_ok && prune_tags;
2094 if (maybe_prune_tags && remote_via_config)
2095 refspec_append(&remote->fetch, TAG_REFSPEC);
2097 if (maybe_prune_tags && (argc || !remote_via_config))
2098 refspec_append(&rs, TAG_REFSPEC);
2100 for (i = 0; i < argc; i++) {
2101 if (!strcmp(argv[i], "tag")) {
2102 i++;
2103 if (i >= argc)
2104 die(_("you need to specify a tag name"));
2106 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2107 argv[i], argv[i]);
2108 } else {
2109 refspec_append(&rs, argv[i]);
2113 if (use_stdin_refspecs) {
2114 struct strbuf line = STRBUF_INIT;
2115 while (strbuf_getline_lf(&line, stdin) != EOF)
2116 refspec_append(&rs, line.buf);
2117 strbuf_release(&line);
2120 if (server_options.nr)
2121 gtransport->server_options = &server_options;
2123 sigchain_push_common(unlock_pack_on_signal);
2124 atexit(unlock_pack_atexit);
2125 sigchain_push(SIGPIPE, SIG_IGN);
2126 exit_code = do_fetch(gtransport, &rs);
2127 sigchain_pop(SIGPIPE);
2128 refspec_clear(&rs);
2129 transport_disconnect(gtransport);
2130 gtransport = NULL;
2131 return exit_code;
2134 int cmd_fetch(int argc, const char **argv, const char *prefix)
2136 int i;
2137 const char *bundle_uri;
2138 struct string_list list = STRING_LIST_INIT_DUP;
2139 struct remote *remote = NULL;
2140 int result = 0;
2141 int prune_tags_ok = 1;
2143 packet_trace_identity("fetch");
2145 /* Record the command line for the reflog */
2146 strbuf_addstr(&default_rla, "fetch");
2147 for (i = 1; i < argc; i++) {
2148 /* This handles non-URLs gracefully */
2149 char *anon = transport_anonymize_url(argv[i]);
2151 strbuf_addf(&default_rla, " %s", anon);
2152 free(anon);
2155 git_config(git_fetch_config, NULL);
2156 if (the_repository->gitdir) {
2157 prepare_repo_settings(the_repository);
2158 the_repository->settings.command_requires_full_index = 0;
2161 argc = parse_options(argc, argv, prefix,
2162 builtin_fetch_options, builtin_fetch_usage, 0);
2164 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2165 recurse_submodules = recurse_submodules_cli;
2167 if (negotiate_only) {
2168 switch (recurse_submodules_cli) {
2169 case RECURSE_SUBMODULES_OFF:
2170 case RECURSE_SUBMODULES_DEFAULT:
2172 * --negotiate-only should never recurse into
2173 * submodules. Skip it by setting recurse_submodules to
2174 * RECURSE_SUBMODULES_OFF.
2176 recurse_submodules = RECURSE_SUBMODULES_OFF;
2177 break;
2179 default:
2180 die(_("options '%s' and '%s' cannot be used together"),
2181 "--negotiate-only", "--recurse-submodules");
2185 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2186 int *sfjc = submodule_fetch_jobs_config == -1
2187 ? &submodule_fetch_jobs_config : NULL;
2188 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2189 ? &recurse_submodules : NULL;
2191 fetch_config_from_gitmodules(sfjc, rs);
2194 if (negotiate_only && !negotiation_tip.nr)
2195 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2197 if (deepen_relative) {
2198 if (deepen_relative < 0)
2199 die(_("negative depth in --deepen is not supported"));
2200 if (depth)
2201 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2202 depth = xstrfmt("%d", deepen_relative);
2204 if (unshallow) {
2205 if (depth)
2206 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2207 else if (!is_repository_shallow(the_repository))
2208 die(_("--unshallow on a complete repository does not make sense"));
2209 else
2210 depth = xstrfmt("%d", INFINITE_DEPTH);
2213 /* no need to be strict, transport_set_option() will validate it again */
2214 if (depth && atoi(depth) < 1)
2215 die(_("depth %s is not a positive number"), depth);
2216 if (depth || deepen_since || deepen_not.nr)
2217 deepen = 1;
2219 /* FETCH_HEAD never gets updated in --dry-run mode */
2220 if (dry_run)
2221 write_fetch_head = 0;
2223 if (!max_jobs)
2224 max_jobs = online_cpus();
2226 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2227 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2228 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2230 if (all) {
2231 if (argc == 1)
2232 die(_("fetch --all does not take a repository argument"));
2233 else if (argc > 1)
2234 die(_("fetch --all does not make sense with refspecs"));
2235 (void) for_each_remote(get_one_remote_for_fetch, &list);
2237 /* do not do fetch_multiple() of one */
2238 if (list.nr == 1)
2239 remote = remote_get(list.items[0].string);
2240 } else if (argc == 0) {
2241 /* No arguments -- use default remote */
2242 remote = remote_get(NULL);
2243 } else if (multiple) {
2244 /* All arguments are assumed to be remotes or groups */
2245 for (i = 0; i < argc; i++)
2246 if (!add_remote_or_group(argv[i], &list))
2247 die(_("no such remote or remote group: %s"),
2248 argv[i]);
2249 } else {
2250 /* Single remote or group */
2251 (void) add_remote_or_group(argv[0], &list);
2252 if (list.nr > 1) {
2253 /* More than one remote */
2254 if (argc > 1)
2255 die(_("fetching a group and specifying refspecs does not make sense"));
2256 } else {
2257 /* Zero or one remotes */
2258 remote = remote_get(argv[0]);
2259 prune_tags_ok = (argc == 1);
2260 argc--;
2261 argv++;
2264 string_list_remove_duplicates(&list, 0);
2266 if (negotiate_only) {
2267 struct oidset acked_commits = OIDSET_INIT;
2268 struct oidset_iter iter;
2269 const struct object_id *oid;
2271 if (!remote)
2272 die(_("must supply remote when using --negotiate-only"));
2273 gtransport = prepare_transport(remote, 1);
2274 if (gtransport->smart_options) {
2275 gtransport->smart_options->acked_commits = &acked_commits;
2276 } else {
2277 warning(_("protocol does not support --negotiate-only, exiting"));
2278 result = 1;
2279 goto cleanup;
2281 if (server_options.nr)
2282 gtransport->server_options = &server_options;
2283 result = transport_fetch_refs(gtransport, NULL);
2285 oidset_iter_init(&acked_commits, &iter);
2286 while ((oid = oidset_iter_next(&iter)))
2287 printf("%s\n", oid_to_hex(oid));
2288 oidset_clear(&acked_commits);
2289 } else if (remote) {
2290 if (filter_options.choice || repo_has_promisor_remote(the_repository))
2291 fetch_one_setup_partial(remote);
2292 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
2293 } else {
2294 int max_children = max_jobs;
2296 if (filter_options.choice)
2297 die(_("--filter can only be used with the remote "
2298 "configured in extensions.partialclone"));
2300 if (atomic_fetch)
2301 die(_("--atomic can only be used when fetching "
2302 "from one remote"));
2304 if (stdin_refspecs)
2305 die(_("--stdin can only be used when fetching "
2306 "from one remote"));
2308 if (max_children < 0)
2309 max_children = fetch_parallel_config;
2311 /* TODO should this also die if we have a previous partial-clone? */
2312 result = fetch_multiple(&list, max_children);
2317 * This is only needed after fetch_one(), which does not fetch
2318 * submodules by itself.
2320 * When we fetch from multiple remotes, fetch_multiple() has
2321 * already updated submodules to grab commits necessary for
2322 * the fetched history from each remote, so there is no need
2323 * to fetch submodules from here.
2325 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2326 struct strvec options = STRVEC_INIT;
2327 int max_children = max_jobs;
2329 if (max_children < 0)
2330 max_children = submodule_fetch_jobs_config;
2331 if (max_children < 0)
2332 max_children = fetch_parallel_config;
2334 add_options_to_argv(&options);
2335 result = fetch_submodules(the_repository,
2336 &options,
2337 submodule_prefix,
2338 recurse_submodules,
2339 recurse_submodules_default,
2340 verbosity < 0,
2341 max_children);
2342 strvec_clear(&options);
2346 * Skip irrelevant tasks because we know objects were not
2347 * fetched.
2349 * NEEDSWORK: as a future optimization, we can return early
2350 * whenever objects were not fetched e.g. if we already have all
2351 * of them.
2353 if (negotiate_only)
2354 goto cleanup;
2356 prepare_repo_settings(the_repository);
2357 if (fetch_write_commit_graph > 0 ||
2358 (fetch_write_commit_graph < 0 &&
2359 the_repository->settings.fetch_write_commit_graph)) {
2360 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2362 if (progress)
2363 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2365 write_commit_graph_reachable(the_repository->objects->odb,
2366 commit_graph_flags,
2367 NULL);
2370 if (enable_auto_gc) {
2371 if (refetch) {
2373 * Hint auto-maintenance strongly to encourage repacking,
2374 * but respect config settings disabling it.
2376 int opt_val;
2377 if (git_config_get_int("gc.autopacklimit", &opt_val))
2378 opt_val = -1;
2379 if (opt_val != 0)
2380 git_config_push_parameter("gc.autoPackLimit=1");
2382 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2383 opt_val = -1;
2384 if (opt_val != 0)
2385 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2387 run_auto_maintenance(verbosity < 0);
2390 cleanup:
2391 string_list_clear(&list, 0);
2392 return result;