pager.h: move declarations for pager.c functions from cache.h
[git.git] / builtin / fetch.c
blob61e8ac113b1f2f65b3d75e365f094477cd654e17
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "advice.h"
6 #include "config.h"
7 #include "gettext.h"
8 #include "environment.h"
9 #include "hex.h"
10 #include "repository.h"
11 #include "refs.h"
12 #include "refspec.h"
13 #include "object-name.h"
14 #include "object-store.h"
15 #include "oidset.h"
16 #include "oid-array.h"
17 #include "commit.h"
18 #include "builtin.h"
19 #include "string-list.h"
20 #include "remote.h"
21 #include "transport.h"
22 #include "run-command.h"
23 #include "parse-options.h"
24 #include "sigchain.h"
25 #include "submodule-config.h"
26 #include "submodule.h"
27 #include "connected.h"
28 #include "strvec.h"
29 #include "utf8.h"
30 #include "packfile.h"
31 #include "pager.h"
32 #include "list-objects-filter-options.h"
33 #include "commit-reach.h"
34 #include "branch.h"
35 #include "promisor-remote.h"
36 #include "commit-graph.h"
37 #include "shallow.h"
38 #include "trace.h"
39 #include "trace2.h"
40 #include "worktree.h"
41 #include "bundle-uri.h"
43 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
45 static const char * const builtin_fetch_usage[] = {
46 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
47 N_("git fetch [<options>] <group>"),
48 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
49 N_("git fetch --all [<options>]"),
50 NULL
53 enum {
54 TAGS_UNSET = 0,
55 TAGS_DEFAULT = 1,
56 TAGS_SET = 2
59 static int fetch_prune_config = -1; /* unspecified */
60 static int fetch_show_forced_updates = 1;
61 static uint64_t forced_updates_ms = 0;
62 static int prefetch = 0;
63 static int prune = -1; /* unspecified */
64 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
66 static int fetch_prune_tags_config = -1; /* unspecified */
67 static int prune_tags = -1; /* unspecified */
68 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
70 static int all, append, dry_run, force, keep, multiple, update_head_ok;
71 static int write_fetch_head = 1;
72 static int verbosity, deepen_relative, set_upstream, refetch;
73 static int progress = -1;
74 static int enable_auto_gc = 1;
75 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
76 static int max_jobs = -1, submodule_fetch_jobs_config = -1;
77 static int fetch_parallel_config = 1;
78 static int atomic_fetch;
79 static enum transport_family family;
80 static const char *depth;
81 static const char *deepen_since;
82 static const char *upload_pack;
83 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
84 static struct strbuf default_rla = STRBUF_INIT;
85 static struct transport *gtransport;
86 static struct transport *gsecondary;
87 static const char *submodule_prefix = "";
88 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
89 static int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
90 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
91 static int shown_url = 0;
92 static struct refspec refmap = REFSPEC_INIT_FETCH;
93 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
94 static struct string_list server_options = STRING_LIST_INIT_DUP;
95 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
96 static int fetch_write_commit_graph = -1;
97 static int stdin_refspecs = 0;
98 static int negotiate_only;
100 static int git_fetch_config(const char *k, const char *v, void *cb)
102 if (!strcmp(k, "fetch.prune")) {
103 fetch_prune_config = git_config_bool(k, v);
104 return 0;
107 if (!strcmp(k, "fetch.prunetags")) {
108 fetch_prune_tags_config = git_config_bool(k, v);
109 return 0;
112 if (!strcmp(k, "fetch.showforcedupdates")) {
113 fetch_show_forced_updates = git_config_bool(k, v);
114 return 0;
117 if (!strcmp(k, "submodule.recurse")) {
118 int r = git_config_bool(k, v) ?
119 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
120 recurse_submodules = r;
123 if (!strcmp(k, "submodule.fetchjobs")) {
124 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
125 return 0;
126 } else if (!strcmp(k, "fetch.recursesubmodules")) {
127 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
128 return 0;
131 if (!strcmp(k, "fetch.parallel")) {
132 fetch_parallel_config = git_config_int(k, v);
133 if (fetch_parallel_config < 0)
134 die(_("fetch.parallel cannot be negative"));
135 if (!fetch_parallel_config)
136 fetch_parallel_config = online_cpus();
137 return 0;
140 return git_default_config(k, v, cb);
143 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
145 BUG_ON_OPT_NEG(unset);
148 * "git fetch --refmap='' origin foo"
149 * can be used to tell the command not to store anywhere
151 refspec_append(&refmap, arg);
153 return 0;
156 static struct option builtin_fetch_options[] = {
157 OPT__VERBOSITY(&verbosity),
158 OPT_BOOL(0, "all", &all,
159 N_("fetch from all remotes")),
160 OPT_BOOL(0, "set-upstream", &set_upstream,
161 N_("set upstream for git pull/fetch")),
162 OPT_BOOL('a', "append", &append,
163 N_("append to .git/FETCH_HEAD instead of overwriting")),
164 OPT_BOOL(0, "atomic", &atomic_fetch,
165 N_("use atomic transaction to update references")),
166 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
167 N_("path to upload pack on remote end")),
168 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
169 OPT_BOOL('m', "multiple", &multiple,
170 N_("fetch from multiple remotes")),
171 OPT_SET_INT('t', "tags", &tags,
172 N_("fetch all tags and associated objects"), TAGS_SET),
173 OPT_SET_INT('n', NULL, &tags,
174 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
175 OPT_INTEGER('j', "jobs", &max_jobs,
176 N_("number of submodules fetched in parallel")),
177 OPT_BOOL(0, "prefetch", &prefetch,
178 N_("modify the refspec to place all refs within refs/prefetch/")),
179 OPT_BOOL('p', "prune", &prune,
180 N_("prune remote-tracking branches no longer on remote")),
181 OPT_BOOL('P', "prune-tags", &prune_tags,
182 N_("prune local tags no longer on remote and clobber changed tags")),
183 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
184 N_("control recursive fetching of submodules"),
185 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
186 OPT_BOOL(0, "dry-run", &dry_run,
187 N_("dry run")),
188 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
189 N_("write fetched references to the FETCH_HEAD file")),
190 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
191 OPT_BOOL('u', "update-head-ok", &update_head_ok,
192 N_("allow updating of HEAD ref")),
193 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
194 OPT_STRING(0, "depth", &depth, N_("depth"),
195 N_("deepen history of shallow clone")),
196 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
197 N_("deepen history of shallow repository based on time")),
198 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
199 N_("deepen history of shallow clone, excluding rev")),
200 OPT_INTEGER(0, "deepen", &deepen_relative,
201 N_("deepen history of shallow clone")),
202 OPT_SET_INT_F(0, "unshallow", &unshallow,
203 N_("convert to a complete repository"),
204 1, PARSE_OPT_NONEG),
205 OPT_SET_INT_F(0, "refetch", &refetch,
206 N_("re-fetch without negotiating common commits"),
207 1, PARSE_OPT_NONEG),
208 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
209 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
210 OPT_CALLBACK_F(0, "recurse-submodules-default",
211 &recurse_submodules_default, N_("on-demand"),
212 N_("default for recursive fetching of submodules "
213 "(lower priority than config files)"),
214 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
215 OPT_BOOL(0, "update-shallow", &update_shallow,
216 N_("accept refs that update .git/shallow")),
217 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
218 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
219 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
220 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
221 TRANSPORT_FAMILY_IPV4),
222 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
223 TRANSPORT_FAMILY_IPV6),
224 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
225 N_("report that we have only objects reachable from this object")),
226 OPT_BOOL(0, "negotiate-only", &negotiate_only,
227 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
228 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
229 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
230 N_("run 'maintenance --auto' after fetching")),
231 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
232 N_("run 'maintenance --auto' after fetching")),
233 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
234 N_("check for forced-updates on all updated branches")),
235 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
236 N_("write the commit-graph after fetching")),
237 OPT_BOOL(0, "stdin", &stdin_refspecs,
238 N_("accept refspecs from stdin")),
239 OPT_END()
242 static void unlock_pack(unsigned int flags)
244 if (gtransport)
245 transport_unlock_pack(gtransport, flags);
246 if (gsecondary)
247 transport_unlock_pack(gsecondary, flags);
250 static void unlock_pack_atexit(void)
252 unlock_pack(0);
255 static void unlock_pack_on_signal(int signo)
257 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
258 sigchain_pop(signo);
259 raise(signo);
262 static void add_merge_config(struct ref **head,
263 const struct ref *remote_refs,
264 struct branch *branch,
265 struct ref ***tail)
267 int i;
269 for (i = 0; i < branch->merge_nr; i++) {
270 struct ref *rm, **old_tail = *tail;
271 struct refspec_item refspec;
273 for (rm = *head; rm; rm = rm->next) {
274 if (branch_merge_matches(branch, i, rm->name)) {
275 rm->fetch_head_status = FETCH_HEAD_MERGE;
276 break;
279 if (rm)
280 continue;
283 * Not fetched to a remote-tracking branch? We need to fetch
284 * it anyway to allow this branch's "branch.$name.merge"
285 * to be honored by 'git pull', but we do not have to
286 * fail if branch.$name.merge is misconfigured to point
287 * at a nonexisting branch. If we were indeed called by
288 * 'git pull', it will notice the misconfiguration because
289 * there is no entry in the resulting FETCH_HEAD marked
290 * for merging.
292 memset(&refspec, 0, sizeof(refspec));
293 refspec.src = branch->merge[i]->src;
294 get_fetch_map(remote_refs, &refspec, tail, 1);
295 for (rm = *old_tail; rm; rm = rm->next)
296 rm->fetch_head_status = FETCH_HEAD_MERGE;
300 static void create_fetch_oidset(struct ref **head, struct oidset *out)
302 struct ref *rm = *head;
303 while (rm) {
304 oidset_insert(out, &rm->old_oid);
305 rm = rm->next;
309 struct refname_hash_entry {
310 struct hashmap_entry ent;
311 struct object_id oid;
312 int ignore;
313 char refname[FLEX_ARRAY];
316 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
317 const struct hashmap_entry *eptr,
318 const struct hashmap_entry *entry_or_key,
319 const void *keydata)
321 const struct refname_hash_entry *e1, *e2;
323 e1 = container_of(eptr, const struct refname_hash_entry, ent);
324 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
325 return strcmp(e1->refname, keydata ? keydata : e2->refname);
328 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
329 const char *refname,
330 const struct object_id *oid)
332 struct refname_hash_entry *ent;
333 size_t len = strlen(refname);
335 FLEX_ALLOC_MEM(ent, refname, refname, len);
336 hashmap_entry_init(&ent->ent, strhash(refname));
337 oidcpy(&ent->oid, oid);
338 hashmap_add(map, &ent->ent);
339 return ent;
342 static int add_one_refname(const char *refname,
343 const struct object_id *oid,
344 int flag UNUSED, void *cbdata)
346 struct hashmap *refname_map = cbdata;
348 (void) refname_hash_add(refname_map, refname, oid);
349 return 0;
352 static void refname_hash_init(struct hashmap *map)
354 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
357 static int refname_hash_exists(struct hashmap *map, const char *refname)
359 return !!hashmap_get_from_hash(map, strhash(refname), refname);
362 static void clear_item(struct refname_hash_entry *item)
364 item->ignore = 1;
368 static void add_already_queued_tags(const char *refname,
369 const struct object_id *old_oid,
370 const struct object_id *new_oid,
371 void *cb_data)
373 struct hashmap *queued_tags = cb_data;
374 if (starts_with(refname, "refs/tags/") && new_oid)
375 (void) refname_hash_add(queued_tags, refname, new_oid);
378 static void find_non_local_tags(const struct ref *refs,
379 struct ref_transaction *transaction,
380 struct ref **head,
381 struct ref ***tail)
383 struct hashmap existing_refs;
384 struct hashmap remote_refs;
385 struct oidset fetch_oids = OIDSET_INIT;
386 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
387 struct string_list_item *remote_ref_item;
388 const struct ref *ref;
389 struct refname_hash_entry *item = NULL;
390 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
392 refname_hash_init(&existing_refs);
393 refname_hash_init(&remote_refs);
394 create_fetch_oidset(head, &fetch_oids);
396 for_each_ref(add_one_refname, &existing_refs);
399 * If we already have a transaction, then we need to filter out all
400 * tags which have already been queued up.
402 if (transaction)
403 ref_transaction_for_each_queued_update(transaction,
404 add_already_queued_tags,
405 &existing_refs);
407 for (ref = refs; ref; ref = ref->next) {
408 if (!starts_with(ref->name, "refs/tags/"))
409 continue;
412 * The peeled ref always follows the matching base
413 * ref, so if we see a peeled ref that we don't want
414 * to fetch then we can mark the ref entry in the list
415 * as one to ignore by setting util to NULL.
417 if (ends_with(ref->name, "^{}")) {
418 if (item &&
419 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
420 !oidset_contains(&fetch_oids, &ref->old_oid) &&
421 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
422 !oidset_contains(&fetch_oids, &item->oid))
423 clear_item(item);
424 item = NULL;
425 continue;
429 * If item is non-NULL here, then we previously saw a
430 * ref not followed by a peeled reference, so we need
431 * to check if it is a lightweight tag that we want to
432 * fetch.
434 if (item &&
435 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
436 !oidset_contains(&fetch_oids, &item->oid))
437 clear_item(item);
439 item = NULL;
441 /* skip duplicates and refs that we already have */
442 if (refname_hash_exists(&remote_refs, ref->name) ||
443 refname_hash_exists(&existing_refs, ref->name))
444 continue;
446 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
447 string_list_insert(&remote_refs_list, ref->name);
449 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
452 * We may have a final lightweight tag that needs to be
453 * checked to see if it needs fetching.
455 if (item &&
456 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
457 !oidset_contains(&fetch_oids, &item->oid))
458 clear_item(item);
461 * For all the tags in the remote_refs_list,
462 * add them to the list of refs to be fetched
464 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
465 const char *refname = remote_ref_item->string;
466 struct ref *rm;
467 unsigned int hash = strhash(refname);
469 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
470 struct refname_hash_entry, ent);
471 if (!item)
472 BUG("unseen remote ref?");
474 /* Unless we have already decided to ignore this item... */
475 if (item->ignore)
476 continue;
478 rm = alloc_ref(item->refname);
479 rm->peer_ref = alloc_ref(item->refname);
480 oidcpy(&rm->old_oid, &item->oid);
481 **tail = rm;
482 *tail = &rm->next;
484 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
485 string_list_clear(&remote_refs_list, 0);
486 oidset_clear(&fetch_oids);
489 static void filter_prefetch_refspec(struct refspec *rs)
491 int i;
493 if (!prefetch)
494 return;
496 for (i = 0; i < rs->nr; i++) {
497 struct strbuf new_dst = STRBUF_INIT;
498 char *old_dst;
499 const char *sub = NULL;
501 if (rs->items[i].negative)
502 continue;
503 if (!rs->items[i].dst ||
504 (rs->items[i].src &&
505 !strncmp(rs->items[i].src,
506 ref_namespace[NAMESPACE_TAGS].ref,
507 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
508 int j;
510 free(rs->items[i].src);
511 free(rs->items[i].dst);
513 for (j = i + 1; j < rs->nr; j++) {
514 rs->items[j - 1] = rs->items[j];
515 rs->raw[j - 1] = rs->raw[j];
517 rs->nr--;
518 i--;
519 continue;
522 old_dst = rs->items[i].dst;
523 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
526 * If old_dst starts with "refs/", then place
527 * sub after that prefix. Otherwise, start at
528 * the beginning of the string.
530 if (!skip_prefix(old_dst, "refs/", &sub))
531 sub = old_dst;
532 strbuf_addstr(&new_dst, sub);
534 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
535 rs->items[i].force = 1;
537 free(old_dst);
541 static struct ref *get_ref_map(struct remote *remote,
542 const struct ref *remote_refs,
543 struct refspec *rs,
544 int tags, int *autotags)
546 int i;
547 struct ref *rm;
548 struct ref *ref_map = NULL;
549 struct ref **tail = &ref_map;
551 /* opportunistically-updated references: */
552 struct ref *orefs = NULL, **oref_tail = &orefs;
554 struct hashmap existing_refs;
555 int existing_refs_populated = 0;
557 filter_prefetch_refspec(rs);
558 if (remote)
559 filter_prefetch_refspec(&remote->fetch);
561 if (rs->nr) {
562 struct refspec *fetch_refspec;
564 for (i = 0; i < rs->nr; i++) {
565 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
566 if (rs->items[i].dst && rs->items[i].dst[0])
567 *autotags = 1;
569 /* Merge everything on the command line (but not --tags) */
570 for (rm = ref_map; rm; rm = rm->next)
571 rm->fetch_head_status = FETCH_HEAD_MERGE;
574 * For any refs that we happen to be fetching via
575 * command-line arguments, the destination ref might
576 * have been missing or have been different than the
577 * remote-tracking ref that would be derived from the
578 * configured refspec. In these cases, we want to
579 * take the opportunity to update their configured
580 * remote-tracking reference. However, we do not want
581 * to mention these entries in FETCH_HEAD at all, as
582 * they would simply be duplicates of existing
583 * entries, so we set them FETCH_HEAD_IGNORE below.
585 * We compute these entries now, based only on the
586 * refspecs specified on the command line. But we add
587 * them to the list following the refspecs resulting
588 * from the tags option so that one of the latter,
589 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
590 * by ref_remove_duplicates() in favor of one of these
591 * opportunistic entries with FETCH_HEAD_IGNORE.
593 if (refmap.nr)
594 fetch_refspec = &refmap;
595 else
596 fetch_refspec = &remote->fetch;
598 for (i = 0; i < fetch_refspec->nr; i++)
599 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
600 } else if (refmap.nr) {
601 die("--refmap option is only meaningful with command-line refspec(s)");
602 } else {
603 /* Use the defaults */
604 struct branch *branch = branch_get(NULL);
605 int has_merge = branch_has_merge_config(branch);
606 if (remote &&
607 (remote->fetch.nr ||
608 /* Note: has_merge implies non-NULL branch->remote_name */
609 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
610 for (i = 0; i < remote->fetch.nr; i++) {
611 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
612 if (remote->fetch.items[i].dst &&
613 remote->fetch.items[i].dst[0])
614 *autotags = 1;
615 if (!i && !has_merge && ref_map &&
616 !remote->fetch.items[0].pattern)
617 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
620 * if the remote we're fetching from is the same
621 * as given in branch.<name>.remote, we add the
622 * ref given in branch.<name>.merge, too.
624 * Note: has_merge implies non-NULL branch->remote_name
626 if (has_merge &&
627 !strcmp(branch->remote_name, remote->name))
628 add_merge_config(&ref_map, remote_refs, branch, &tail);
629 } else if (!prefetch) {
630 ref_map = get_remote_ref(remote_refs, "HEAD");
631 if (!ref_map)
632 die(_("couldn't find remote ref HEAD"));
633 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
634 tail = &ref_map->next;
638 if (tags == TAGS_SET)
639 /* also fetch all tags */
640 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
641 else if (tags == TAGS_DEFAULT && *autotags)
642 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
644 /* Now append any refs to be updated opportunistically: */
645 *tail = orefs;
646 for (rm = orefs; rm; rm = rm->next) {
647 rm->fetch_head_status = FETCH_HEAD_IGNORE;
648 tail = &rm->next;
652 * apply negative refspecs first, before we remove duplicates. This is
653 * necessary as negative refspecs might remove an otherwise conflicting
654 * duplicate.
656 if (rs->nr)
657 ref_map = apply_negative_refspecs(ref_map, rs);
658 else
659 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
661 ref_map = ref_remove_duplicates(ref_map);
663 for (rm = ref_map; rm; rm = rm->next) {
664 if (rm->peer_ref) {
665 const char *refname = rm->peer_ref->name;
666 struct refname_hash_entry *peer_item;
667 unsigned int hash = strhash(refname);
669 if (!existing_refs_populated) {
670 refname_hash_init(&existing_refs);
671 for_each_ref(add_one_refname, &existing_refs);
672 existing_refs_populated = 1;
675 peer_item = hashmap_get_entry_from_hash(&existing_refs,
676 hash, refname,
677 struct refname_hash_entry, ent);
678 if (peer_item) {
679 struct object_id *old_oid = &peer_item->oid;
680 oidcpy(&rm->peer_ref->old_oid, old_oid);
684 if (existing_refs_populated)
685 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
687 return ref_map;
690 #define STORE_REF_ERROR_OTHER 1
691 #define STORE_REF_ERROR_DF_CONFLICT 2
693 static int s_update_ref(const char *action,
694 struct ref *ref,
695 struct ref_transaction *transaction,
696 int check_old)
698 char *msg;
699 char *rla = getenv("GIT_REFLOG_ACTION");
700 struct ref_transaction *our_transaction = NULL;
701 struct strbuf err = STRBUF_INIT;
702 int ret;
704 if (dry_run)
705 return 0;
706 if (!rla)
707 rla = default_rla.buf;
708 msg = xstrfmt("%s: %s", rla, action);
711 * If no transaction was passed to us, we manage the transaction
712 * ourselves. Otherwise, we trust the caller to handle the transaction
713 * lifecycle.
715 if (!transaction) {
716 transaction = our_transaction = ref_transaction_begin(&err);
717 if (!transaction) {
718 ret = STORE_REF_ERROR_OTHER;
719 goto out;
723 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
724 check_old ? &ref->old_oid : NULL,
725 0, msg, &err);
726 if (ret) {
727 ret = STORE_REF_ERROR_OTHER;
728 goto out;
731 if (our_transaction) {
732 switch (ref_transaction_commit(our_transaction, &err)) {
733 case 0:
734 break;
735 case TRANSACTION_NAME_CONFLICT:
736 ret = STORE_REF_ERROR_DF_CONFLICT;
737 goto out;
738 default:
739 ret = STORE_REF_ERROR_OTHER;
740 goto out;
744 out:
745 ref_transaction_free(our_transaction);
746 if (ret)
747 error("%s", err.buf);
748 strbuf_release(&err);
749 free(msg);
750 return ret;
753 static int refcol_width = 10;
754 static int compact_format;
756 static void adjust_refcol_width(const struct ref *ref)
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;
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;
784 * Not precise calculation for compact mode because '*' can
785 * appear on the left hand side of '->' and shrink the column
786 * back.
788 if (refcol_width < rlen)
789 refcol_width = rlen;
792 static void prepare_format_display(struct ref *ref_map)
794 struct ref *rm;
795 const char *format = "full";
797 if (verbosity < 0)
798 return;
800 git_config_get_string_tmp("fetch.output", &format);
801 if (!strcasecmp(format, "full"))
802 compact_format = 0;
803 else if (!strcasecmp(format, "compact"))
804 compact_format = 1;
805 else
806 die(_("invalid value for '%s': '%s'"),
807 "fetch.output", format);
809 for (rm = ref_map; rm; rm = rm->next) {
810 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
811 !rm->peer_ref ||
812 !strcmp(rm->name, "HEAD"))
813 continue;
815 adjust_refcol_width(rm);
819 static void print_remote_to_local(struct strbuf *display,
820 const char *remote, const char *local)
822 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
825 static int find_and_replace(struct strbuf *haystack,
826 const char *needle,
827 const char *placeholder)
829 const char *p = NULL;
830 int plen, nlen;
832 nlen = strlen(needle);
833 if (ends_with(haystack->buf, needle))
834 p = haystack->buf + haystack->len - nlen;
835 else
836 p = strstr(haystack->buf, needle);
837 if (!p)
838 return 0;
840 if (p > haystack->buf && p[-1] != '/')
841 return 0;
843 plen = strlen(p);
844 if (plen > nlen && p[nlen] != '/')
845 return 0;
847 strbuf_splice(haystack, p - haystack->buf, nlen,
848 placeholder, strlen(placeholder));
849 return 1;
852 static void print_compact(struct strbuf *display,
853 const char *remote, const char *local)
855 struct strbuf r = STRBUF_INIT;
856 struct strbuf l = STRBUF_INIT;
858 if (!strcmp(remote, local)) {
859 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
860 return;
863 strbuf_addstr(&r, remote);
864 strbuf_addstr(&l, local);
866 if (!find_and_replace(&r, local, "*"))
867 find_and_replace(&l, remote, "*");
868 print_remote_to_local(display, r.buf, l.buf);
870 strbuf_release(&r);
871 strbuf_release(&l);
874 static void format_display(struct strbuf *display, char code,
875 const char *summary, const char *error,
876 const char *remote, const char *local,
877 int summary_width)
879 int width;
881 if (verbosity < 0)
882 return;
884 width = (summary_width + strlen(summary) - gettext_width(summary));
886 strbuf_addf(display, "%c %-*s ", code, width, summary);
887 if (!compact_format)
888 print_remote_to_local(display, remote, local);
889 else
890 print_compact(display, remote, local);
891 if (error)
892 strbuf_addf(display, " (%s)", error);
895 static int update_local_ref(struct ref *ref,
896 struct ref_transaction *transaction,
897 const char *remote, const struct ref *remote_ref,
898 struct strbuf *display, int summary_width)
900 struct commit *current = NULL, *updated;
901 const char *pretty_ref = prettify_refname(ref->name);
902 int fast_forward = 0;
904 if (!repo_has_object_file(the_repository, &ref->new_oid))
905 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
907 if (oideq(&ref->old_oid, &ref->new_oid)) {
908 if (verbosity > 0)
909 format_display(display, '=', _("[up to date]"), NULL,
910 remote, pretty_ref, summary_width);
911 return 0;
914 if (!update_head_ok &&
915 !is_null_oid(&ref->old_oid) &&
916 branch_checked_out(ref->name)) {
918 * If this is the head, and it's not okay to update
919 * the head, and the old value of the head isn't empty...
921 format_display(display, '!', _("[rejected]"),
922 _("can't fetch into checked-out branch"),
923 remote, pretty_ref, summary_width);
924 return 1;
927 if (!is_null_oid(&ref->old_oid) &&
928 starts_with(ref->name, "refs/tags/")) {
929 if (force || ref->force) {
930 int r;
931 r = s_update_ref("updating tag", ref, transaction, 0);
932 format_display(display, r ? '!' : 't', _("[tag update]"),
933 r ? _("unable to update local ref") : NULL,
934 remote, pretty_ref, summary_width);
935 return r;
936 } else {
937 format_display(display, '!', _("[rejected]"), _("would clobber existing tag"),
938 remote, pretty_ref, summary_width);
939 return 1;
943 current = lookup_commit_reference_gently(the_repository,
944 &ref->old_oid, 1);
945 updated = lookup_commit_reference_gently(the_repository,
946 &ref->new_oid, 1);
947 if (!current || !updated) {
948 const char *msg;
949 const char *what;
950 int r;
952 * Nicely describe the new ref we're fetching.
953 * Base this on the remote's ref name, as it's
954 * more likely to follow a standard layout.
956 const char *name = remote_ref ? remote_ref->name : "";
957 if (starts_with(name, "refs/tags/")) {
958 msg = "storing tag";
959 what = _("[new tag]");
960 } else if (starts_with(name, "refs/heads/")) {
961 msg = "storing head";
962 what = _("[new branch]");
963 } else {
964 msg = "storing ref";
965 what = _("[new ref]");
968 r = s_update_ref(msg, ref, transaction, 0);
969 format_display(display, r ? '!' : '*', what,
970 r ? _("unable to update local ref") : NULL,
971 remote, pretty_ref, summary_width);
972 return r;
975 if (fetch_show_forced_updates) {
976 uint64_t t_before = getnanotime();
977 fast_forward = repo_in_merge_bases(the_repository, current,
978 updated);
979 forced_updates_ms += (getnanotime() - t_before) / 1000000;
980 } else {
981 fast_forward = 1;
984 if (fast_forward) {
985 struct strbuf quickref = STRBUF_INIT;
986 int r;
988 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
989 strbuf_addstr(&quickref, "..");
990 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
991 r = s_update_ref("fast-forward", ref, transaction, 1);
992 format_display(display, r ? '!' : ' ', quickref.buf,
993 r ? _("unable to update local ref") : NULL,
994 remote, pretty_ref, summary_width);
995 strbuf_release(&quickref);
996 return r;
997 } else if (force || ref->force) {
998 struct strbuf quickref = STRBUF_INIT;
999 int r;
1000 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1001 strbuf_addstr(&quickref, "...");
1002 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1003 r = s_update_ref("forced-update", ref, transaction, 1);
1004 format_display(display, r ? '!' : '+', quickref.buf,
1005 r ? _("unable to update local ref") : _("forced update"),
1006 remote, pretty_ref, summary_width);
1007 strbuf_release(&quickref);
1008 return r;
1009 } else {
1010 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
1011 remote, pretty_ref, summary_width);
1012 return 1;
1016 static const struct object_id *iterate_ref_map(void *cb_data)
1018 struct ref **rm = cb_data;
1019 struct ref *ref = *rm;
1021 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1022 ref = ref->next;
1023 if (!ref)
1024 return NULL;
1025 *rm = ref->next;
1026 return &ref->old_oid;
1029 struct fetch_head {
1030 FILE *fp;
1031 struct strbuf buf;
1034 static int open_fetch_head(struct fetch_head *fetch_head)
1036 const char *filename = git_path_fetch_head(the_repository);
1038 if (write_fetch_head) {
1039 fetch_head->fp = fopen(filename, "a");
1040 if (!fetch_head->fp)
1041 return error_errno(_("cannot open '%s'"), filename);
1042 strbuf_init(&fetch_head->buf, 0);
1043 } else {
1044 fetch_head->fp = NULL;
1047 return 0;
1050 static void append_fetch_head(struct fetch_head *fetch_head,
1051 const struct object_id *old_oid,
1052 enum fetch_head_status fetch_head_status,
1053 const char *note,
1054 const char *url, size_t url_len)
1056 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1057 const char *merge_status_marker;
1058 size_t i;
1060 if (!fetch_head->fp)
1061 return;
1063 switch (fetch_head_status) {
1064 case FETCH_HEAD_NOT_FOR_MERGE:
1065 merge_status_marker = "not-for-merge";
1066 break;
1067 case FETCH_HEAD_MERGE:
1068 merge_status_marker = "";
1069 break;
1070 default:
1071 /* do not write anything to FETCH_HEAD */
1072 return;
1075 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1076 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1077 for (i = 0; i < url_len; ++i)
1078 if ('\n' == url[i])
1079 strbuf_addstr(&fetch_head->buf, "\\n");
1080 else
1081 strbuf_addch(&fetch_head->buf, url[i]);
1082 strbuf_addch(&fetch_head->buf, '\n');
1085 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1086 * any of the reference updates fails. We thus have to write all
1087 * updates to a buffer first and only commit it as soon as all
1088 * references have been successfully updated.
1090 if (!atomic_fetch) {
1091 strbuf_write(&fetch_head->buf, fetch_head->fp);
1092 strbuf_reset(&fetch_head->buf);
1096 static void commit_fetch_head(struct fetch_head *fetch_head)
1098 if (!fetch_head->fp || !atomic_fetch)
1099 return;
1100 strbuf_write(&fetch_head->buf, fetch_head->fp);
1103 static void close_fetch_head(struct fetch_head *fetch_head)
1105 if (!fetch_head->fp)
1106 return;
1108 fclose(fetch_head->fp);
1109 strbuf_release(&fetch_head->buf);
1112 static const char warn_show_forced_updates[] =
1113 N_("fetch normally indicates which branches had a forced update,\n"
1114 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1115 "flag or run 'git config fetch.showForcedUpdates true'");
1116 static const char warn_time_show_forced_updates[] =
1117 N_("it took %.2f seconds to check forced updates; you can use\n"
1118 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1119 "to avoid this check\n");
1121 static int store_updated_refs(const char *raw_url, const char *remote_name,
1122 int connectivity_checked,
1123 struct ref_transaction *transaction, struct ref *ref_map,
1124 struct fetch_head *fetch_head)
1126 int url_len, i, rc = 0;
1127 struct strbuf note = STRBUF_INIT;
1128 const char *what, *kind;
1129 struct ref *rm;
1130 char *url;
1131 int want_status;
1132 int summary_width = 0;
1134 if (verbosity >= 0)
1135 summary_width = transport_summary_width(ref_map);
1137 if (raw_url)
1138 url = transport_anonymize_url(raw_url);
1139 else
1140 url = xstrdup("foreign");
1142 if (!connectivity_checked) {
1143 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1145 opt.exclude_hidden_refs_section = "fetch";
1146 rm = ref_map;
1147 if (check_connected(iterate_ref_map, &rm, &opt)) {
1148 rc = error(_("%s did not send all necessary objects\n"), url);
1149 goto abort;
1153 prepare_format_display(ref_map);
1156 * We do a pass for each fetch_head_status type in their enum order, so
1157 * merged entries are written before not-for-merge. That lets readers
1158 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1160 for (want_status = FETCH_HEAD_MERGE;
1161 want_status <= FETCH_HEAD_IGNORE;
1162 want_status++) {
1163 for (rm = ref_map; rm; rm = rm->next) {
1164 struct ref *ref = NULL;
1166 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1167 if (want_status == FETCH_HEAD_MERGE)
1168 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1169 rm->peer_ref ? rm->peer_ref->name : rm->name);
1170 continue;
1174 * When writing FETCH_HEAD we need to determine whether
1175 * we already have the commit or not. If not, then the
1176 * reference is not for merge and needs to be written
1177 * to the reflog after other commits which we already
1178 * have. We're not interested in this property though
1179 * in case FETCH_HEAD is not to be updated, so we can
1180 * skip the classification in that case.
1182 if (fetch_head->fp) {
1183 struct commit *commit = NULL;
1186 * References in "refs/tags/" are often going to point
1187 * to annotated tags, which are not part of the
1188 * commit-graph. We thus only try to look up refs in
1189 * the graph which are not in that namespace to not
1190 * regress performance in repositories with many
1191 * annotated tags.
1193 if (!starts_with(rm->name, "refs/tags/"))
1194 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1195 if (!commit) {
1196 commit = lookup_commit_reference_gently(the_repository,
1197 &rm->old_oid,
1199 if (!commit)
1200 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1204 if (rm->fetch_head_status != want_status)
1205 continue;
1207 if (rm->peer_ref) {
1208 ref = alloc_ref(rm->peer_ref->name);
1209 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1210 oidcpy(&ref->new_oid, &rm->old_oid);
1211 ref->force = rm->peer_ref->force;
1214 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1215 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1216 check_for_new_submodule_commits(&rm->old_oid);
1219 if (!strcmp(rm->name, "HEAD")) {
1220 kind = "";
1221 what = "";
1223 else if (skip_prefix(rm->name, "refs/heads/", &what))
1224 kind = "branch";
1225 else if (skip_prefix(rm->name, "refs/tags/", &what))
1226 kind = "tag";
1227 else if (skip_prefix(rm->name, "refs/remotes/", &what))
1228 kind = "remote-tracking branch";
1229 else {
1230 kind = "";
1231 what = rm->name;
1234 url_len = strlen(url);
1235 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1237 url_len = i + 1;
1238 if (4 < i && !strncmp(".git", url + i - 3, 4))
1239 url_len = i - 3;
1241 strbuf_reset(&note);
1242 if (*what) {
1243 if (*kind)
1244 strbuf_addf(&note, "%s ", kind);
1245 strbuf_addf(&note, "'%s' of ", what);
1248 append_fetch_head(fetch_head, &rm->old_oid,
1249 rm->fetch_head_status,
1250 note.buf, url, url_len);
1252 strbuf_reset(&note);
1253 if (ref) {
1254 rc |= update_local_ref(ref, transaction, what,
1255 rm, &note, summary_width);
1256 free(ref);
1257 } else if (write_fetch_head || dry_run) {
1259 * Display fetches written to FETCH_HEAD (or
1260 * would be written to FETCH_HEAD, if --dry-run
1261 * is set).
1263 format_display(&note, '*',
1264 *kind ? kind : "branch", NULL,
1265 *what ? what : "HEAD",
1266 "FETCH_HEAD", summary_width);
1268 if (note.len) {
1269 if (!shown_url) {
1270 fprintf(stderr, _("From %.*s\n"),
1271 url_len, url);
1272 shown_url = 1;
1274 fprintf(stderr, " %s\n", note.buf);
1279 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1280 error(_("some local refs could not be updated; try running\n"
1281 " 'git remote prune %s' to remove any old, conflicting "
1282 "branches"), remote_name);
1284 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1285 if (!fetch_show_forced_updates) {
1286 warning(_(warn_show_forced_updates));
1287 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1288 warning(_(warn_time_show_forced_updates),
1289 forced_updates_ms / 1000.0);
1293 abort:
1294 strbuf_release(&note);
1295 free(url);
1296 return rc;
1300 * We would want to bypass the object transfer altogether if
1301 * everything we are going to fetch already exists and is connected
1302 * locally.
1304 static int check_exist_and_connected(struct ref *ref_map)
1306 struct ref *rm = ref_map;
1307 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1308 struct ref *r;
1311 * If we are deepening a shallow clone we already have these
1312 * objects reachable. Running rev-list here will return with
1313 * a good (0) exit status and we'll bypass the fetch that we
1314 * really need to perform. Claiming failure now will ensure
1315 * we perform the network exchange to deepen our history.
1317 if (deepen)
1318 return -1;
1321 * Similarly, if we need to refetch, we always want to perform a full
1322 * fetch ignoring existing objects.
1324 if (refetch)
1325 return -1;
1329 * check_connected() allows objects to merely be promised, but
1330 * we need all direct targets to exist.
1332 for (r = rm; r; r = r->next) {
1333 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1334 OBJECT_INFO_SKIP_FETCH_OBJECT))
1335 return -1;
1338 opt.quiet = 1;
1339 opt.exclude_hidden_refs_section = "fetch";
1340 return check_connected(iterate_ref_map, &rm, &opt);
1343 static int fetch_and_consume_refs(struct transport *transport,
1344 struct ref_transaction *transaction,
1345 struct ref *ref_map,
1346 struct fetch_head *fetch_head)
1348 int connectivity_checked = 1;
1349 int ret;
1352 * We don't need to perform a fetch in case we can already satisfy all
1353 * refs.
1355 ret = check_exist_and_connected(ref_map);
1356 if (ret) {
1357 trace2_region_enter("fetch", "fetch_refs", the_repository);
1358 ret = transport_fetch_refs(transport, ref_map);
1359 trace2_region_leave("fetch", "fetch_refs", the_repository);
1360 if (ret)
1361 goto out;
1362 connectivity_checked = transport->smart_options ?
1363 transport->smart_options->connectivity_checked : 0;
1366 trace2_region_enter("fetch", "consume_refs", the_repository);
1367 ret = store_updated_refs(transport->url, transport->remote->name,
1368 connectivity_checked, transaction, ref_map,
1369 fetch_head);
1370 trace2_region_leave("fetch", "consume_refs", the_repository);
1372 out:
1373 transport_unlock_pack(transport, 0);
1374 return ret;
1377 static int prune_refs(struct refspec *rs,
1378 struct ref_transaction *transaction,
1379 struct ref *ref_map,
1380 const char *raw_url)
1382 int url_len, i, result = 0;
1383 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1384 struct strbuf err = STRBUF_INIT;
1385 char *url;
1386 const char *dangling_msg = dry_run
1387 ? _(" (%s will become dangling)")
1388 : _(" (%s has become dangling)");
1390 if (raw_url)
1391 url = transport_anonymize_url(raw_url);
1392 else
1393 url = xstrdup("foreign");
1395 url_len = strlen(url);
1396 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1399 url_len = i + 1;
1400 if (4 < i && !strncmp(".git", url + i - 3, 4))
1401 url_len = i - 3;
1403 if (!dry_run) {
1404 if (transaction) {
1405 for (ref = stale_refs; ref; ref = ref->next) {
1406 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1407 "fetch: prune", &err);
1408 if (result)
1409 goto cleanup;
1411 } else {
1412 struct string_list refnames = STRING_LIST_INIT_NODUP;
1414 for (ref = stale_refs; ref; ref = ref->next)
1415 string_list_append(&refnames, ref->name);
1417 result = delete_refs("fetch: prune", &refnames, 0);
1418 string_list_clear(&refnames, 0);
1422 if (verbosity >= 0) {
1423 int summary_width = transport_summary_width(stale_refs);
1425 for (ref = stale_refs; ref; ref = ref->next) {
1426 struct strbuf sb = STRBUF_INIT;
1427 if (!shown_url) {
1428 fprintf(stderr, _("From %.*s\n"), url_len, url);
1429 shown_url = 1;
1431 format_display(&sb, '-', _("[deleted]"), NULL,
1432 _("(none)"), prettify_refname(ref->name),
1433 summary_width);
1434 fprintf(stderr, " %s\n",sb.buf);
1435 strbuf_release(&sb);
1436 warn_dangling_symref(stderr, dangling_msg, ref->name);
1440 cleanup:
1441 strbuf_release(&err);
1442 free(url);
1443 free_refs(stale_refs);
1444 return result;
1447 static void check_not_current_branch(struct ref *ref_map)
1449 const char *path;
1450 for (; ref_map; ref_map = ref_map->next)
1451 if (ref_map->peer_ref &&
1452 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1453 (path = branch_checked_out(ref_map->peer_ref->name)))
1454 die(_("refusing to fetch into branch '%s' "
1455 "checked out at '%s'"),
1456 ref_map->peer_ref->name, path);
1459 static int truncate_fetch_head(void)
1461 const char *filename = git_path_fetch_head(the_repository);
1462 FILE *fp = fopen_for_writing(filename);
1464 if (!fp)
1465 return error_errno(_("cannot open '%s'"), filename);
1466 fclose(fp);
1467 return 0;
1470 static void set_option(struct transport *transport, const char *name, const char *value)
1472 int r = transport_set_option(transport, name, value);
1473 if (r < 0)
1474 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1475 name, value, transport->url);
1476 if (r > 0)
1477 warning(_("option \"%s\" is ignored for %s\n"),
1478 name, transport->url);
1482 static int add_oid(const char *refname UNUSED,
1483 const struct object_id *oid,
1484 int flags UNUSED, void *cb_data)
1486 struct oid_array *oids = cb_data;
1488 oid_array_append(oids, oid);
1489 return 0;
1492 static void add_negotiation_tips(struct git_transport_options *smart_options)
1494 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1495 int i;
1497 for (i = 0; i < negotiation_tip.nr; i++) {
1498 const char *s = negotiation_tip.items[i].string;
1499 int old_nr;
1500 if (!has_glob_specials(s)) {
1501 struct object_id oid;
1502 if (repo_get_oid(the_repository, s, &oid))
1503 die(_("%s is not a valid object"), s);
1504 if (!has_object(the_repository, &oid, 0))
1505 die(_("the object %s does not exist"), s);
1506 oid_array_append(oids, &oid);
1507 continue;
1509 old_nr = oids->nr;
1510 for_each_glob_ref(add_oid, s, oids);
1511 if (old_nr == oids->nr)
1512 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1515 smart_options->negotiation_tips = oids;
1518 static struct transport *prepare_transport(struct remote *remote, int deepen)
1520 struct transport *transport;
1522 transport = transport_get(remote, NULL);
1523 transport_set_verbosity(transport, verbosity, progress);
1524 transport->family = family;
1525 if (upload_pack)
1526 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1527 if (keep)
1528 set_option(transport, TRANS_OPT_KEEP, "yes");
1529 if (depth)
1530 set_option(transport, TRANS_OPT_DEPTH, depth);
1531 if (deepen && deepen_since)
1532 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1533 if (deepen && deepen_not.nr)
1534 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1535 (const char *)&deepen_not);
1536 if (deepen_relative)
1537 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1538 if (update_shallow)
1539 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1540 if (refetch)
1541 set_option(transport, TRANS_OPT_REFETCH, "yes");
1542 if (filter_options.choice) {
1543 const char *spec =
1544 expand_list_objects_filter_spec(&filter_options);
1545 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1546 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1548 if (negotiation_tip.nr) {
1549 if (transport->smart_options)
1550 add_negotiation_tips(transport->smart_options);
1551 else
1552 warning("ignoring --negotiation-tip because the protocol does not support it");
1554 return transport;
1557 static int backfill_tags(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(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 int autotags = (transport->remote->fetch_tags == 1);
1597 int retcode = 0;
1598 const struct ref *remote_refs;
1599 struct transport_ls_refs_options transport_ls_refs_options =
1600 TRANSPORT_LS_REFS_OPTIONS_INIT;
1601 int must_list_refs = 1;
1602 struct fetch_head fetch_head = { 0 };
1603 struct strbuf err = STRBUF_INIT;
1605 if (tags == TAGS_DEFAULT) {
1606 if (transport->remote->fetch_tags == 2)
1607 tags = TAGS_SET;
1608 if (transport->remote->fetch_tags == -1)
1609 tags = TAGS_UNSET;
1612 /* if not appending, truncate FETCH_HEAD */
1613 if (!append && write_fetch_head) {
1614 retcode = truncate_fetch_head();
1615 if (retcode)
1616 goto cleanup;
1619 if (rs->nr) {
1620 int i;
1622 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1625 * We can avoid listing refs if all of them are exact
1626 * OIDs
1628 must_list_refs = 0;
1629 for (i = 0; i < rs->nr; i++) {
1630 if (!rs->items[i].exact_sha1) {
1631 must_list_refs = 1;
1632 break;
1635 } else {
1636 struct branch *branch = branch_get(NULL);
1638 if (transport->remote->fetch.nr)
1639 refspec_ref_prefixes(&transport->remote->fetch,
1640 &transport_ls_refs_options.ref_prefixes);
1641 if (branch_has_merge_config(branch) &&
1642 !strcmp(branch->remote_name, transport->remote->name)) {
1643 int i;
1644 for (i = 0; i < branch->merge_nr; i++) {
1645 strvec_push(&transport_ls_refs_options.ref_prefixes,
1646 branch->merge[i]->src);
1651 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1652 must_list_refs = 1;
1653 if (transport_ls_refs_options.ref_prefixes.nr)
1654 strvec_push(&transport_ls_refs_options.ref_prefixes,
1655 "refs/tags/");
1658 if (must_list_refs) {
1659 trace2_region_enter("fetch", "remote_refs", the_repository);
1660 remote_refs = transport_get_remote_refs(transport,
1661 &transport_ls_refs_options);
1662 trace2_region_leave("fetch", "remote_refs", the_repository);
1663 } else
1664 remote_refs = NULL;
1666 transport_ls_refs_options_release(&transport_ls_refs_options);
1668 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1669 tags, &autotags);
1670 if (!update_head_ok)
1671 check_not_current_branch(ref_map);
1673 retcode = open_fetch_head(&fetch_head);
1674 if (retcode)
1675 goto cleanup;
1677 if (atomic_fetch) {
1678 transaction = ref_transaction_begin(&err);
1679 if (!transaction) {
1680 retcode = error("%s", err.buf);
1681 goto cleanup;
1685 if (tags == TAGS_DEFAULT && autotags)
1686 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1687 if (prune) {
1689 * We only prune based on refspecs specified
1690 * explicitly (via command line or configuration); we
1691 * don't care whether --tags was specified.
1693 if (rs->nr) {
1694 retcode = prune_refs(rs, transaction, ref_map, transport->url);
1695 } else {
1696 retcode = prune_refs(&transport->remote->fetch,
1697 transaction, ref_map,
1698 transport->url);
1700 if (retcode != 0)
1701 retcode = 1;
1704 if (fetch_and_consume_refs(transport, transaction, ref_map, &fetch_head)) {
1705 retcode = 1;
1706 goto cleanup;
1710 * If neither --no-tags nor --tags was specified, do automated tag
1711 * following.
1713 if (tags == TAGS_DEFAULT && autotags) {
1714 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1716 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1717 if (tags_ref_map) {
1719 * If backfilling of tags fails then we want to tell
1720 * the user so, but we have to continue regardless to
1721 * populate upstream information of the references we
1722 * have already fetched above. The exception though is
1723 * when `--atomic` is passed: in that case we'll abort
1724 * the transaction and don't commit anything.
1726 if (backfill_tags(transport, transaction, tags_ref_map,
1727 &fetch_head))
1728 retcode = 1;
1731 free_refs(tags_ref_map);
1734 if (transaction) {
1735 if (retcode)
1736 goto cleanup;
1738 retcode = ref_transaction_commit(transaction, &err);
1739 if (retcode) {
1740 error("%s", err.buf);
1741 ref_transaction_free(transaction);
1742 transaction = NULL;
1743 goto cleanup;
1747 commit_fetch_head(&fetch_head);
1749 if (set_upstream) {
1750 struct branch *branch = branch_get("HEAD");
1751 struct ref *rm;
1752 struct ref *source_ref = NULL;
1755 * We're setting the upstream configuration for the
1756 * current branch. The relevant upstream is the
1757 * fetched branch that is meant to be merged with the
1758 * current one, i.e. the one fetched to FETCH_HEAD.
1760 * When there are several such branches, consider the
1761 * request ambiguous and err on the safe side by doing
1762 * nothing and just emit a warning.
1764 for (rm = ref_map; rm; rm = rm->next) {
1765 if (!rm->peer_ref) {
1766 if (source_ref) {
1767 warning(_("multiple branches detected, incompatible with --set-upstream"));
1768 goto cleanup;
1769 } else {
1770 source_ref = rm;
1774 if (source_ref) {
1775 if (!branch) {
1776 const char *shortname = source_ref->name;
1777 skip_prefix(shortname, "refs/heads/", &shortname);
1779 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1780 "it does not point to any branch."),
1781 shortname, transport->remote->name);
1782 goto cleanup;
1785 if (!strcmp(source_ref->name, "HEAD") ||
1786 starts_with(source_ref->name, "refs/heads/"))
1787 install_branch_config(0,
1788 branch->name,
1789 transport->remote->name,
1790 source_ref->name);
1791 else if (starts_with(source_ref->name, "refs/remotes/"))
1792 warning(_("not setting upstream for a remote remote-tracking branch"));
1793 else if (starts_with(source_ref->name, "refs/tags/"))
1794 warning(_("not setting upstream for a remote tag"));
1795 else
1796 warning(_("unknown branch type"));
1797 } else {
1798 warning(_("no source branch found;\n"
1799 "you need to specify exactly one branch with the --set-upstream option"));
1803 cleanup:
1804 if (retcode && transaction) {
1805 ref_transaction_abort(transaction, &err);
1806 error("%s", err.buf);
1809 close_fetch_head(&fetch_head);
1810 strbuf_release(&err);
1811 free_refs(ref_map);
1812 return retcode;
1815 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1817 struct string_list *list = priv;
1818 if (!remote->skip_default_update)
1819 string_list_append(list, remote->name);
1820 return 0;
1823 struct remote_group_data {
1824 const char *name;
1825 struct string_list *list;
1828 static int get_remote_group(const char *key, const char *value, void *priv)
1830 struct remote_group_data *g = priv;
1832 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1833 /* split list by white space */
1834 while (*value) {
1835 size_t wordlen = strcspn(value, " \t\n");
1837 if (wordlen >= 1)
1838 string_list_append_nodup(g->list,
1839 xstrndup(value, wordlen));
1840 value += wordlen + (value[wordlen] != '\0');
1844 return 0;
1847 static int add_remote_or_group(const char *name, struct string_list *list)
1849 int prev_nr = list->nr;
1850 struct remote_group_data g;
1851 g.name = name; g.list = list;
1853 git_config(get_remote_group, &g);
1854 if (list->nr == prev_nr) {
1855 struct remote *remote = remote_get(name);
1856 if (!remote_is_configured(remote, 0))
1857 return 0;
1858 string_list_append(list, remote->name);
1860 return 1;
1863 static void add_options_to_argv(struct strvec *argv)
1865 if (dry_run)
1866 strvec_push(argv, "--dry-run");
1867 if (prune != -1)
1868 strvec_push(argv, prune ? "--prune" : "--no-prune");
1869 if (prune_tags != -1)
1870 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1871 if (update_head_ok)
1872 strvec_push(argv, "--update-head-ok");
1873 if (force)
1874 strvec_push(argv, "--force");
1875 if (keep)
1876 strvec_push(argv, "--keep");
1877 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1878 strvec_push(argv, "--recurse-submodules");
1879 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1880 strvec_push(argv, "--recurse-submodules=on-demand");
1881 if (tags == TAGS_SET)
1882 strvec_push(argv, "--tags");
1883 else if (tags == TAGS_UNSET)
1884 strvec_push(argv, "--no-tags");
1885 if (verbosity >= 2)
1886 strvec_push(argv, "-v");
1887 if (verbosity >= 1)
1888 strvec_push(argv, "-v");
1889 else if (verbosity < 0)
1890 strvec_push(argv, "-q");
1891 if (family == TRANSPORT_FAMILY_IPV4)
1892 strvec_push(argv, "--ipv4");
1893 else if (family == TRANSPORT_FAMILY_IPV6)
1894 strvec_push(argv, "--ipv6");
1895 if (!write_fetch_head)
1896 strvec_push(argv, "--no-write-fetch-head");
1899 /* Fetch multiple remotes in parallel */
1901 struct parallel_fetch_state {
1902 const char **argv;
1903 struct string_list *remotes;
1904 int next, result;
1907 static int fetch_next_remote(struct child_process *cp,
1908 struct strbuf *out UNUSED,
1909 void *cb, void **task_cb)
1911 struct parallel_fetch_state *state = cb;
1912 char *remote;
1914 if (state->next < 0 || state->next >= state->remotes->nr)
1915 return 0;
1917 remote = state->remotes->items[state->next++].string;
1918 *task_cb = remote;
1920 strvec_pushv(&cp->args, state->argv);
1921 strvec_push(&cp->args, remote);
1922 cp->git_cmd = 1;
1924 if (verbosity >= 0)
1925 printf(_("Fetching %s\n"), remote);
1927 return 1;
1930 static int fetch_failed_to_start(struct strbuf *out UNUSED,
1931 void *cb, void *task_cb)
1933 struct parallel_fetch_state *state = cb;
1934 const char *remote = task_cb;
1936 state->result = error(_("could not fetch %s"), remote);
1938 return 0;
1941 static int fetch_finished(int result, struct strbuf *out,
1942 void *cb, void *task_cb)
1944 struct parallel_fetch_state *state = cb;
1945 const char *remote = task_cb;
1947 if (result) {
1948 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1949 remote, result);
1950 state->result = -1;
1953 return 0;
1956 static int fetch_multiple(struct string_list *list, int max_children)
1958 int i, result = 0;
1959 struct strvec argv = STRVEC_INIT;
1961 if (!append && write_fetch_head) {
1962 int errcode = truncate_fetch_head();
1963 if (errcode)
1964 return errcode;
1967 strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
1968 "--no-write-commit-graph", NULL);
1969 add_options_to_argv(&argv);
1971 if (max_children != 1 && list->nr != 1) {
1972 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1973 const struct run_process_parallel_opts opts = {
1974 .tr2_category = "fetch",
1975 .tr2_label = "parallel/fetch",
1977 .processes = max_children,
1979 .get_next_task = &fetch_next_remote,
1980 .start_failure = &fetch_failed_to_start,
1981 .task_finished = &fetch_finished,
1982 .data = &state,
1985 strvec_push(&argv, "--end-of-options");
1987 run_processes_parallel(&opts);
1988 result = state.result;
1989 } else
1990 for (i = 0; i < list->nr; i++) {
1991 const char *name = list->items[i].string;
1992 struct child_process cmd = CHILD_PROCESS_INIT;
1994 strvec_pushv(&cmd.args, argv.v);
1995 strvec_push(&cmd.args, name);
1996 if (verbosity >= 0)
1997 printf(_("Fetching %s\n"), name);
1998 cmd.git_cmd = 1;
1999 if (run_command(&cmd)) {
2000 error(_("could not fetch %s"), name);
2001 result = 1;
2005 strvec_clear(&argv);
2006 return !!result;
2010 * Fetching from the promisor remote should use the given filter-spec
2011 * or inherit the default filter-spec from the config.
2013 static inline void fetch_one_setup_partial(struct remote *remote)
2016 * Explicit --no-filter argument overrides everything, regardless
2017 * of any prior partial clones and fetches.
2019 if (filter_options.no_filter)
2020 return;
2023 * If no prior partial clone/fetch and the current fetch DID NOT
2024 * request a partial-fetch, do a normal fetch.
2026 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
2027 return;
2030 * If this is a partial-fetch request, we enable partial on
2031 * this repo if not already enabled and remember the given
2032 * filter-spec as the default for subsequent fetches to this
2033 * remote if there is currently no default filter-spec.
2035 if (filter_options.choice) {
2036 partial_clone_register(remote->name, &filter_options);
2037 return;
2041 * Do a partial-fetch from the promisor remote using either the
2042 * explicitly given filter-spec or inherit the filter-spec from
2043 * the config.
2045 if (!filter_options.choice)
2046 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2047 return;
2050 static int fetch_one(struct remote *remote, int argc, const char **argv,
2051 int prune_tags_ok, int use_stdin_refspecs)
2053 struct refspec rs = REFSPEC_INIT_FETCH;
2054 int i;
2055 int exit_code;
2056 int maybe_prune_tags;
2057 int remote_via_config = remote_is_configured(remote, 0);
2059 if (!remote)
2060 die(_("no remote repository specified; please specify either a URL or a\n"
2061 "remote name from which new revisions should be fetched"));
2063 gtransport = prepare_transport(remote, 1);
2065 if (prune < 0) {
2066 /* no command line request */
2067 if (0 <= remote->prune)
2068 prune = remote->prune;
2069 else if (0 <= fetch_prune_config)
2070 prune = fetch_prune_config;
2071 else
2072 prune = PRUNE_BY_DEFAULT;
2075 if (prune_tags < 0) {
2076 /* no command line request */
2077 if (0 <= remote->prune_tags)
2078 prune_tags = remote->prune_tags;
2079 else if (0 <= fetch_prune_tags_config)
2080 prune_tags = fetch_prune_tags_config;
2081 else
2082 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2085 maybe_prune_tags = prune_tags_ok && prune_tags;
2086 if (maybe_prune_tags && remote_via_config)
2087 refspec_append(&remote->fetch, TAG_REFSPEC);
2089 if (maybe_prune_tags && (argc || !remote_via_config))
2090 refspec_append(&rs, TAG_REFSPEC);
2092 for (i = 0; i < argc; i++) {
2093 if (!strcmp(argv[i], "tag")) {
2094 i++;
2095 if (i >= argc)
2096 die(_("you need to specify a tag name"));
2098 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2099 argv[i], argv[i]);
2100 } else {
2101 refspec_append(&rs, argv[i]);
2105 if (use_stdin_refspecs) {
2106 struct strbuf line = STRBUF_INIT;
2107 while (strbuf_getline_lf(&line, stdin) != EOF)
2108 refspec_append(&rs, line.buf);
2109 strbuf_release(&line);
2112 if (server_options.nr)
2113 gtransport->server_options = &server_options;
2115 sigchain_push_common(unlock_pack_on_signal);
2116 atexit(unlock_pack_atexit);
2117 sigchain_push(SIGPIPE, SIG_IGN);
2118 exit_code = do_fetch(gtransport, &rs);
2119 sigchain_pop(SIGPIPE);
2120 refspec_clear(&rs);
2121 transport_disconnect(gtransport);
2122 gtransport = NULL;
2123 return exit_code;
2126 int cmd_fetch(int argc, const char **argv, const char *prefix)
2128 int i;
2129 const char *bundle_uri;
2130 struct string_list list = STRING_LIST_INIT_DUP;
2131 struct remote *remote = NULL;
2132 int result = 0;
2133 int prune_tags_ok = 1;
2135 packet_trace_identity("fetch");
2137 /* Record the command line for the reflog */
2138 strbuf_addstr(&default_rla, "fetch");
2139 for (i = 1; i < argc; i++) {
2140 /* This handles non-URLs gracefully */
2141 char *anon = transport_anonymize_url(argv[i]);
2143 strbuf_addf(&default_rla, " %s", anon);
2144 free(anon);
2147 git_config(git_fetch_config, NULL);
2148 if (the_repository->gitdir) {
2149 prepare_repo_settings(the_repository);
2150 the_repository->settings.command_requires_full_index = 0;
2153 argc = parse_options(argc, argv, prefix,
2154 builtin_fetch_options, builtin_fetch_usage, 0);
2156 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2157 recurse_submodules = recurse_submodules_cli;
2159 if (negotiate_only) {
2160 switch (recurse_submodules_cli) {
2161 case RECURSE_SUBMODULES_OFF:
2162 case RECURSE_SUBMODULES_DEFAULT:
2164 * --negotiate-only should never recurse into
2165 * submodules. Skip it by setting recurse_submodules to
2166 * RECURSE_SUBMODULES_OFF.
2168 recurse_submodules = RECURSE_SUBMODULES_OFF;
2169 break;
2171 default:
2172 die(_("options '%s' and '%s' cannot be used together"),
2173 "--negotiate-only", "--recurse-submodules");
2177 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2178 int *sfjc = submodule_fetch_jobs_config == -1
2179 ? &submodule_fetch_jobs_config : NULL;
2180 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2181 ? &recurse_submodules : NULL;
2183 fetch_config_from_gitmodules(sfjc, rs);
2186 if (negotiate_only && !negotiation_tip.nr)
2187 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2189 if (deepen_relative) {
2190 if (deepen_relative < 0)
2191 die(_("negative depth in --deepen is not supported"));
2192 if (depth)
2193 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2194 depth = xstrfmt("%d", deepen_relative);
2196 if (unshallow) {
2197 if (depth)
2198 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2199 else if (!is_repository_shallow(the_repository))
2200 die(_("--unshallow on a complete repository does not make sense"));
2201 else
2202 depth = xstrfmt("%d", INFINITE_DEPTH);
2205 /* no need to be strict, transport_set_option() will validate it again */
2206 if (depth && atoi(depth) < 1)
2207 die(_("depth %s is not a positive number"), depth);
2208 if (depth || deepen_since || deepen_not.nr)
2209 deepen = 1;
2211 /* FETCH_HEAD never gets updated in --dry-run mode */
2212 if (dry_run)
2213 write_fetch_head = 0;
2215 if (!max_jobs)
2216 max_jobs = online_cpus();
2218 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2219 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2220 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2222 if (all) {
2223 if (argc == 1)
2224 die(_("fetch --all does not take a repository argument"));
2225 else if (argc > 1)
2226 die(_("fetch --all does not make sense with refspecs"));
2227 (void) for_each_remote(get_one_remote_for_fetch, &list);
2229 /* do not do fetch_multiple() of one */
2230 if (list.nr == 1)
2231 remote = remote_get(list.items[0].string);
2232 } else if (argc == 0) {
2233 /* No arguments -- use default remote */
2234 remote = remote_get(NULL);
2235 } else if (multiple) {
2236 /* All arguments are assumed to be remotes or groups */
2237 for (i = 0; i < argc; i++)
2238 if (!add_remote_or_group(argv[i], &list))
2239 die(_("no such remote or remote group: %s"),
2240 argv[i]);
2241 } else {
2242 /* Single remote or group */
2243 (void) add_remote_or_group(argv[0], &list);
2244 if (list.nr > 1) {
2245 /* More than one remote */
2246 if (argc > 1)
2247 die(_("fetching a group and specifying refspecs does not make sense"));
2248 } else {
2249 /* Zero or one remotes */
2250 remote = remote_get(argv[0]);
2251 prune_tags_ok = (argc == 1);
2252 argc--;
2253 argv++;
2256 string_list_remove_duplicates(&list, 0);
2258 if (negotiate_only) {
2259 struct oidset acked_commits = OIDSET_INIT;
2260 struct oidset_iter iter;
2261 const struct object_id *oid;
2263 if (!remote)
2264 die(_("must supply remote when using --negotiate-only"));
2265 gtransport = prepare_transport(remote, 1);
2266 if (gtransport->smart_options) {
2267 gtransport->smart_options->acked_commits = &acked_commits;
2268 } else {
2269 warning(_("protocol does not support --negotiate-only, exiting"));
2270 result = 1;
2271 goto cleanup;
2273 if (server_options.nr)
2274 gtransport->server_options = &server_options;
2275 result = transport_fetch_refs(gtransport, NULL);
2277 oidset_iter_init(&acked_commits, &iter);
2278 while ((oid = oidset_iter_next(&iter)))
2279 printf("%s\n", oid_to_hex(oid));
2280 oidset_clear(&acked_commits);
2281 } else if (remote) {
2282 if (filter_options.choice || repo_has_promisor_remote(the_repository))
2283 fetch_one_setup_partial(remote);
2284 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
2285 } else {
2286 int max_children = max_jobs;
2288 if (filter_options.choice)
2289 die(_("--filter can only be used with the remote "
2290 "configured in extensions.partialclone"));
2292 if (atomic_fetch)
2293 die(_("--atomic can only be used when fetching "
2294 "from one remote"));
2296 if (stdin_refspecs)
2297 die(_("--stdin can only be used when fetching "
2298 "from one remote"));
2300 if (max_children < 0)
2301 max_children = fetch_parallel_config;
2303 /* TODO should this also die if we have a previous partial-clone? */
2304 result = fetch_multiple(&list, max_children);
2309 * This is only needed after fetch_one(), which does not fetch
2310 * submodules by itself.
2312 * When we fetch from multiple remotes, fetch_multiple() has
2313 * already updated submodules to grab commits necessary for
2314 * the fetched history from each remote, so there is no need
2315 * to fetch submodules from here.
2317 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2318 struct strvec options = STRVEC_INIT;
2319 int max_children = max_jobs;
2321 if (max_children < 0)
2322 max_children = submodule_fetch_jobs_config;
2323 if (max_children < 0)
2324 max_children = fetch_parallel_config;
2326 add_options_to_argv(&options);
2327 result = fetch_submodules(the_repository,
2328 &options,
2329 submodule_prefix,
2330 recurse_submodules,
2331 recurse_submodules_default,
2332 verbosity < 0,
2333 max_children);
2334 strvec_clear(&options);
2338 * Skip irrelevant tasks because we know objects were not
2339 * fetched.
2341 * NEEDSWORK: as a future optimization, we can return early
2342 * whenever objects were not fetched e.g. if we already have all
2343 * of them.
2345 if (negotiate_only)
2346 goto cleanup;
2348 prepare_repo_settings(the_repository);
2349 if (fetch_write_commit_graph > 0 ||
2350 (fetch_write_commit_graph < 0 &&
2351 the_repository->settings.fetch_write_commit_graph)) {
2352 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2354 if (progress)
2355 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2357 write_commit_graph_reachable(the_repository->objects->odb,
2358 commit_graph_flags,
2359 NULL);
2362 if (enable_auto_gc) {
2363 if (refetch) {
2365 * Hint auto-maintenance strongly to encourage repacking,
2366 * but respect config settings disabling it.
2368 int opt_val;
2369 if (git_config_get_int("gc.autopacklimit", &opt_val))
2370 opt_val = -1;
2371 if (opt_val != 0)
2372 git_config_push_parameter("gc.autoPackLimit=1");
2374 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2375 opt_val = -1;
2376 if (opt_val != 0)
2377 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2379 run_auto_maintenance(verbosity < 0);
2382 cleanup:
2383 string_list_clear(&list, 0);
2384 return result;