Merge branch 'jc/maint-github-actions-update'
[git.git] / builtin / fetch.c
blob7378cafeec9fd6ea3edc521646ab7d8f66bcc02a
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "repository.h"
7 #include "refs.h"
8 #include "refspec.h"
9 #include "object-store.h"
10 #include "oidset.h"
11 #include "commit.h"
12 #include "builtin.h"
13 #include "string-list.h"
14 #include "remote.h"
15 #include "transport.h"
16 #include "run-command.h"
17 #include "parse-options.h"
18 #include "sigchain.h"
19 #include "submodule-config.h"
20 #include "submodule.h"
21 #include "connected.h"
22 #include "strvec.h"
23 #include "utf8.h"
24 #include "packfile.h"
25 #include "list-objects-filter-options.h"
26 #include "commit-reach.h"
27 #include "branch.h"
28 #include "promisor-remote.h"
29 #include "commit-graph.h"
30 #include "shallow.h"
31 #include "worktree.h"
33 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
35 static const char * const builtin_fetch_usage[] = {
36 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
37 N_("git fetch [<options>] <group>"),
38 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
39 N_("git fetch --all [<options>]"),
40 NULL
43 enum {
44 TAGS_UNSET = 0,
45 TAGS_DEFAULT = 1,
46 TAGS_SET = 2
49 static int fetch_prune_config = -1; /* unspecified */
50 static int fetch_show_forced_updates = 1;
51 static uint64_t forced_updates_ms = 0;
52 static int prefetch = 0;
53 static int prune = -1; /* unspecified */
54 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
56 static int fetch_prune_tags_config = -1; /* unspecified */
57 static int prune_tags = -1; /* unspecified */
58 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
60 static int all, append, dry_run, force, keep, multiple, update_head_ok;
61 static int write_fetch_head = 1;
62 static int verbosity, deepen_relative, set_upstream, refetch;
63 static int progress = -1;
64 static int enable_auto_gc = 1;
65 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
66 static int max_jobs = -1, submodule_fetch_jobs_config = -1;
67 static int fetch_parallel_config = 1;
68 static int atomic_fetch;
69 static enum transport_family family;
70 static const char *depth;
71 static const char *deepen_since;
72 static const char *upload_pack;
73 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
74 static struct strbuf default_rla = STRBUF_INIT;
75 static struct transport *gtransport;
76 static struct transport *gsecondary;
77 static const char *submodule_prefix = "";
78 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
79 static int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
80 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
81 static int shown_url = 0;
82 static struct refspec refmap = REFSPEC_INIT_FETCH;
83 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
84 static struct string_list server_options = STRING_LIST_INIT_DUP;
85 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
86 static int fetch_write_commit_graph = -1;
87 static int stdin_refspecs = 0;
88 static int negotiate_only;
90 static int git_fetch_config(const char *k, const char *v, void *cb)
92 if (!strcmp(k, "fetch.prune")) {
93 fetch_prune_config = git_config_bool(k, v);
94 return 0;
97 if (!strcmp(k, "fetch.prunetags")) {
98 fetch_prune_tags_config = git_config_bool(k, v);
99 return 0;
102 if (!strcmp(k, "fetch.showforcedupdates")) {
103 fetch_show_forced_updates = git_config_bool(k, v);
104 return 0;
107 if (!strcmp(k, "submodule.recurse")) {
108 int r = git_config_bool(k, v) ?
109 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
110 recurse_submodules = r;
113 if (!strcmp(k, "submodule.fetchjobs")) {
114 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
115 return 0;
116 } else if (!strcmp(k, "fetch.recursesubmodules")) {
117 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
118 return 0;
121 if (!strcmp(k, "fetch.parallel")) {
122 fetch_parallel_config = git_config_int(k, v);
123 if (fetch_parallel_config < 0)
124 die(_("fetch.parallel cannot be negative"));
125 if (!fetch_parallel_config)
126 fetch_parallel_config = online_cpus();
127 return 0;
130 return git_default_config(k, v, cb);
133 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
135 BUG_ON_OPT_NEG(unset);
138 * "git fetch --refmap='' origin foo"
139 * can be used to tell the command not to store anywhere
141 refspec_append(&refmap, arg);
143 return 0;
146 static struct option builtin_fetch_options[] = {
147 OPT__VERBOSITY(&verbosity),
148 OPT_BOOL(0, "all", &all,
149 N_("fetch from all remotes")),
150 OPT_BOOL(0, "set-upstream", &set_upstream,
151 N_("set upstream for git pull/fetch")),
152 OPT_BOOL('a', "append", &append,
153 N_("append to .git/FETCH_HEAD instead of overwriting")),
154 OPT_BOOL(0, "atomic", &atomic_fetch,
155 N_("use atomic transaction to update references")),
156 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
157 N_("path to upload pack on remote end")),
158 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
159 OPT_BOOL('m', "multiple", &multiple,
160 N_("fetch from multiple remotes")),
161 OPT_SET_INT('t', "tags", &tags,
162 N_("fetch all tags and associated objects"), TAGS_SET),
163 OPT_SET_INT('n', NULL, &tags,
164 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
165 OPT_INTEGER('j', "jobs", &max_jobs,
166 N_("number of submodules fetched in parallel")),
167 OPT_BOOL(0, "prefetch", &prefetch,
168 N_("modify the refspec to place all refs within refs/prefetch/")),
169 OPT_BOOL('p', "prune", &prune,
170 N_("prune remote-tracking branches no longer on remote")),
171 OPT_BOOL('P', "prune-tags", &prune_tags,
172 N_("prune local tags no longer on remote and clobber changed tags")),
173 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
174 N_("control recursive fetching of submodules"),
175 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
176 OPT_BOOL(0, "dry-run", &dry_run,
177 N_("dry run")),
178 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
179 N_("write fetched references to the FETCH_HEAD file")),
180 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
181 OPT_BOOL('u', "update-head-ok", &update_head_ok,
182 N_("allow updating of HEAD ref")),
183 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
184 OPT_STRING(0, "depth", &depth, N_("depth"),
185 N_("deepen history of shallow clone")),
186 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
187 N_("deepen history of shallow repository based on time")),
188 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
189 N_("deepen history of shallow clone, excluding rev")),
190 OPT_INTEGER(0, "deepen", &deepen_relative,
191 N_("deepen history of shallow clone")),
192 OPT_SET_INT_F(0, "unshallow", &unshallow,
193 N_("convert to a complete repository"),
194 1, PARSE_OPT_NONEG),
195 OPT_SET_INT_F(0, "refetch", &refetch,
196 N_("re-fetch without negotiating common commits"),
197 1, PARSE_OPT_NONEG),
198 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
199 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
200 OPT_CALLBACK_F(0, "recurse-submodules-default",
201 &recurse_submodules_default, N_("on-demand"),
202 N_("default for recursive fetching of submodules "
203 "(lower priority than config files)"),
204 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
205 OPT_BOOL(0, "update-shallow", &update_shallow,
206 N_("accept refs that update .git/shallow")),
207 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
208 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
209 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
210 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
211 TRANSPORT_FAMILY_IPV4),
212 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
213 TRANSPORT_FAMILY_IPV6),
214 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
215 N_("report that we have only objects reachable from this object")),
216 OPT_BOOL(0, "negotiate-only", &negotiate_only,
217 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
218 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
219 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
220 N_("run 'maintenance --auto' after fetching")),
221 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
222 N_("run 'maintenance --auto' after fetching")),
223 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
224 N_("check for forced-updates on all updated branches")),
225 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
226 N_("write the commit-graph after fetching")),
227 OPT_BOOL(0, "stdin", &stdin_refspecs,
228 N_("accept refspecs from stdin")),
229 OPT_END()
232 static void unlock_pack(unsigned int flags)
234 if (gtransport)
235 transport_unlock_pack(gtransport, flags);
236 if (gsecondary)
237 transport_unlock_pack(gsecondary, flags);
240 static void unlock_pack_atexit(void)
242 unlock_pack(0);
245 static void unlock_pack_on_signal(int signo)
247 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
248 sigchain_pop(signo);
249 raise(signo);
252 static void add_merge_config(struct ref **head,
253 const struct ref *remote_refs,
254 struct branch *branch,
255 struct ref ***tail)
257 int i;
259 for (i = 0; i < branch->merge_nr; i++) {
260 struct ref *rm, **old_tail = *tail;
261 struct refspec_item refspec;
263 for (rm = *head; rm; rm = rm->next) {
264 if (branch_merge_matches(branch, i, rm->name)) {
265 rm->fetch_head_status = FETCH_HEAD_MERGE;
266 break;
269 if (rm)
270 continue;
273 * Not fetched to a remote-tracking branch? We need to fetch
274 * it anyway to allow this branch's "branch.$name.merge"
275 * to be honored by 'git pull', but we do not have to
276 * fail if branch.$name.merge is misconfigured to point
277 * at a nonexisting branch. If we were indeed called by
278 * 'git pull', it will notice the misconfiguration because
279 * there is no entry in the resulting FETCH_HEAD marked
280 * for merging.
282 memset(&refspec, 0, sizeof(refspec));
283 refspec.src = branch->merge[i]->src;
284 get_fetch_map(remote_refs, &refspec, tail, 1);
285 for (rm = *old_tail; rm; rm = rm->next)
286 rm->fetch_head_status = FETCH_HEAD_MERGE;
290 static void create_fetch_oidset(struct ref **head, struct oidset *out)
292 struct ref *rm = *head;
293 while (rm) {
294 oidset_insert(out, &rm->old_oid);
295 rm = rm->next;
299 struct refname_hash_entry {
300 struct hashmap_entry ent;
301 struct object_id oid;
302 int ignore;
303 char refname[FLEX_ARRAY];
306 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
307 const struct hashmap_entry *eptr,
308 const struct hashmap_entry *entry_or_key,
309 const void *keydata)
311 const struct refname_hash_entry *e1, *e2;
313 e1 = container_of(eptr, const struct refname_hash_entry, ent);
314 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
315 return strcmp(e1->refname, keydata ? keydata : e2->refname);
318 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
319 const char *refname,
320 const struct object_id *oid)
322 struct refname_hash_entry *ent;
323 size_t len = strlen(refname);
325 FLEX_ALLOC_MEM(ent, refname, refname, len);
326 hashmap_entry_init(&ent->ent, strhash(refname));
327 oidcpy(&ent->oid, oid);
328 hashmap_add(map, &ent->ent);
329 return ent;
332 static int add_one_refname(const char *refname,
333 const struct object_id *oid,
334 int flag UNUSED, void *cbdata)
336 struct hashmap *refname_map = cbdata;
338 (void) refname_hash_add(refname_map, refname, oid);
339 return 0;
342 static void refname_hash_init(struct hashmap *map)
344 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
347 static int refname_hash_exists(struct hashmap *map, const char *refname)
349 return !!hashmap_get_from_hash(map, strhash(refname), refname);
352 static void clear_item(struct refname_hash_entry *item)
354 item->ignore = 1;
358 static void add_already_queued_tags(const char *refname,
359 const struct object_id *old_oid,
360 const struct object_id *new_oid,
361 void *cb_data)
363 struct hashmap *queued_tags = cb_data;
364 if (starts_with(refname, "refs/tags/") && new_oid)
365 (void) refname_hash_add(queued_tags, refname, new_oid);
368 static void find_non_local_tags(const struct ref *refs,
369 struct ref_transaction *transaction,
370 struct ref **head,
371 struct ref ***tail)
373 struct hashmap existing_refs;
374 struct hashmap remote_refs;
375 struct oidset fetch_oids = OIDSET_INIT;
376 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
377 struct string_list_item *remote_ref_item;
378 const struct ref *ref;
379 struct refname_hash_entry *item = NULL;
380 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
382 refname_hash_init(&existing_refs);
383 refname_hash_init(&remote_refs);
384 create_fetch_oidset(head, &fetch_oids);
386 for_each_ref(add_one_refname, &existing_refs);
389 * If we already have a transaction, then we need to filter out all
390 * tags which have already been queued up.
392 if (transaction)
393 ref_transaction_for_each_queued_update(transaction,
394 add_already_queued_tags,
395 &existing_refs);
397 for (ref = refs; ref; ref = ref->next) {
398 if (!starts_with(ref->name, "refs/tags/"))
399 continue;
402 * The peeled ref always follows the matching base
403 * ref, so if we see a peeled ref that we don't want
404 * to fetch then we can mark the ref entry in the list
405 * as one to ignore by setting util to NULL.
407 if (ends_with(ref->name, "^{}")) {
408 if (item &&
409 !has_object_file_with_flags(&ref->old_oid, quick_flags) &&
410 !oidset_contains(&fetch_oids, &ref->old_oid) &&
411 !has_object_file_with_flags(&item->oid, quick_flags) &&
412 !oidset_contains(&fetch_oids, &item->oid))
413 clear_item(item);
414 item = NULL;
415 continue;
419 * If item is non-NULL here, then we previously saw a
420 * ref not followed by a peeled reference, so we need
421 * to check if it is a lightweight tag that we want to
422 * fetch.
424 if (item &&
425 !has_object_file_with_flags(&item->oid, quick_flags) &&
426 !oidset_contains(&fetch_oids, &item->oid))
427 clear_item(item);
429 item = NULL;
431 /* skip duplicates and refs that we already have */
432 if (refname_hash_exists(&remote_refs, ref->name) ||
433 refname_hash_exists(&existing_refs, ref->name))
434 continue;
436 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
437 string_list_insert(&remote_refs_list, ref->name);
439 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
442 * We may have a final lightweight tag that needs to be
443 * checked to see if it needs fetching.
445 if (item &&
446 !has_object_file_with_flags(&item->oid, quick_flags) &&
447 !oidset_contains(&fetch_oids, &item->oid))
448 clear_item(item);
451 * For all the tags in the remote_refs_list,
452 * add them to the list of refs to be fetched
454 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
455 const char *refname = remote_ref_item->string;
456 struct ref *rm;
457 unsigned int hash = strhash(refname);
459 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
460 struct refname_hash_entry, ent);
461 if (!item)
462 BUG("unseen remote ref?");
464 /* Unless we have already decided to ignore this item... */
465 if (item->ignore)
466 continue;
468 rm = alloc_ref(item->refname);
469 rm->peer_ref = alloc_ref(item->refname);
470 oidcpy(&rm->old_oid, &item->oid);
471 **tail = rm;
472 *tail = &rm->next;
474 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
475 string_list_clear(&remote_refs_list, 0);
476 oidset_clear(&fetch_oids);
479 static void filter_prefetch_refspec(struct refspec *rs)
481 int i;
483 if (!prefetch)
484 return;
486 for (i = 0; i < rs->nr; i++) {
487 struct strbuf new_dst = STRBUF_INIT;
488 char *old_dst;
489 const char *sub = NULL;
491 if (rs->items[i].negative)
492 continue;
493 if (!rs->items[i].dst ||
494 (rs->items[i].src &&
495 !strncmp(rs->items[i].src,
496 ref_namespace[NAMESPACE_TAGS].ref,
497 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
498 int j;
500 free(rs->items[i].src);
501 free(rs->items[i].dst);
503 for (j = i + 1; j < rs->nr; j++) {
504 rs->items[j - 1] = rs->items[j];
505 rs->raw[j - 1] = rs->raw[j];
507 rs->nr--;
508 i--;
509 continue;
512 old_dst = rs->items[i].dst;
513 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
516 * If old_dst starts with "refs/", then place
517 * sub after that prefix. Otherwise, start at
518 * the beginning of the string.
520 if (!skip_prefix(old_dst, "refs/", &sub))
521 sub = old_dst;
522 strbuf_addstr(&new_dst, sub);
524 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
525 rs->items[i].force = 1;
527 free(old_dst);
531 static struct ref *get_ref_map(struct remote *remote,
532 const struct ref *remote_refs,
533 struct refspec *rs,
534 int tags, int *autotags)
536 int i;
537 struct ref *rm;
538 struct ref *ref_map = NULL;
539 struct ref **tail = &ref_map;
541 /* opportunistically-updated references: */
542 struct ref *orefs = NULL, **oref_tail = &orefs;
544 struct hashmap existing_refs;
545 int existing_refs_populated = 0;
547 filter_prefetch_refspec(rs);
548 if (remote)
549 filter_prefetch_refspec(&remote->fetch);
551 if (rs->nr) {
552 struct refspec *fetch_refspec;
554 for (i = 0; i < rs->nr; i++) {
555 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
556 if (rs->items[i].dst && rs->items[i].dst[0])
557 *autotags = 1;
559 /* Merge everything on the command line (but not --tags) */
560 for (rm = ref_map; rm; rm = rm->next)
561 rm->fetch_head_status = FETCH_HEAD_MERGE;
564 * For any refs that we happen to be fetching via
565 * command-line arguments, the destination ref might
566 * have been missing or have been different than the
567 * remote-tracking ref that would be derived from the
568 * configured refspec. In these cases, we want to
569 * take the opportunity to update their configured
570 * remote-tracking reference. However, we do not want
571 * to mention these entries in FETCH_HEAD at all, as
572 * they would simply be duplicates of existing
573 * entries, so we set them FETCH_HEAD_IGNORE below.
575 * We compute these entries now, based only on the
576 * refspecs specified on the command line. But we add
577 * them to the list following the refspecs resulting
578 * from the tags option so that one of the latter,
579 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
580 * by ref_remove_duplicates() in favor of one of these
581 * opportunistic entries with FETCH_HEAD_IGNORE.
583 if (refmap.nr)
584 fetch_refspec = &refmap;
585 else
586 fetch_refspec = &remote->fetch;
588 for (i = 0; i < fetch_refspec->nr; i++)
589 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
590 } else if (refmap.nr) {
591 die("--refmap option is only meaningful with command-line refspec(s)");
592 } else {
593 /* Use the defaults */
594 struct branch *branch = branch_get(NULL);
595 int has_merge = branch_has_merge_config(branch);
596 if (remote &&
597 (remote->fetch.nr ||
598 /* Note: has_merge implies non-NULL branch->remote_name */
599 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
600 for (i = 0; i < remote->fetch.nr; i++) {
601 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
602 if (remote->fetch.items[i].dst &&
603 remote->fetch.items[i].dst[0])
604 *autotags = 1;
605 if (!i && !has_merge && ref_map &&
606 !remote->fetch.items[0].pattern)
607 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
610 * if the remote we're fetching from is the same
611 * as given in branch.<name>.remote, we add the
612 * ref given in branch.<name>.merge, too.
614 * Note: has_merge implies non-NULL branch->remote_name
616 if (has_merge &&
617 !strcmp(branch->remote_name, remote->name))
618 add_merge_config(&ref_map, remote_refs, branch, &tail);
619 } else if (!prefetch) {
620 ref_map = get_remote_ref(remote_refs, "HEAD");
621 if (!ref_map)
622 die(_("couldn't find remote ref HEAD"));
623 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
624 tail = &ref_map->next;
628 if (tags == TAGS_SET)
629 /* also fetch all tags */
630 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
631 else if (tags == TAGS_DEFAULT && *autotags)
632 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
634 /* Now append any refs to be updated opportunistically: */
635 *tail = orefs;
636 for (rm = orefs; rm; rm = rm->next) {
637 rm->fetch_head_status = FETCH_HEAD_IGNORE;
638 tail = &rm->next;
642 * apply negative refspecs first, before we remove duplicates. This is
643 * necessary as negative refspecs might remove an otherwise conflicting
644 * duplicate.
646 if (rs->nr)
647 ref_map = apply_negative_refspecs(ref_map, rs);
648 else
649 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
651 ref_map = ref_remove_duplicates(ref_map);
653 for (rm = ref_map; rm; rm = rm->next) {
654 if (rm->peer_ref) {
655 const char *refname = rm->peer_ref->name;
656 struct refname_hash_entry *peer_item;
657 unsigned int hash = strhash(refname);
659 if (!existing_refs_populated) {
660 refname_hash_init(&existing_refs);
661 for_each_ref(add_one_refname, &existing_refs);
662 existing_refs_populated = 1;
665 peer_item = hashmap_get_entry_from_hash(&existing_refs,
666 hash, refname,
667 struct refname_hash_entry, ent);
668 if (peer_item) {
669 struct object_id *old_oid = &peer_item->oid;
670 oidcpy(&rm->peer_ref->old_oid, old_oid);
674 if (existing_refs_populated)
675 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
677 return ref_map;
680 #define STORE_REF_ERROR_OTHER 1
681 #define STORE_REF_ERROR_DF_CONFLICT 2
683 static int s_update_ref(const char *action,
684 struct ref *ref,
685 struct ref_transaction *transaction,
686 int check_old)
688 char *msg;
689 char *rla = getenv("GIT_REFLOG_ACTION");
690 struct ref_transaction *our_transaction = NULL;
691 struct strbuf err = STRBUF_INIT;
692 int ret;
694 if (dry_run)
695 return 0;
696 if (!rla)
697 rla = default_rla.buf;
698 msg = xstrfmt("%s: %s", rla, action);
701 * If no transaction was passed to us, we manage the transaction
702 * ourselves. Otherwise, we trust the caller to handle the transaction
703 * lifecycle.
705 if (!transaction) {
706 transaction = our_transaction = ref_transaction_begin(&err);
707 if (!transaction) {
708 ret = STORE_REF_ERROR_OTHER;
709 goto out;
713 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
714 check_old ? &ref->old_oid : NULL,
715 0, msg, &err);
716 if (ret) {
717 ret = STORE_REF_ERROR_OTHER;
718 goto out;
721 if (our_transaction) {
722 switch (ref_transaction_commit(our_transaction, &err)) {
723 case 0:
724 break;
725 case TRANSACTION_NAME_CONFLICT:
726 ret = STORE_REF_ERROR_DF_CONFLICT;
727 goto out;
728 default:
729 ret = STORE_REF_ERROR_OTHER;
730 goto out;
734 out:
735 ref_transaction_free(our_transaction);
736 if (ret)
737 error("%s", err.buf);
738 strbuf_release(&err);
739 free(msg);
740 return ret;
743 static int refcol_width = 10;
744 static int compact_format;
746 static void adjust_refcol_width(const struct ref *ref)
748 int max, rlen, llen, len;
750 /* uptodate lines are only shown on high verbosity level */
751 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
752 return;
754 max = term_columns();
755 rlen = utf8_strwidth(prettify_refname(ref->name));
757 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
760 * rough estimation to see if the output line is too long and
761 * should not be counted (we can't do precise calculation
762 * anyway because we don't know if the error explanation part
763 * will be printed in update_local_ref)
765 if (compact_format) {
766 llen = 0;
767 max = max * 2 / 3;
769 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
770 if (len >= max)
771 return;
774 * Not precise calculation for compact mode because '*' can
775 * appear on the left hand side of '->' and shrink the column
776 * back.
778 if (refcol_width < rlen)
779 refcol_width = rlen;
782 static void prepare_format_display(struct ref *ref_map)
784 struct ref *rm;
785 const char *format = "full";
787 if (verbosity < 0)
788 return;
790 git_config_get_string_tmp("fetch.output", &format);
791 if (!strcasecmp(format, "full"))
792 compact_format = 0;
793 else if (!strcasecmp(format, "compact"))
794 compact_format = 1;
795 else
796 die(_("invalid value for '%s': '%s'"),
797 "fetch.output", format);
799 for (rm = ref_map; rm; rm = rm->next) {
800 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
801 !rm->peer_ref ||
802 !strcmp(rm->name, "HEAD"))
803 continue;
805 adjust_refcol_width(rm);
809 static void print_remote_to_local(struct strbuf *display,
810 const char *remote, const char *local)
812 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
815 static int find_and_replace(struct strbuf *haystack,
816 const char *needle,
817 const char *placeholder)
819 const char *p = NULL;
820 int plen, nlen;
822 nlen = strlen(needle);
823 if (ends_with(haystack->buf, needle))
824 p = haystack->buf + haystack->len - nlen;
825 else
826 p = strstr(haystack->buf, needle);
827 if (!p)
828 return 0;
830 if (p > haystack->buf && p[-1] != '/')
831 return 0;
833 plen = strlen(p);
834 if (plen > nlen && p[nlen] != '/')
835 return 0;
837 strbuf_splice(haystack, p - haystack->buf, nlen,
838 placeholder, strlen(placeholder));
839 return 1;
842 static void print_compact(struct strbuf *display,
843 const char *remote, const char *local)
845 struct strbuf r = STRBUF_INIT;
846 struct strbuf l = STRBUF_INIT;
848 if (!strcmp(remote, local)) {
849 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
850 return;
853 strbuf_addstr(&r, remote);
854 strbuf_addstr(&l, local);
856 if (!find_and_replace(&r, local, "*"))
857 find_and_replace(&l, remote, "*");
858 print_remote_to_local(display, r.buf, l.buf);
860 strbuf_release(&r);
861 strbuf_release(&l);
864 static void format_display(struct strbuf *display, char code,
865 const char *summary, const char *error,
866 const char *remote, const char *local,
867 int summary_width)
869 int width;
871 if (verbosity < 0)
872 return;
874 width = (summary_width + strlen(summary) - gettext_width(summary));
876 strbuf_addf(display, "%c %-*s ", code, width, summary);
877 if (!compact_format)
878 print_remote_to_local(display, remote, local);
879 else
880 print_compact(display, remote, local);
881 if (error)
882 strbuf_addf(display, " (%s)", error);
885 static int update_local_ref(struct ref *ref,
886 struct ref_transaction *transaction,
887 const char *remote, const struct ref *remote_ref,
888 struct strbuf *display, int summary_width)
890 struct commit *current = NULL, *updated;
891 const char *pretty_ref = prettify_refname(ref->name);
892 int fast_forward = 0;
894 if (!repo_has_object_file(the_repository, &ref->new_oid))
895 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
897 if (oideq(&ref->old_oid, &ref->new_oid)) {
898 if (verbosity > 0)
899 format_display(display, '=', _("[up to date]"), NULL,
900 remote, pretty_ref, summary_width);
901 return 0;
904 if (!update_head_ok &&
905 !is_null_oid(&ref->old_oid) &&
906 branch_checked_out(ref->name)) {
908 * If this is the head, and it's not okay to update
909 * the head, and the old value of the head isn't empty...
911 format_display(display, '!', _("[rejected]"),
912 _("can't fetch into checked-out branch"),
913 remote, pretty_ref, summary_width);
914 return 1;
917 if (!is_null_oid(&ref->old_oid) &&
918 starts_with(ref->name, "refs/tags/")) {
919 if (force || ref->force) {
920 int r;
921 r = s_update_ref("updating tag", ref, transaction, 0);
922 format_display(display, r ? '!' : 't', _("[tag update]"),
923 r ? _("unable to update local ref") : NULL,
924 remote, pretty_ref, summary_width);
925 return r;
926 } else {
927 format_display(display, '!', _("[rejected]"), _("would clobber existing tag"),
928 remote, pretty_ref, summary_width);
929 return 1;
933 current = lookup_commit_reference_gently(the_repository,
934 &ref->old_oid, 1);
935 updated = lookup_commit_reference_gently(the_repository,
936 &ref->new_oid, 1);
937 if (!current || !updated) {
938 const char *msg;
939 const char *what;
940 int r;
942 * Nicely describe the new ref we're fetching.
943 * Base this on the remote's ref name, as it's
944 * more likely to follow a standard layout.
946 const char *name = remote_ref ? remote_ref->name : "";
947 if (starts_with(name, "refs/tags/")) {
948 msg = "storing tag";
949 what = _("[new tag]");
950 } else if (starts_with(name, "refs/heads/")) {
951 msg = "storing head";
952 what = _("[new branch]");
953 } else {
954 msg = "storing ref";
955 what = _("[new ref]");
958 r = s_update_ref(msg, ref, transaction, 0);
959 format_display(display, r ? '!' : '*', what,
960 r ? _("unable to update local ref") : NULL,
961 remote, pretty_ref, summary_width);
962 return r;
965 if (fetch_show_forced_updates) {
966 uint64_t t_before = getnanotime();
967 fast_forward = in_merge_bases(current, updated);
968 forced_updates_ms += (getnanotime() - t_before) / 1000000;
969 } else {
970 fast_forward = 1;
973 if (fast_forward) {
974 struct strbuf quickref = STRBUF_INIT;
975 int r;
977 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
978 strbuf_addstr(&quickref, "..");
979 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
980 r = s_update_ref("fast-forward", ref, transaction, 1);
981 format_display(display, r ? '!' : ' ', quickref.buf,
982 r ? _("unable to update local ref") : NULL,
983 remote, pretty_ref, summary_width);
984 strbuf_release(&quickref);
985 return r;
986 } else if (force || ref->force) {
987 struct strbuf quickref = STRBUF_INIT;
988 int r;
989 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
990 strbuf_addstr(&quickref, "...");
991 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
992 r = s_update_ref("forced-update", ref, transaction, 1);
993 format_display(display, r ? '!' : '+', quickref.buf,
994 r ? _("unable to update local ref") : _("forced update"),
995 remote, pretty_ref, summary_width);
996 strbuf_release(&quickref);
997 return r;
998 } else {
999 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
1000 remote, pretty_ref, summary_width);
1001 return 1;
1005 static const struct object_id *iterate_ref_map(void *cb_data)
1007 struct ref **rm = cb_data;
1008 struct ref *ref = *rm;
1010 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1011 ref = ref->next;
1012 if (!ref)
1013 return NULL;
1014 *rm = ref->next;
1015 return &ref->old_oid;
1018 struct fetch_head {
1019 FILE *fp;
1020 struct strbuf buf;
1023 static int open_fetch_head(struct fetch_head *fetch_head)
1025 const char *filename = git_path_fetch_head(the_repository);
1027 if (write_fetch_head) {
1028 fetch_head->fp = fopen(filename, "a");
1029 if (!fetch_head->fp)
1030 return error_errno(_("cannot open '%s'"), filename);
1031 strbuf_init(&fetch_head->buf, 0);
1032 } else {
1033 fetch_head->fp = NULL;
1036 return 0;
1039 static void append_fetch_head(struct fetch_head *fetch_head,
1040 const struct object_id *old_oid,
1041 enum fetch_head_status fetch_head_status,
1042 const char *note,
1043 const char *url, size_t url_len)
1045 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1046 const char *merge_status_marker;
1047 size_t i;
1049 if (!fetch_head->fp)
1050 return;
1052 switch (fetch_head_status) {
1053 case FETCH_HEAD_NOT_FOR_MERGE:
1054 merge_status_marker = "not-for-merge";
1055 break;
1056 case FETCH_HEAD_MERGE:
1057 merge_status_marker = "";
1058 break;
1059 default:
1060 /* do not write anything to FETCH_HEAD */
1061 return;
1064 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1065 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1066 for (i = 0; i < url_len; ++i)
1067 if ('\n' == url[i])
1068 strbuf_addstr(&fetch_head->buf, "\\n");
1069 else
1070 strbuf_addch(&fetch_head->buf, url[i]);
1071 strbuf_addch(&fetch_head->buf, '\n');
1074 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1075 * any of the reference updates fails. We thus have to write all
1076 * updates to a buffer first and only commit it as soon as all
1077 * references have been successfully updated.
1079 if (!atomic_fetch) {
1080 strbuf_write(&fetch_head->buf, fetch_head->fp);
1081 strbuf_reset(&fetch_head->buf);
1085 static void commit_fetch_head(struct fetch_head *fetch_head)
1087 if (!fetch_head->fp || !atomic_fetch)
1088 return;
1089 strbuf_write(&fetch_head->buf, fetch_head->fp);
1092 static void close_fetch_head(struct fetch_head *fetch_head)
1094 if (!fetch_head->fp)
1095 return;
1097 fclose(fetch_head->fp);
1098 strbuf_release(&fetch_head->buf);
1101 static const char warn_show_forced_updates[] =
1102 N_("fetch normally indicates which branches had a forced update,\n"
1103 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1104 "flag or run 'git config fetch.showForcedUpdates true'");
1105 static const char warn_time_show_forced_updates[] =
1106 N_("it took %.2f seconds to check forced updates; you can use\n"
1107 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1108 "to avoid this check\n");
1110 static int store_updated_refs(const char *raw_url, const char *remote_name,
1111 int connectivity_checked,
1112 struct ref_transaction *transaction, struct ref *ref_map,
1113 struct fetch_head *fetch_head)
1115 int url_len, i, rc = 0;
1116 struct strbuf note = STRBUF_INIT;
1117 const char *what, *kind;
1118 struct ref *rm;
1119 char *url;
1120 int want_status;
1121 int summary_width = 0;
1123 if (verbosity >= 0)
1124 summary_width = transport_summary_width(ref_map);
1126 if (raw_url)
1127 url = transport_anonymize_url(raw_url);
1128 else
1129 url = xstrdup("foreign");
1131 if (!connectivity_checked) {
1132 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1134 rm = ref_map;
1135 if (check_connected(iterate_ref_map, &rm, &opt)) {
1136 rc = error(_("%s did not send all necessary objects\n"), url);
1137 goto abort;
1141 prepare_format_display(ref_map);
1144 * We do a pass for each fetch_head_status type in their enum order, so
1145 * merged entries are written before not-for-merge. That lets readers
1146 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1148 for (want_status = FETCH_HEAD_MERGE;
1149 want_status <= FETCH_HEAD_IGNORE;
1150 want_status++) {
1151 for (rm = ref_map; rm; rm = rm->next) {
1152 struct ref *ref = NULL;
1154 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1155 if (want_status == FETCH_HEAD_MERGE)
1156 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1157 rm->peer_ref ? rm->peer_ref->name : rm->name);
1158 continue;
1162 * When writing FETCH_HEAD we need to determine whether
1163 * we already have the commit or not. If not, then the
1164 * reference is not for merge and needs to be written
1165 * to the reflog after other commits which we already
1166 * have. We're not interested in this property though
1167 * in case FETCH_HEAD is not to be updated, so we can
1168 * skip the classification in that case.
1170 if (fetch_head->fp) {
1171 struct commit *commit = NULL;
1174 * References in "refs/tags/" are often going to point
1175 * to annotated tags, which are not part of the
1176 * commit-graph. We thus only try to look up refs in
1177 * the graph which are not in that namespace to not
1178 * regress performance in repositories with many
1179 * annotated tags.
1181 if (!starts_with(rm->name, "refs/tags/"))
1182 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1183 if (!commit) {
1184 commit = lookup_commit_reference_gently(the_repository,
1185 &rm->old_oid,
1187 if (!commit)
1188 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1192 if (rm->fetch_head_status != want_status)
1193 continue;
1195 if (rm->peer_ref) {
1196 ref = alloc_ref(rm->peer_ref->name);
1197 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1198 oidcpy(&ref->new_oid, &rm->old_oid);
1199 ref->force = rm->peer_ref->force;
1202 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1203 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1204 check_for_new_submodule_commits(&rm->old_oid);
1207 if (!strcmp(rm->name, "HEAD")) {
1208 kind = "";
1209 what = "";
1211 else if (skip_prefix(rm->name, "refs/heads/", &what))
1212 kind = "branch";
1213 else if (skip_prefix(rm->name, "refs/tags/", &what))
1214 kind = "tag";
1215 else if (skip_prefix(rm->name, "refs/remotes/", &what))
1216 kind = "remote-tracking branch";
1217 else {
1218 kind = "";
1219 what = rm->name;
1222 url_len = strlen(url);
1223 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1225 url_len = i + 1;
1226 if (4 < i && !strncmp(".git", url + i - 3, 4))
1227 url_len = i - 3;
1229 strbuf_reset(&note);
1230 if (*what) {
1231 if (*kind)
1232 strbuf_addf(&note, "%s ", kind);
1233 strbuf_addf(&note, "'%s' of ", what);
1236 append_fetch_head(fetch_head, &rm->old_oid,
1237 rm->fetch_head_status,
1238 note.buf, url, url_len);
1240 strbuf_reset(&note);
1241 if (ref) {
1242 rc |= update_local_ref(ref, transaction, what,
1243 rm, &note, summary_width);
1244 free(ref);
1245 } else if (write_fetch_head || dry_run) {
1247 * Display fetches written to FETCH_HEAD (or
1248 * would be written to FETCH_HEAD, if --dry-run
1249 * is set).
1251 format_display(&note, '*',
1252 *kind ? kind : "branch", NULL,
1253 *what ? what : "HEAD",
1254 "FETCH_HEAD", summary_width);
1256 if (note.len) {
1257 if (!shown_url) {
1258 fprintf(stderr, _("From %.*s\n"),
1259 url_len, url);
1260 shown_url = 1;
1262 fprintf(stderr, " %s\n", note.buf);
1267 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1268 error(_("some local refs could not be updated; try running\n"
1269 " 'git remote prune %s' to remove any old, conflicting "
1270 "branches"), remote_name);
1272 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1273 if (!fetch_show_forced_updates) {
1274 warning(_(warn_show_forced_updates));
1275 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1276 warning(_(warn_time_show_forced_updates),
1277 forced_updates_ms / 1000.0);
1281 abort:
1282 strbuf_release(&note);
1283 free(url);
1284 return rc;
1288 * We would want to bypass the object transfer altogether if
1289 * everything we are going to fetch already exists and is connected
1290 * locally.
1292 static int check_exist_and_connected(struct ref *ref_map)
1294 struct ref *rm = ref_map;
1295 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1296 struct ref *r;
1299 * If we are deepening a shallow clone we already have these
1300 * objects reachable. Running rev-list here will return with
1301 * a good (0) exit status and we'll bypass the fetch that we
1302 * really need to perform. Claiming failure now will ensure
1303 * we perform the network exchange to deepen our history.
1305 if (deepen)
1306 return -1;
1309 * Similarly, if we need to refetch, we always want to perform a full
1310 * fetch ignoring existing objects.
1312 if (refetch)
1313 return -1;
1317 * check_connected() allows objects to merely be promised, but
1318 * we need all direct targets to exist.
1320 for (r = rm; r; r = r->next) {
1321 if (!has_object_file_with_flags(&r->old_oid,
1322 OBJECT_INFO_SKIP_FETCH_OBJECT))
1323 return -1;
1326 opt.quiet = 1;
1327 return check_connected(iterate_ref_map, &rm, &opt);
1330 static int fetch_and_consume_refs(struct transport *transport,
1331 struct ref_transaction *transaction,
1332 struct ref *ref_map,
1333 struct fetch_head *fetch_head)
1335 int connectivity_checked = 1;
1336 int ret;
1339 * We don't need to perform a fetch in case we can already satisfy all
1340 * refs.
1342 ret = check_exist_and_connected(ref_map);
1343 if (ret) {
1344 trace2_region_enter("fetch", "fetch_refs", the_repository);
1345 ret = transport_fetch_refs(transport, ref_map);
1346 trace2_region_leave("fetch", "fetch_refs", the_repository);
1347 if (ret)
1348 goto out;
1349 connectivity_checked = transport->smart_options ?
1350 transport->smart_options->connectivity_checked : 0;
1353 trace2_region_enter("fetch", "consume_refs", the_repository);
1354 ret = store_updated_refs(transport->url, transport->remote->name,
1355 connectivity_checked, transaction, ref_map,
1356 fetch_head);
1357 trace2_region_leave("fetch", "consume_refs", the_repository);
1359 out:
1360 transport_unlock_pack(transport, 0);
1361 return ret;
1364 static int prune_refs(struct refspec *rs,
1365 struct ref_transaction *transaction,
1366 struct ref *ref_map,
1367 const char *raw_url)
1369 int url_len, i, result = 0;
1370 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1371 struct strbuf err = STRBUF_INIT;
1372 char *url;
1373 const char *dangling_msg = dry_run
1374 ? _(" (%s will become dangling)")
1375 : _(" (%s has become dangling)");
1377 if (raw_url)
1378 url = transport_anonymize_url(raw_url);
1379 else
1380 url = xstrdup("foreign");
1382 url_len = strlen(url);
1383 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1386 url_len = i + 1;
1387 if (4 < i && !strncmp(".git", url + i - 3, 4))
1388 url_len = i - 3;
1390 if (!dry_run) {
1391 if (transaction) {
1392 for (ref = stale_refs; ref; ref = ref->next) {
1393 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1394 "fetch: prune", &err);
1395 if (result)
1396 goto cleanup;
1398 } else {
1399 struct string_list refnames = STRING_LIST_INIT_NODUP;
1401 for (ref = stale_refs; ref; ref = ref->next)
1402 string_list_append(&refnames, ref->name);
1404 result = delete_refs("fetch: prune", &refnames, 0);
1405 string_list_clear(&refnames, 0);
1409 if (verbosity >= 0) {
1410 int summary_width = transport_summary_width(stale_refs);
1412 for (ref = stale_refs; ref; ref = ref->next) {
1413 struct strbuf sb = STRBUF_INIT;
1414 if (!shown_url) {
1415 fprintf(stderr, _("From %.*s\n"), url_len, url);
1416 shown_url = 1;
1418 format_display(&sb, '-', _("[deleted]"), NULL,
1419 _("(none)"), prettify_refname(ref->name),
1420 summary_width);
1421 fprintf(stderr, " %s\n",sb.buf);
1422 strbuf_release(&sb);
1423 warn_dangling_symref(stderr, dangling_msg, ref->name);
1427 cleanup:
1428 strbuf_release(&err);
1429 free(url);
1430 free_refs(stale_refs);
1431 return result;
1434 static void check_not_current_branch(struct ref *ref_map)
1436 const char *path;
1437 for (; ref_map; ref_map = ref_map->next)
1438 if (ref_map->peer_ref &&
1439 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1440 (path = branch_checked_out(ref_map->peer_ref->name)))
1441 die(_("refusing to fetch into branch '%s' "
1442 "checked out at '%s'"),
1443 ref_map->peer_ref->name, path);
1446 static int truncate_fetch_head(void)
1448 const char *filename = git_path_fetch_head(the_repository);
1449 FILE *fp = fopen_for_writing(filename);
1451 if (!fp)
1452 return error_errno(_("cannot open '%s'"), filename);
1453 fclose(fp);
1454 return 0;
1457 static void set_option(struct transport *transport, const char *name, const char *value)
1459 int r = transport_set_option(transport, name, value);
1460 if (r < 0)
1461 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1462 name, value, transport->url);
1463 if (r > 0)
1464 warning(_("option \"%s\" is ignored for %s\n"),
1465 name, transport->url);
1469 static int add_oid(const char *refname UNUSED,
1470 const struct object_id *oid,
1471 int flags UNUSED, void *cb_data)
1473 struct oid_array *oids = cb_data;
1475 oid_array_append(oids, oid);
1476 return 0;
1479 static void add_negotiation_tips(struct git_transport_options *smart_options)
1481 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1482 int i;
1484 for (i = 0; i < negotiation_tip.nr; i++) {
1485 const char *s = negotiation_tip.items[i].string;
1486 int old_nr;
1487 if (!has_glob_specials(s)) {
1488 struct object_id oid;
1489 if (get_oid(s, &oid))
1490 die(_("%s is not a valid object"), s);
1491 if (!has_object(the_repository, &oid, 0))
1492 die(_("the object %s does not exist"), s);
1493 oid_array_append(oids, &oid);
1494 continue;
1496 old_nr = oids->nr;
1497 for_each_glob_ref(add_oid, s, oids);
1498 if (old_nr == oids->nr)
1499 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1502 smart_options->negotiation_tips = oids;
1505 static struct transport *prepare_transport(struct remote *remote, int deepen)
1507 struct transport *transport;
1509 transport = transport_get(remote, NULL);
1510 transport_set_verbosity(transport, verbosity, progress);
1511 transport->family = family;
1512 if (upload_pack)
1513 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1514 if (keep)
1515 set_option(transport, TRANS_OPT_KEEP, "yes");
1516 if (depth)
1517 set_option(transport, TRANS_OPT_DEPTH, depth);
1518 if (deepen && deepen_since)
1519 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1520 if (deepen && deepen_not.nr)
1521 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1522 (const char *)&deepen_not);
1523 if (deepen_relative)
1524 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1525 if (update_shallow)
1526 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1527 if (refetch)
1528 set_option(transport, TRANS_OPT_REFETCH, "yes");
1529 if (filter_options.choice) {
1530 const char *spec =
1531 expand_list_objects_filter_spec(&filter_options);
1532 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1533 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1535 if (negotiation_tip.nr) {
1536 if (transport->smart_options)
1537 add_negotiation_tips(transport->smart_options);
1538 else
1539 warning("ignoring --negotiation-tip because the protocol does not support it");
1541 return transport;
1544 static int backfill_tags(struct transport *transport,
1545 struct ref_transaction *transaction,
1546 struct ref *ref_map,
1547 struct fetch_head *fetch_head)
1549 int retcode, cannot_reuse;
1552 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1553 * when remote helper is used (setting it to an empty string
1554 * is not unsetting). We could extend the remote helper
1555 * protocol for that, but for now, just force a new connection
1556 * without deepen-since. Similar story for deepen-not.
1558 cannot_reuse = transport->cannot_reuse ||
1559 deepen_since || deepen_not.nr;
1560 if (cannot_reuse) {
1561 gsecondary = prepare_transport(transport->remote, 0);
1562 transport = gsecondary;
1565 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1566 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1567 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1568 retcode = fetch_and_consume_refs(transport, transaction, ref_map, fetch_head);
1570 if (gsecondary) {
1571 transport_disconnect(gsecondary);
1572 gsecondary = NULL;
1575 return retcode;
1578 static int do_fetch(struct transport *transport,
1579 struct refspec *rs)
1581 struct ref_transaction *transaction = NULL;
1582 struct ref *ref_map = NULL;
1583 int autotags = (transport->remote->fetch_tags == 1);
1584 int retcode = 0;
1585 const struct ref *remote_refs;
1586 struct transport_ls_refs_options transport_ls_refs_options =
1587 TRANSPORT_LS_REFS_OPTIONS_INIT;
1588 int must_list_refs = 1;
1589 struct fetch_head fetch_head = { 0 };
1590 struct strbuf err = STRBUF_INIT;
1592 if (tags == TAGS_DEFAULT) {
1593 if (transport->remote->fetch_tags == 2)
1594 tags = TAGS_SET;
1595 if (transport->remote->fetch_tags == -1)
1596 tags = TAGS_UNSET;
1599 /* if not appending, truncate FETCH_HEAD */
1600 if (!append && write_fetch_head) {
1601 retcode = truncate_fetch_head();
1602 if (retcode)
1603 goto cleanup;
1606 if (rs->nr) {
1607 int i;
1609 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1612 * We can avoid listing refs if all of them are exact
1613 * OIDs
1615 must_list_refs = 0;
1616 for (i = 0; i < rs->nr; i++) {
1617 if (!rs->items[i].exact_sha1) {
1618 must_list_refs = 1;
1619 break;
1622 } else {
1623 struct branch *branch = branch_get(NULL);
1625 if (transport->remote->fetch.nr)
1626 refspec_ref_prefixes(&transport->remote->fetch,
1627 &transport_ls_refs_options.ref_prefixes);
1628 if (branch_has_merge_config(branch) &&
1629 !strcmp(branch->remote_name, transport->remote->name)) {
1630 int i;
1631 for (i = 0; i < branch->merge_nr; i++) {
1632 strvec_push(&transport_ls_refs_options.ref_prefixes,
1633 branch->merge[i]->src);
1638 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1639 must_list_refs = 1;
1640 if (transport_ls_refs_options.ref_prefixes.nr)
1641 strvec_push(&transport_ls_refs_options.ref_prefixes,
1642 "refs/tags/");
1645 if (must_list_refs) {
1646 trace2_region_enter("fetch", "remote_refs", the_repository);
1647 remote_refs = transport_get_remote_refs(transport,
1648 &transport_ls_refs_options);
1649 trace2_region_leave("fetch", "remote_refs", the_repository);
1650 } else
1651 remote_refs = NULL;
1653 transport_ls_refs_options_release(&transport_ls_refs_options);
1655 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1656 tags, &autotags);
1657 if (!update_head_ok)
1658 check_not_current_branch(ref_map);
1660 retcode = open_fetch_head(&fetch_head);
1661 if (retcode)
1662 goto cleanup;
1664 if (atomic_fetch) {
1665 transaction = ref_transaction_begin(&err);
1666 if (!transaction) {
1667 retcode = error("%s", err.buf);
1668 goto cleanup;
1672 if (tags == TAGS_DEFAULT && autotags)
1673 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1674 if (prune) {
1676 * We only prune based on refspecs specified
1677 * explicitly (via command line or configuration); we
1678 * don't care whether --tags was specified.
1680 if (rs->nr) {
1681 retcode = prune_refs(rs, transaction, ref_map, transport->url);
1682 } else {
1683 retcode = prune_refs(&transport->remote->fetch,
1684 transaction, ref_map,
1685 transport->url);
1687 if (retcode != 0)
1688 retcode = 1;
1691 if (fetch_and_consume_refs(transport, transaction, ref_map, &fetch_head)) {
1692 retcode = 1;
1693 goto cleanup;
1697 * If neither --no-tags nor --tags was specified, do automated tag
1698 * following.
1700 if (tags == TAGS_DEFAULT && autotags) {
1701 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1703 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1704 if (tags_ref_map) {
1706 * If backfilling of tags fails then we want to tell
1707 * the user so, but we have to continue regardless to
1708 * populate upstream information of the references we
1709 * have already fetched above. The exception though is
1710 * when `--atomic` is passed: in that case we'll abort
1711 * the transaction and don't commit anything.
1713 if (backfill_tags(transport, transaction, tags_ref_map,
1714 &fetch_head))
1715 retcode = 1;
1718 free_refs(tags_ref_map);
1721 if (transaction) {
1722 if (retcode)
1723 goto cleanup;
1725 retcode = ref_transaction_commit(transaction, &err);
1726 if (retcode) {
1727 error("%s", err.buf);
1728 ref_transaction_free(transaction);
1729 transaction = NULL;
1730 goto cleanup;
1734 commit_fetch_head(&fetch_head);
1736 if (set_upstream) {
1737 struct branch *branch = branch_get("HEAD");
1738 struct ref *rm;
1739 struct ref *source_ref = NULL;
1742 * We're setting the upstream configuration for the
1743 * current branch. The relevant upstream is the
1744 * fetched branch that is meant to be merged with the
1745 * current one, i.e. the one fetched to FETCH_HEAD.
1747 * When there are several such branches, consider the
1748 * request ambiguous and err on the safe side by doing
1749 * nothing and just emit a warning.
1751 for (rm = ref_map; rm; rm = rm->next) {
1752 if (!rm->peer_ref) {
1753 if (source_ref) {
1754 warning(_("multiple branches detected, incompatible with --set-upstream"));
1755 goto cleanup;
1756 } else {
1757 source_ref = rm;
1761 if (source_ref) {
1762 if (!branch) {
1763 const char *shortname = source_ref->name;
1764 skip_prefix(shortname, "refs/heads/", &shortname);
1766 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1767 "it does not point to any branch."),
1768 shortname, transport->remote->name);
1769 goto cleanup;
1772 if (!strcmp(source_ref->name, "HEAD") ||
1773 starts_with(source_ref->name, "refs/heads/"))
1774 install_branch_config(0,
1775 branch->name,
1776 transport->remote->name,
1777 source_ref->name);
1778 else if (starts_with(source_ref->name, "refs/remotes/"))
1779 warning(_("not setting upstream for a remote remote-tracking branch"));
1780 else if (starts_with(source_ref->name, "refs/tags/"))
1781 warning(_("not setting upstream for a remote tag"));
1782 else
1783 warning(_("unknown branch type"));
1784 } else {
1785 warning(_("no source branch found;\n"
1786 "you need to specify exactly one branch with the --set-upstream option"));
1790 cleanup:
1791 if (retcode && transaction) {
1792 ref_transaction_abort(transaction, &err);
1793 error("%s", err.buf);
1796 close_fetch_head(&fetch_head);
1797 strbuf_release(&err);
1798 free_refs(ref_map);
1799 return retcode;
1802 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1804 struct string_list *list = priv;
1805 if (!remote->skip_default_update)
1806 string_list_append(list, remote->name);
1807 return 0;
1810 struct remote_group_data {
1811 const char *name;
1812 struct string_list *list;
1815 static int get_remote_group(const char *key, const char *value, void *priv)
1817 struct remote_group_data *g = priv;
1819 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1820 /* split list by white space */
1821 while (*value) {
1822 size_t wordlen = strcspn(value, " \t\n");
1824 if (wordlen >= 1)
1825 string_list_append_nodup(g->list,
1826 xstrndup(value, wordlen));
1827 value += wordlen + (value[wordlen] != '\0');
1831 return 0;
1834 static int add_remote_or_group(const char *name, struct string_list *list)
1836 int prev_nr = list->nr;
1837 struct remote_group_data g;
1838 g.name = name; g.list = list;
1840 git_config(get_remote_group, &g);
1841 if (list->nr == prev_nr) {
1842 struct remote *remote = remote_get(name);
1843 if (!remote_is_configured(remote, 0))
1844 return 0;
1845 string_list_append(list, remote->name);
1847 return 1;
1850 static void add_options_to_argv(struct strvec *argv)
1852 if (dry_run)
1853 strvec_push(argv, "--dry-run");
1854 if (prune != -1)
1855 strvec_push(argv, prune ? "--prune" : "--no-prune");
1856 if (prune_tags != -1)
1857 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1858 if (update_head_ok)
1859 strvec_push(argv, "--update-head-ok");
1860 if (force)
1861 strvec_push(argv, "--force");
1862 if (keep)
1863 strvec_push(argv, "--keep");
1864 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1865 strvec_push(argv, "--recurse-submodules");
1866 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1867 strvec_push(argv, "--recurse-submodules=on-demand");
1868 if (tags == TAGS_SET)
1869 strvec_push(argv, "--tags");
1870 else if (tags == TAGS_UNSET)
1871 strvec_push(argv, "--no-tags");
1872 if (verbosity >= 2)
1873 strvec_push(argv, "-v");
1874 if (verbosity >= 1)
1875 strvec_push(argv, "-v");
1876 else if (verbosity < 0)
1877 strvec_push(argv, "-q");
1878 if (family == TRANSPORT_FAMILY_IPV4)
1879 strvec_push(argv, "--ipv4");
1880 else if (family == TRANSPORT_FAMILY_IPV6)
1881 strvec_push(argv, "--ipv6");
1884 /* Fetch multiple remotes in parallel */
1886 struct parallel_fetch_state {
1887 const char **argv;
1888 struct string_list *remotes;
1889 int next, result;
1892 static int fetch_next_remote(struct child_process *cp, struct strbuf *out,
1893 void *cb, void **task_cb)
1895 struct parallel_fetch_state *state = cb;
1896 char *remote;
1898 if (state->next < 0 || state->next >= state->remotes->nr)
1899 return 0;
1901 remote = state->remotes->items[state->next++].string;
1902 *task_cb = remote;
1904 strvec_pushv(&cp->args, state->argv);
1905 strvec_push(&cp->args, remote);
1906 cp->git_cmd = 1;
1908 if (verbosity >= 0)
1909 printf(_("Fetching %s\n"), remote);
1911 return 1;
1914 static int fetch_failed_to_start(struct strbuf *out, void *cb, void *task_cb)
1916 struct parallel_fetch_state *state = cb;
1917 const char *remote = task_cb;
1919 state->result = error(_("could not fetch %s"), remote);
1921 return 0;
1924 static int fetch_finished(int result, struct strbuf *out,
1925 void *cb, void *task_cb)
1927 struct parallel_fetch_state *state = cb;
1928 const char *remote = task_cb;
1930 if (result) {
1931 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1932 remote, result);
1933 state->result = -1;
1936 return 0;
1939 static int fetch_multiple(struct string_list *list, int max_children)
1941 int i, result = 0;
1942 struct strvec argv = STRVEC_INIT;
1944 if (!append && write_fetch_head) {
1945 int errcode = truncate_fetch_head();
1946 if (errcode)
1947 return errcode;
1950 strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
1951 "--no-write-commit-graph", NULL);
1952 add_options_to_argv(&argv);
1954 if (max_children != 1 && list->nr != 1) {
1955 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1956 const struct run_process_parallel_opts opts = {
1957 .tr2_category = "fetch",
1958 .tr2_label = "parallel/fetch",
1960 .processes = max_children,
1962 .get_next_task = &fetch_next_remote,
1963 .start_failure = &fetch_failed_to_start,
1964 .task_finished = &fetch_finished,
1965 .data = &state,
1968 strvec_push(&argv, "--end-of-options");
1970 run_processes_parallel(&opts);
1971 result = state.result;
1972 } else
1973 for (i = 0; i < list->nr; i++) {
1974 const char *name = list->items[i].string;
1975 struct child_process cmd = CHILD_PROCESS_INIT;
1977 strvec_pushv(&cmd.args, argv.v);
1978 strvec_push(&cmd.args, name);
1979 if (verbosity >= 0)
1980 printf(_("Fetching %s\n"), name);
1981 cmd.git_cmd = 1;
1982 if (run_command(&cmd)) {
1983 error(_("could not fetch %s"), name);
1984 result = 1;
1988 strvec_clear(&argv);
1989 return !!result;
1993 * Fetching from the promisor remote should use the given filter-spec
1994 * or inherit the default filter-spec from the config.
1996 static inline void fetch_one_setup_partial(struct remote *remote)
1999 * Explicit --no-filter argument overrides everything, regardless
2000 * of any prior partial clones and fetches.
2002 if (filter_options.no_filter)
2003 return;
2006 * If no prior partial clone/fetch and the current fetch DID NOT
2007 * request a partial-fetch, do a normal fetch.
2009 if (!has_promisor_remote() && !filter_options.choice)
2010 return;
2013 * If this is a partial-fetch request, we enable partial on
2014 * this repo if not already enabled and remember the given
2015 * filter-spec as the default for subsequent fetches to this
2016 * remote if there is currently no default filter-spec.
2018 if (filter_options.choice) {
2019 partial_clone_register(remote->name, &filter_options);
2020 return;
2024 * Do a partial-fetch from the promisor remote using either the
2025 * explicitly given filter-spec or inherit the filter-spec from
2026 * the config.
2028 if (!filter_options.choice)
2029 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2030 return;
2033 static int fetch_one(struct remote *remote, int argc, const char **argv,
2034 int prune_tags_ok, int use_stdin_refspecs)
2036 struct refspec rs = REFSPEC_INIT_FETCH;
2037 int i;
2038 int exit_code;
2039 int maybe_prune_tags;
2040 int remote_via_config = remote_is_configured(remote, 0);
2042 if (!remote)
2043 die(_("no remote repository specified; please specify either a URL or a\n"
2044 "remote name from which new revisions should be fetched"));
2046 gtransport = prepare_transport(remote, 1);
2048 if (prune < 0) {
2049 /* no command line request */
2050 if (0 <= remote->prune)
2051 prune = remote->prune;
2052 else if (0 <= fetch_prune_config)
2053 prune = fetch_prune_config;
2054 else
2055 prune = PRUNE_BY_DEFAULT;
2058 if (prune_tags < 0) {
2059 /* no command line request */
2060 if (0 <= remote->prune_tags)
2061 prune_tags = remote->prune_tags;
2062 else if (0 <= fetch_prune_tags_config)
2063 prune_tags = fetch_prune_tags_config;
2064 else
2065 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2068 maybe_prune_tags = prune_tags_ok && prune_tags;
2069 if (maybe_prune_tags && remote_via_config)
2070 refspec_append(&remote->fetch, TAG_REFSPEC);
2072 if (maybe_prune_tags && (argc || !remote_via_config))
2073 refspec_append(&rs, TAG_REFSPEC);
2075 for (i = 0; i < argc; i++) {
2076 if (!strcmp(argv[i], "tag")) {
2077 i++;
2078 if (i >= argc)
2079 die(_("you need to specify a tag name"));
2081 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2082 argv[i], argv[i]);
2083 } else {
2084 refspec_append(&rs, argv[i]);
2088 if (use_stdin_refspecs) {
2089 struct strbuf line = STRBUF_INIT;
2090 while (strbuf_getline_lf(&line, stdin) != EOF)
2091 refspec_append(&rs, line.buf);
2092 strbuf_release(&line);
2095 if (server_options.nr)
2096 gtransport->server_options = &server_options;
2098 sigchain_push_common(unlock_pack_on_signal);
2099 atexit(unlock_pack_atexit);
2100 sigchain_push(SIGPIPE, SIG_IGN);
2101 exit_code = do_fetch(gtransport, &rs);
2102 sigchain_pop(SIGPIPE);
2103 refspec_clear(&rs);
2104 transport_disconnect(gtransport);
2105 gtransport = NULL;
2106 return exit_code;
2109 int cmd_fetch(int argc, const char **argv, const char *prefix)
2111 int i;
2112 struct string_list list = STRING_LIST_INIT_DUP;
2113 struct remote *remote = NULL;
2114 int result = 0;
2115 int prune_tags_ok = 1;
2117 packet_trace_identity("fetch");
2119 /* Record the command line for the reflog */
2120 strbuf_addstr(&default_rla, "fetch");
2121 for (i = 1; i < argc; i++) {
2122 /* This handles non-URLs gracefully */
2123 char *anon = transport_anonymize_url(argv[i]);
2125 strbuf_addf(&default_rla, " %s", anon);
2126 free(anon);
2129 git_config(git_fetch_config, NULL);
2130 if (the_repository->gitdir) {
2131 prepare_repo_settings(the_repository);
2132 the_repository->settings.command_requires_full_index = 0;
2135 argc = parse_options(argc, argv, prefix,
2136 builtin_fetch_options, builtin_fetch_usage, 0);
2138 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2139 recurse_submodules = recurse_submodules_cli;
2141 if (negotiate_only) {
2142 switch (recurse_submodules_cli) {
2143 case RECURSE_SUBMODULES_OFF:
2144 case RECURSE_SUBMODULES_DEFAULT:
2146 * --negotiate-only should never recurse into
2147 * submodules. Skip it by setting recurse_submodules to
2148 * RECURSE_SUBMODULES_OFF.
2150 recurse_submodules = RECURSE_SUBMODULES_OFF;
2151 break;
2153 default:
2154 die(_("options '%s' and '%s' cannot be used together"),
2155 "--negotiate-only", "--recurse-submodules");
2159 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2160 int *sfjc = submodule_fetch_jobs_config == -1
2161 ? &submodule_fetch_jobs_config : NULL;
2162 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2163 ? &recurse_submodules : NULL;
2165 fetch_config_from_gitmodules(sfjc, rs);
2168 if (negotiate_only && !negotiation_tip.nr)
2169 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2171 if (deepen_relative) {
2172 if (deepen_relative < 0)
2173 die(_("negative depth in --deepen is not supported"));
2174 if (depth)
2175 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2176 depth = xstrfmt("%d", deepen_relative);
2178 if (unshallow) {
2179 if (depth)
2180 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2181 else if (!is_repository_shallow(the_repository))
2182 die(_("--unshallow on a complete repository does not make sense"));
2183 else
2184 depth = xstrfmt("%d", INFINITE_DEPTH);
2187 /* no need to be strict, transport_set_option() will validate it again */
2188 if (depth && atoi(depth) < 1)
2189 die(_("depth %s is not a positive number"), depth);
2190 if (depth || deepen_since || deepen_not.nr)
2191 deepen = 1;
2193 /* FETCH_HEAD never gets updated in --dry-run mode */
2194 if (dry_run)
2195 write_fetch_head = 0;
2197 if (all) {
2198 if (argc == 1)
2199 die(_("fetch --all does not take a repository argument"));
2200 else if (argc > 1)
2201 die(_("fetch --all does not make sense with refspecs"));
2202 (void) for_each_remote(get_one_remote_for_fetch, &list);
2204 /* do not do fetch_multiple() of one */
2205 if (list.nr == 1)
2206 remote = remote_get(list.items[0].string);
2207 } else if (argc == 0) {
2208 /* No arguments -- use default remote */
2209 remote = remote_get(NULL);
2210 } else if (multiple) {
2211 /* All arguments are assumed to be remotes or groups */
2212 for (i = 0; i < argc; i++)
2213 if (!add_remote_or_group(argv[i], &list))
2214 die(_("no such remote or remote group: %s"),
2215 argv[i]);
2216 } else {
2217 /* Single remote or group */
2218 (void) add_remote_or_group(argv[0], &list);
2219 if (list.nr > 1) {
2220 /* More than one remote */
2221 if (argc > 1)
2222 die(_("fetching a group and specifying refspecs does not make sense"));
2223 } else {
2224 /* Zero or one remotes */
2225 remote = remote_get(argv[0]);
2226 prune_tags_ok = (argc == 1);
2227 argc--;
2228 argv++;
2232 if (negotiate_only) {
2233 struct oidset acked_commits = OIDSET_INIT;
2234 struct oidset_iter iter;
2235 const struct object_id *oid;
2237 if (!remote)
2238 die(_("must supply remote when using --negotiate-only"));
2239 gtransport = prepare_transport(remote, 1);
2240 if (gtransport->smart_options) {
2241 gtransport->smart_options->acked_commits = &acked_commits;
2242 } else {
2243 warning(_("protocol does not support --negotiate-only, exiting"));
2244 result = 1;
2245 goto cleanup;
2247 if (server_options.nr)
2248 gtransport->server_options = &server_options;
2249 result = transport_fetch_refs(gtransport, NULL);
2251 oidset_iter_init(&acked_commits, &iter);
2252 while ((oid = oidset_iter_next(&iter)))
2253 printf("%s\n", oid_to_hex(oid));
2254 oidset_clear(&acked_commits);
2255 } else if (remote) {
2256 if (filter_options.choice || has_promisor_remote())
2257 fetch_one_setup_partial(remote);
2258 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
2259 } else {
2260 int max_children = max_jobs;
2262 if (filter_options.choice)
2263 die(_("--filter can only be used with the remote "
2264 "configured in extensions.partialclone"));
2266 if (atomic_fetch)
2267 die(_("--atomic can only be used when fetching "
2268 "from one remote"));
2270 if (stdin_refspecs)
2271 die(_("--stdin can only be used when fetching "
2272 "from one remote"));
2274 if (max_children < 0)
2275 max_children = fetch_parallel_config;
2277 /* TODO should this also die if we have a previous partial-clone? */
2278 result = fetch_multiple(&list, max_children);
2283 * This is only needed after fetch_one(), which does not fetch
2284 * submodules by itself.
2286 * When we fetch from multiple remotes, fetch_multiple() has
2287 * already updated submodules to grab commits necessary for
2288 * the fetched history from each remote, so there is no need
2289 * to fetch submodules from here.
2291 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2292 struct strvec options = STRVEC_INIT;
2293 int max_children = max_jobs;
2295 if (max_children < 0)
2296 max_children = submodule_fetch_jobs_config;
2297 if (max_children < 0)
2298 max_children = fetch_parallel_config;
2300 add_options_to_argv(&options);
2301 result = fetch_submodules(the_repository,
2302 &options,
2303 submodule_prefix,
2304 recurse_submodules,
2305 recurse_submodules_default,
2306 verbosity < 0,
2307 max_children);
2308 strvec_clear(&options);
2312 * Skip irrelevant tasks because we know objects were not
2313 * fetched.
2315 * NEEDSWORK: as a future optimization, we can return early
2316 * whenever objects were not fetched e.g. if we already have all
2317 * of them.
2319 if (negotiate_only)
2320 goto cleanup;
2322 prepare_repo_settings(the_repository);
2323 if (fetch_write_commit_graph > 0 ||
2324 (fetch_write_commit_graph < 0 &&
2325 the_repository->settings.fetch_write_commit_graph)) {
2326 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2328 if (progress)
2329 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2331 write_commit_graph_reachable(the_repository->objects->odb,
2332 commit_graph_flags,
2333 NULL);
2336 if (enable_auto_gc) {
2337 if (refetch) {
2339 * Hint auto-maintenance strongly to encourage repacking,
2340 * but respect config settings disabling it.
2342 int opt_val;
2343 if (git_config_get_int("gc.autopacklimit", &opt_val))
2344 opt_val = -1;
2345 if (opt_val != 0)
2346 git_config_push_parameter("gc.autoPackLimit=1");
2348 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2349 opt_val = -1;
2350 if (opt_val != 0)
2351 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2353 run_auto_maintenance(verbosity < 0);
2356 cleanup:
2357 string_list_clear(&list, 0);
2358 return result;