fetch: move option related variables into main function
[alt-git.git] / builtin / fetch.c
blobe3629a7b646ad44c19745d196800f8193f94cfe9
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "gettext.h"
7 #include "environment.h"
8 #include "hex.h"
9 #include "repository.h"
10 #include "refs.h"
11 #include "refspec.h"
12 #include "object-store.h"
13 #include "oidset.h"
14 #include "commit.h"
15 #include "builtin.h"
16 #include "string-list.h"
17 #include "remote.h"
18 #include "transport.h"
19 #include "run-command.h"
20 #include "parse-options.h"
21 #include "sigchain.h"
22 #include "submodule-config.h"
23 #include "submodule.h"
24 #include "connected.h"
25 #include "strvec.h"
26 #include "utf8.h"
27 #include "packfile.h"
28 #include "list-objects-filter-options.h"
29 #include "commit-reach.h"
30 #include "branch.h"
31 #include "promisor-remote.h"
32 #include "commit-graph.h"
33 #include "shallow.h"
34 #include "worktree.h"
35 #include "bundle-uri.h"
37 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
39 static const char * const builtin_fetch_usage[] = {
40 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
41 N_("git fetch [<options>] <group>"),
42 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
43 N_("git fetch --all [<options>]"),
44 NULL
47 enum {
48 TAGS_UNSET = 0,
49 TAGS_DEFAULT = 1,
50 TAGS_SET = 2
53 enum display_format {
54 DISPLAY_FORMAT_UNKNOWN = 0,
55 DISPLAY_FORMAT_FULL,
56 DISPLAY_FORMAT_COMPACT,
59 struct display_state {
60 struct strbuf buf;
62 int refcol_width;
63 enum display_format format;
65 char *url;
66 int url_len, shown_url;
69 static int fetch_prune_config = -1; /* unspecified */
70 static int fetch_show_forced_updates = 1;
71 static uint64_t forced_updates_ms = 0;
72 static int prefetch = 0;
73 static int prune = -1; /* unspecified */
74 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
76 static int fetch_prune_tags_config = -1; /* unspecified */
77 static int prune_tags = -1; /* unspecified */
78 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
80 static int append, dry_run, force, keep, update_head_ok;
81 static int write_fetch_head = 1;
82 static int verbosity, deepen_relative, set_upstream, refetch;
83 static int progress = -1;
84 static int tags = TAGS_DEFAULT, update_shallow, deepen;
85 static int submodule_fetch_jobs_config = -1;
86 static int fetch_parallel_config = 1;
87 static int atomic_fetch;
88 static enum transport_family family;
89 static const char *depth;
90 static const char *deepen_since;
91 static const char *upload_pack;
92 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
93 static struct strbuf default_rla = STRBUF_INIT;
94 static struct transport *gtransport;
95 static struct transport *gsecondary;
96 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
97 static struct refspec refmap = REFSPEC_INIT_FETCH;
98 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
99 static struct string_list server_options = STRING_LIST_INIT_DUP;
100 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
102 struct fetch_config {
103 enum display_format display_format;
106 static int git_fetch_config(const char *k, const char *v, void *cb)
108 struct fetch_config *fetch_config = cb;
110 if (!strcmp(k, "fetch.prune")) {
111 fetch_prune_config = git_config_bool(k, v);
112 return 0;
115 if (!strcmp(k, "fetch.prunetags")) {
116 fetch_prune_tags_config = git_config_bool(k, v);
117 return 0;
120 if (!strcmp(k, "fetch.showforcedupdates")) {
121 fetch_show_forced_updates = git_config_bool(k, v);
122 return 0;
125 if (!strcmp(k, "submodule.recurse")) {
126 int r = git_config_bool(k, v) ?
127 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
128 recurse_submodules = r;
131 if (!strcmp(k, "submodule.fetchjobs")) {
132 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
133 return 0;
134 } else if (!strcmp(k, "fetch.recursesubmodules")) {
135 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
136 return 0;
139 if (!strcmp(k, "fetch.parallel")) {
140 fetch_parallel_config = git_config_int(k, v);
141 if (fetch_parallel_config < 0)
142 die(_("fetch.parallel cannot be negative"));
143 if (!fetch_parallel_config)
144 fetch_parallel_config = online_cpus();
145 return 0;
148 if (!strcmp(k, "fetch.output")) {
149 if (!v)
150 return config_error_nonbool(k);
151 else if (!strcasecmp(v, "full"))
152 fetch_config->display_format = DISPLAY_FORMAT_FULL;
153 else if (!strcasecmp(v, "compact"))
154 fetch_config->display_format = DISPLAY_FORMAT_COMPACT;
155 else
156 die(_("invalid value for '%s': '%s'"),
157 "fetch.output", v);
160 return git_default_config(k, v, cb);
163 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
165 BUG_ON_OPT_NEG(unset);
168 * "git fetch --refmap='' origin foo"
169 * can be used to tell the command not to store anywhere
171 refspec_append(&refmap, arg);
173 return 0;
176 static void unlock_pack(unsigned int flags)
178 if (gtransport)
179 transport_unlock_pack(gtransport, flags);
180 if (gsecondary)
181 transport_unlock_pack(gsecondary, flags);
184 static void unlock_pack_atexit(void)
186 unlock_pack(0);
189 static void unlock_pack_on_signal(int signo)
191 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
192 sigchain_pop(signo);
193 raise(signo);
196 static void add_merge_config(struct ref **head,
197 const struct ref *remote_refs,
198 struct branch *branch,
199 struct ref ***tail)
201 int i;
203 for (i = 0; i < branch->merge_nr; i++) {
204 struct ref *rm, **old_tail = *tail;
205 struct refspec_item refspec;
207 for (rm = *head; rm; rm = rm->next) {
208 if (branch_merge_matches(branch, i, rm->name)) {
209 rm->fetch_head_status = FETCH_HEAD_MERGE;
210 break;
213 if (rm)
214 continue;
217 * Not fetched to a remote-tracking branch? We need to fetch
218 * it anyway to allow this branch's "branch.$name.merge"
219 * to be honored by 'git pull', but we do not have to
220 * fail if branch.$name.merge is misconfigured to point
221 * at a nonexisting branch. If we were indeed called by
222 * 'git pull', it will notice the misconfiguration because
223 * there is no entry in the resulting FETCH_HEAD marked
224 * for merging.
226 memset(&refspec, 0, sizeof(refspec));
227 refspec.src = branch->merge[i]->src;
228 get_fetch_map(remote_refs, &refspec, tail, 1);
229 for (rm = *old_tail; rm; rm = rm->next)
230 rm->fetch_head_status = FETCH_HEAD_MERGE;
234 static void create_fetch_oidset(struct ref **head, struct oidset *out)
236 struct ref *rm = *head;
237 while (rm) {
238 oidset_insert(out, &rm->old_oid);
239 rm = rm->next;
243 struct refname_hash_entry {
244 struct hashmap_entry ent;
245 struct object_id oid;
246 int ignore;
247 char refname[FLEX_ARRAY];
250 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
251 const struct hashmap_entry *eptr,
252 const struct hashmap_entry *entry_or_key,
253 const void *keydata)
255 const struct refname_hash_entry *e1, *e2;
257 e1 = container_of(eptr, const struct refname_hash_entry, ent);
258 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
259 return strcmp(e1->refname, keydata ? keydata : e2->refname);
262 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
263 const char *refname,
264 const struct object_id *oid)
266 struct refname_hash_entry *ent;
267 size_t len = strlen(refname);
269 FLEX_ALLOC_MEM(ent, refname, refname, len);
270 hashmap_entry_init(&ent->ent, strhash(refname));
271 oidcpy(&ent->oid, oid);
272 hashmap_add(map, &ent->ent);
273 return ent;
276 static int add_one_refname(const char *refname,
277 const struct object_id *oid,
278 int flag UNUSED, void *cbdata)
280 struct hashmap *refname_map = cbdata;
282 (void) refname_hash_add(refname_map, refname, oid);
283 return 0;
286 static void refname_hash_init(struct hashmap *map)
288 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
291 static int refname_hash_exists(struct hashmap *map, const char *refname)
293 return !!hashmap_get_from_hash(map, strhash(refname), refname);
296 static void clear_item(struct refname_hash_entry *item)
298 item->ignore = 1;
302 static void add_already_queued_tags(const char *refname,
303 const struct object_id *old_oid,
304 const struct object_id *new_oid,
305 void *cb_data)
307 struct hashmap *queued_tags = cb_data;
308 if (starts_with(refname, "refs/tags/") && new_oid)
309 (void) refname_hash_add(queued_tags, refname, new_oid);
312 static void find_non_local_tags(const struct ref *refs,
313 struct ref_transaction *transaction,
314 struct ref **head,
315 struct ref ***tail)
317 struct hashmap existing_refs;
318 struct hashmap remote_refs;
319 struct oidset fetch_oids = OIDSET_INIT;
320 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
321 struct string_list_item *remote_ref_item;
322 const struct ref *ref;
323 struct refname_hash_entry *item = NULL;
324 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
326 refname_hash_init(&existing_refs);
327 refname_hash_init(&remote_refs);
328 create_fetch_oidset(head, &fetch_oids);
330 for_each_ref(add_one_refname, &existing_refs);
333 * If we already have a transaction, then we need to filter out all
334 * tags which have already been queued up.
336 if (transaction)
337 ref_transaction_for_each_queued_update(transaction,
338 add_already_queued_tags,
339 &existing_refs);
341 for (ref = refs; ref; ref = ref->next) {
342 if (!starts_with(ref->name, "refs/tags/"))
343 continue;
346 * The peeled ref always follows the matching base
347 * ref, so if we see a peeled ref that we don't want
348 * to fetch then we can mark the ref entry in the list
349 * as one to ignore by setting util to NULL.
351 if (ends_with(ref->name, "^{}")) {
352 if (item &&
353 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
354 !oidset_contains(&fetch_oids, &ref->old_oid) &&
355 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
356 !oidset_contains(&fetch_oids, &item->oid))
357 clear_item(item);
358 item = NULL;
359 continue;
363 * If item is non-NULL here, then we previously saw a
364 * ref not followed by a peeled reference, so we need
365 * to check if it is a lightweight tag that we want to
366 * fetch.
368 if (item &&
369 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
370 !oidset_contains(&fetch_oids, &item->oid))
371 clear_item(item);
373 item = NULL;
375 /* skip duplicates and refs that we already have */
376 if (refname_hash_exists(&remote_refs, ref->name) ||
377 refname_hash_exists(&existing_refs, ref->name))
378 continue;
380 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
381 string_list_insert(&remote_refs_list, ref->name);
383 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
386 * We may have a final lightweight tag that needs to be
387 * checked to see if it needs fetching.
389 if (item &&
390 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
391 !oidset_contains(&fetch_oids, &item->oid))
392 clear_item(item);
395 * For all the tags in the remote_refs_list,
396 * add them to the list of refs to be fetched
398 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
399 const char *refname = remote_ref_item->string;
400 struct ref *rm;
401 unsigned int hash = strhash(refname);
403 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
404 struct refname_hash_entry, ent);
405 if (!item)
406 BUG("unseen remote ref?");
408 /* Unless we have already decided to ignore this item... */
409 if (item->ignore)
410 continue;
412 rm = alloc_ref(item->refname);
413 rm->peer_ref = alloc_ref(item->refname);
414 oidcpy(&rm->old_oid, &item->oid);
415 **tail = rm;
416 *tail = &rm->next;
418 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
419 string_list_clear(&remote_refs_list, 0);
420 oidset_clear(&fetch_oids);
423 static void filter_prefetch_refspec(struct refspec *rs)
425 int i;
427 if (!prefetch)
428 return;
430 for (i = 0; i < rs->nr; i++) {
431 struct strbuf new_dst = STRBUF_INIT;
432 char *old_dst;
433 const char *sub = NULL;
435 if (rs->items[i].negative)
436 continue;
437 if (!rs->items[i].dst ||
438 (rs->items[i].src &&
439 !strncmp(rs->items[i].src,
440 ref_namespace[NAMESPACE_TAGS].ref,
441 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
442 int j;
444 free(rs->items[i].src);
445 free(rs->items[i].dst);
447 for (j = i + 1; j < rs->nr; j++) {
448 rs->items[j - 1] = rs->items[j];
449 rs->raw[j - 1] = rs->raw[j];
451 rs->nr--;
452 i--;
453 continue;
456 old_dst = rs->items[i].dst;
457 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
460 * If old_dst starts with "refs/", then place
461 * sub after that prefix. Otherwise, start at
462 * the beginning of the string.
464 if (!skip_prefix(old_dst, "refs/", &sub))
465 sub = old_dst;
466 strbuf_addstr(&new_dst, sub);
468 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
469 rs->items[i].force = 1;
471 free(old_dst);
475 static struct ref *get_ref_map(struct remote *remote,
476 const struct ref *remote_refs,
477 struct refspec *rs,
478 int tags, int *autotags)
480 int i;
481 struct ref *rm;
482 struct ref *ref_map = NULL;
483 struct ref **tail = &ref_map;
485 /* opportunistically-updated references: */
486 struct ref *orefs = NULL, **oref_tail = &orefs;
488 struct hashmap existing_refs;
489 int existing_refs_populated = 0;
491 filter_prefetch_refspec(rs);
492 if (remote)
493 filter_prefetch_refspec(&remote->fetch);
495 if (rs->nr) {
496 struct refspec *fetch_refspec;
498 for (i = 0; i < rs->nr; i++) {
499 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
500 if (rs->items[i].dst && rs->items[i].dst[0])
501 *autotags = 1;
503 /* Merge everything on the command line (but not --tags) */
504 for (rm = ref_map; rm; rm = rm->next)
505 rm->fetch_head_status = FETCH_HEAD_MERGE;
508 * For any refs that we happen to be fetching via
509 * command-line arguments, the destination ref might
510 * have been missing or have been different than the
511 * remote-tracking ref that would be derived from the
512 * configured refspec. In these cases, we want to
513 * take the opportunity to update their configured
514 * remote-tracking reference. However, we do not want
515 * to mention these entries in FETCH_HEAD at all, as
516 * they would simply be duplicates of existing
517 * entries, so we set them FETCH_HEAD_IGNORE below.
519 * We compute these entries now, based only on the
520 * refspecs specified on the command line. But we add
521 * them to the list following the refspecs resulting
522 * from the tags option so that one of the latter,
523 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
524 * by ref_remove_duplicates() in favor of one of these
525 * opportunistic entries with FETCH_HEAD_IGNORE.
527 if (refmap.nr)
528 fetch_refspec = &refmap;
529 else
530 fetch_refspec = &remote->fetch;
532 for (i = 0; i < fetch_refspec->nr; i++)
533 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
534 } else if (refmap.nr) {
535 die("--refmap option is only meaningful with command-line refspec(s)");
536 } else {
537 /* Use the defaults */
538 struct branch *branch = branch_get(NULL);
539 int has_merge = branch_has_merge_config(branch);
540 if (remote &&
541 (remote->fetch.nr ||
542 /* Note: has_merge implies non-NULL branch->remote_name */
543 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
544 for (i = 0; i < remote->fetch.nr; i++) {
545 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
546 if (remote->fetch.items[i].dst &&
547 remote->fetch.items[i].dst[0])
548 *autotags = 1;
549 if (!i && !has_merge && ref_map &&
550 !remote->fetch.items[0].pattern)
551 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
554 * if the remote we're fetching from is the same
555 * as given in branch.<name>.remote, we add the
556 * ref given in branch.<name>.merge, too.
558 * Note: has_merge implies non-NULL branch->remote_name
560 if (has_merge &&
561 !strcmp(branch->remote_name, remote->name))
562 add_merge_config(&ref_map, remote_refs, branch, &tail);
563 } else if (!prefetch) {
564 ref_map = get_remote_ref(remote_refs, "HEAD");
565 if (!ref_map)
566 die(_("couldn't find remote ref HEAD"));
567 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
568 tail = &ref_map->next;
572 if (tags == TAGS_SET)
573 /* also fetch all tags */
574 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
575 else if (tags == TAGS_DEFAULT && *autotags)
576 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
578 /* Now append any refs to be updated opportunistically: */
579 *tail = orefs;
580 for (rm = orefs; rm; rm = rm->next) {
581 rm->fetch_head_status = FETCH_HEAD_IGNORE;
582 tail = &rm->next;
586 * apply negative refspecs first, before we remove duplicates. This is
587 * necessary as negative refspecs might remove an otherwise conflicting
588 * duplicate.
590 if (rs->nr)
591 ref_map = apply_negative_refspecs(ref_map, rs);
592 else
593 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
595 ref_map = ref_remove_duplicates(ref_map);
597 for (rm = ref_map; rm; rm = rm->next) {
598 if (rm->peer_ref) {
599 const char *refname = rm->peer_ref->name;
600 struct refname_hash_entry *peer_item;
601 unsigned int hash = strhash(refname);
603 if (!existing_refs_populated) {
604 refname_hash_init(&existing_refs);
605 for_each_ref(add_one_refname, &existing_refs);
606 existing_refs_populated = 1;
609 peer_item = hashmap_get_entry_from_hash(&existing_refs,
610 hash, refname,
611 struct refname_hash_entry, ent);
612 if (peer_item) {
613 struct object_id *old_oid = &peer_item->oid;
614 oidcpy(&rm->peer_ref->old_oid, old_oid);
618 if (existing_refs_populated)
619 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
621 return ref_map;
624 #define STORE_REF_ERROR_OTHER 1
625 #define STORE_REF_ERROR_DF_CONFLICT 2
627 static int s_update_ref(const char *action,
628 struct ref *ref,
629 struct ref_transaction *transaction,
630 int check_old)
632 char *msg;
633 char *rla = getenv("GIT_REFLOG_ACTION");
634 struct ref_transaction *our_transaction = NULL;
635 struct strbuf err = STRBUF_INIT;
636 int ret;
638 if (dry_run)
639 return 0;
640 if (!rla)
641 rla = default_rla.buf;
642 msg = xstrfmt("%s: %s", rla, action);
645 * If no transaction was passed to us, we manage the transaction
646 * ourselves. Otherwise, we trust the caller to handle the transaction
647 * lifecycle.
649 if (!transaction) {
650 transaction = our_transaction = ref_transaction_begin(&err);
651 if (!transaction) {
652 ret = STORE_REF_ERROR_OTHER;
653 goto out;
657 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
658 check_old ? &ref->old_oid : NULL,
659 0, msg, &err);
660 if (ret) {
661 ret = STORE_REF_ERROR_OTHER;
662 goto out;
665 if (our_transaction) {
666 switch (ref_transaction_commit(our_transaction, &err)) {
667 case 0:
668 break;
669 case TRANSACTION_NAME_CONFLICT:
670 ret = STORE_REF_ERROR_DF_CONFLICT;
671 goto out;
672 default:
673 ret = STORE_REF_ERROR_OTHER;
674 goto out;
678 out:
679 ref_transaction_free(our_transaction);
680 if (ret)
681 error("%s", err.buf);
682 strbuf_release(&err);
683 free(msg);
684 return ret;
687 static int refcol_width(const struct ref *ref_map, int compact_format)
689 const struct ref *ref;
690 int max, width = 10;
692 max = term_columns();
693 if (compact_format)
694 max = max * 2 / 3;
696 for (ref = ref_map; ref; ref = ref->next) {
697 int rlen, llen = 0, len;
699 if (ref->status == REF_STATUS_REJECT_SHALLOW ||
700 !ref->peer_ref ||
701 !strcmp(ref->name, "HEAD"))
702 continue;
704 /* uptodate lines are only shown on high verbosity level */
705 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
706 continue;
708 rlen = utf8_strwidth(prettify_refname(ref->name));
709 if (!compact_format)
710 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
713 * rough estimation to see if the output line is too long and
714 * should not be counted (we can't do precise calculation
715 * anyway because we don't know if the error explanation part
716 * will be printed in update_local_ref)
718 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
719 if (len >= max)
720 continue;
722 if (width < rlen)
723 width = rlen;
726 return width;
729 static void display_state_init(struct display_state *display_state, struct ref *ref_map,
730 const char *raw_url, enum display_format format)
732 int i;
734 memset(display_state, 0, sizeof(*display_state));
735 strbuf_init(&display_state->buf, 0);
736 display_state->format = format;
738 if (raw_url)
739 display_state->url = transport_anonymize_url(raw_url);
740 else
741 display_state->url = xstrdup("foreign");
743 display_state->url_len = strlen(display_state->url);
744 for (i = display_state->url_len - 1; display_state->url[i] == '/' && 0 <= i; i--)
746 display_state->url_len = i + 1;
747 if (4 < i && !strncmp(".git", display_state->url + i - 3, 4))
748 display_state->url_len = i - 3;
750 if (verbosity < 0)
751 return;
753 switch (display_state->format) {
754 case DISPLAY_FORMAT_FULL:
755 case DISPLAY_FORMAT_COMPACT:
756 display_state->refcol_width = refcol_width(ref_map,
757 display_state->format == DISPLAY_FORMAT_COMPACT);
758 break;
759 default:
760 BUG("unexpected display format %d", display_state->format);
764 static void display_state_release(struct display_state *display_state)
766 strbuf_release(&display_state->buf);
767 free(display_state->url);
770 static void print_remote_to_local(struct display_state *display_state,
771 const char *remote, const char *local)
773 strbuf_addf(&display_state->buf, "%-*s -> %s",
774 display_state->refcol_width, remote, local);
777 static int find_and_replace(struct strbuf *haystack,
778 const char *needle,
779 const char *placeholder)
781 const char *p = NULL;
782 int plen, nlen;
784 nlen = strlen(needle);
785 if (ends_with(haystack->buf, needle))
786 p = haystack->buf + haystack->len - nlen;
787 else
788 p = strstr(haystack->buf, needle);
789 if (!p)
790 return 0;
792 if (p > haystack->buf && p[-1] != '/')
793 return 0;
795 plen = strlen(p);
796 if (plen > nlen && p[nlen] != '/')
797 return 0;
799 strbuf_splice(haystack, p - haystack->buf, nlen,
800 placeholder, strlen(placeholder));
801 return 1;
804 static void print_compact(struct display_state *display_state,
805 const char *remote, const char *local)
807 struct strbuf r = STRBUF_INIT;
808 struct strbuf l = STRBUF_INIT;
810 if (!strcmp(remote, local)) {
811 strbuf_addf(&display_state->buf, "%-*s -> *", display_state->refcol_width, remote);
812 return;
815 strbuf_addstr(&r, remote);
816 strbuf_addstr(&l, local);
818 if (!find_and_replace(&r, local, "*"))
819 find_and_replace(&l, remote, "*");
820 print_remote_to_local(display_state, r.buf, l.buf);
822 strbuf_release(&r);
823 strbuf_release(&l);
826 static void display_ref_update(struct display_state *display_state, char code,
827 const char *summary, const char *error,
828 const char *remote, const char *local,
829 int summary_width)
831 if (verbosity < 0)
832 return;
834 strbuf_reset(&display_state->buf);
836 switch (display_state->format) {
837 case DISPLAY_FORMAT_FULL:
838 case DISPLAY_FORMAT_COMPACT: {
839 int width;
841 if (!display_state->shown_url) {
842 strbuf_addf(&display_state->buf, _("From %.*s\n"),
843 display_state->url_len, display_state->url);
844 display_state->shown_url = 1;
847 width = (summary_width + strlen(summary) - gettext_width(summary));
848 remote = prettify_refname(remote);
849 local = prettify_refname(local);
851 strbuf_addf(&display_state->buf, " %c %-*s ", code, width, summary);
853 if (display_state->format != DISPLAY_FORMAT_COMPACT)
854 print_remote_to_local(display_state, remote, local);
855 else
856 print_compact(display_state, remote, local);
858 if (error)
859 strbuf_addf(&display_state->buf, " (%s)", error);
861 break;
863 default:
864 BUG("unexpected display format %d", display_state->format);
866 strbuf_addch(&display_state->buf, '\n');
868 fputs(display_state->buf.buf, stderr);
871 static int update_local_ref(struct ref *ref,
872 struct ref_transaction *transaction,
873 struct display_state *display_state,
874 const struct ref *remote_ref,
875 int summary_width)
877 struct commit *current = NULL, *updated;
878 int fast_forward = 0;
880 if (!repo_has_object_file(the_repository, &ref->new_oid))
881 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
883 if (oideq(&ref->old_oid, &ref->new_oid)) {
884 if (verbosity > 0)
885 display_ref_update(display_state, '=', _("[up to date]"), NULL,
886 remote_ref->name, ref->name, summary_width);
887 return 0;
890 if (!update_head_ok &&
891 !is_null_oid(&ref->old_oid) &&
892 branch_checked_out(ref->name)) {
894 * If this is the head, and it's not okay to update
895 * the head, and the old value of the head isn't empty...
897 display_ref_update(display_state, '!', _("[rejected]"),
898 _("can't fetch into checked-out branch"),
899 remote_ref->name, ref->name, summary_width);
900 return 1;
903 if (!is_null_oid(&ref->old_oid) &&
904 starts_with(ref->name, "refs/tags/")) {
905 if (force || ref->force) {
906 int r;
907 r = s_update_ref("updating tag", ref, transaction, 0);
908 display_ref_update(display_state, r ? '!' : 't', _("[tag update]"),
909 r ? _("unable to update local ref") : NULL,
910 remote_ref->name, ref->name, summary_width);
911 return r;
912 } else {
913 display_ref_update(display_state, '!', _("[rejected]"),
914 _("would clobber existing tag"),
915 remote_ref->name, ref->name, summary_width);
916 return 1;
920 current = lookup_commit_reference_gently(the_repository,
921 &ref->old_oid, 1);
922 updated = lookup_commit_reference_gently(the_repository,
923 &ref->new_oid, 1);
924 if (!current || !updated) {
925 const char *msg;
926 const char *what;
927 int r;
929 * Nicely describe the new ref we're fetching.
930 * Base this on the remote's ref name, as it's
931 * more likely to follow a standard layout.
933 const char *name = remote_ref ? remote_ref->name : "";
934 if (starts_with(name, "refs/tags/")) {
935 msg = "storing tag";
936 what = _("[new tag]");
937 } else if (starts_with(name, "refs/heads/")) {
938 msg = "storing head";
939 what = _("[new branch]");
940 } else {
941 msg = "storing ref";
942 what = _("[new ref]");
945 r = s_update_ref(msg, ref, transaction, 0);
946 display_ref_update(display_state, r ? '!' : '*', what,
947 r ? _("unable to update local ref") : NULL,
948 remote_ref->name, ref->name, summary_width);
949 return r;
952 if (fetch_show_forced_updates) {
953 uint64_t t_before = getnanotime();
954 fast_forward = repo_in_merge_bases(the_repository, current,
955 updated);
956 forced_updates_ms += (getnanotime() - t_before) / 1000000;
957 } else {
958 fast_forward = 1;
961 if (fast_forward) {
962 struct strbuf quickref = STRBUF_INIT;
963 int r;
965 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
966 strbuf_addstr(&quickref, "..");
967 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
968 r = s_update_ref("fast-forward", ref, transaction, 1);
969 display_ref_update(display_state, r ? '!' : ' ', quickref.buf,
970 r ? _("unable to update local ref") : NULL,
971 remote_ref->name, ref->name, summary_width);
972 strbuf_release(&quickref);
973 return r;
974 } else if (force || ref->force) {
975 struct strbuf quickref = STRBUF_INIT;
976 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("forced-update", ref, transaction, 1);
981 display_ref_update(display_state, r ? '!' : '+', quickref.buf,
982 r ? _("unable to update local ref") : _("forced update"),
983 remote_ref->name, ref->name, summary_width);
984 strbuf_release(&quickref);
985 return r;
986 } else {
987 display_ref_update(display_state, '!', _("[rejected]"), _("non-fast-forward"),
988 remote_ref->name, ref->name, summary_width);
989 return 1;
993 static const struct object_id *iterate_ref_map(void *cb_data)
995 struct ref **rm = cb_data;
996 struct ref *ref = *rm;
998 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
999 ref = ref->next;
1000 if (!ref)
1001 return NULL;
1002 *rm = ref->next;
1003 return &ref->old_oid;
1006 struct fetch_head {
1007 FILE *fp;
1008 struct strbuf buf;
1011 static int open_fetch_head(struct fetch_head *fetch_head)
1013 const char *filename = git_path_fetch_head(the_repository);
1015 if (write_fetch_head) {
1016 fetch_head->fp = fopen(filename, "a");
1017 if (!fetch_head->fp)
1018 return error_errno(_("cannot open '%s'"), filename);
1019 strbuf_init(&fetch_head->buf, 0);
1020 } else {
1021 fetch_head->fp = NULL;
1024 return 0;
1027 static void append_fetch_head(struct fetch_head *fetch_head,
1028 const struct object_id *old_oid,
1029 enum fetch_head_status fetch_head_status,
1030 const char *note,
1031 const char *url, size_t url_len)
1033 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1034 const char *merge_status_marker;
1035 size_t i;
1037 if (!fetch_head->fp)
1038 return;
1040 switch (fetch_head_status) {
1041 case FETCH_HEAD_NOT_FOR_MERGE:
1042 merge_status_marker = "not-for-merge";
1043 break;
1044 case FETCH_HEAD_MERGE:
1045 merge_status_marker = "";
1046 break;
1047 default:
1048 /* do not write anything to FETCH_HEAD */
1049 return;
1052 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1053 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1054 for (i = 0; i < url_len; ++i)
1055 if ('\n' == url[i])
1056 strbuf_addstr(&fetch_head->buf, "\\n");
1057 else
1058 strbuf_addch(&fetch_head->buf, url[i]);
1059 strbuf_addch(&fetch_head->buf, '\n');
1062 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1063 * any of the reference updates fails. We thus have to write all
1064 * updates to a buffer first and only commit it as soon as all
1065 * references have been successfully updated.
1067 if (!atomic_fetch) {
1068 strbuf_write(&fetch_head->buf, fetch_head->fp);
1069 strbuf_reset(&fetch_head->buf);
1073 static void commit_fetch_head(struct fetch_head *fetch_head)
1075 if (!fetch_head->fp || !atomic_fetch)
1076 return;
1077 strbuf_write(&fetch_head->buf, fetch_head->fp);
1080 static void close_fetch_head(struct fetch_head *fetch_head)
1082 if (!fetch_head->fp)
1083 return;
1085 fclose(fetch_head->fp);
1086 strbuf_release(&fetch_head->buf);
1089 static const char warn_show_forced_updates[] =
1090 N_("fetch normally indicates which branches had a forced update,\n"
1091 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1092 "flag or run 'git config fetch.showForcedUpdates true'");
1093 static const char warn_time_show_forced_updates[] =
1094 N_("it took %.2f seconds to check forced updates; you can use\n"
1095 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1096 "to avoid this check\n");
1098 static int store_updated_refs(struct display_state *display_state,
1099 const char *remote_name,
1100 int connectivity_checked,
1101 struct ref_transaction *transaction, struct ref *ref_map,
1102 struct fetch_head *fetch_head)
1104 int rc = 0;
1105 struct strbuf note = STRBUF_INIT;
1106 const char *what, *kind;
1107 struct ref *rm;
1108 int want_status;
1109 int summary_width = 0;
1111 if (verbosity >= 0)
1112 summary_width = transport_summary_width(ref_map);
1114 if (!connectivity_checked) {
1115 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1117 opt.exclude_hidden_refs_section = "fetch";
1118 rm = ref_map;
1119 if (check_connected(iterate_ref_map, &rm, &opt)) {
1120 rc = error(_("%s did not send all necessary objects\n"),
1121 display_state->url);
1122 goto abort;
1127 * We do a pass for each fetch_head_status type in their enum order, so
1128 * merged entries are written before not-for-merge. That lets readers
1129 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1131 for (want_status = FETCH_HEAD_MERGE;
1132 want_status <= FETCH_HEAD_IGNORE;
1133 want_status++) {
1134 for (rm = ref_map; rm; rm = rm->next) {
1135 struct ref *ref = NULL;
1137 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1138 if (want_status == FETCH_HEAD_MERGE)
1139 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1140 rm->peer_ref ? rm->peer_ref->name : rm->name);
1141 continue;
1145 * When writing FETCH_HEAD we need to determine whether
1146 * we already have the commit or not. If not, then the
1147 * reference is not for merge and needs to be written
1148 * to the reflog after other commits which we already
1149 * have. We're not interested in this property though
1150 * in case FETCH_HEAD is not to be updated, so we can
1151 * skip the classification in that case.
1153 if (fetch_head->fp) {
1154 struct commit *commit = NULL;
1157 * References in "refs/tags/" are often going to point
1158 * to annotated tags, which are not part of the
1159 * commit-graph. We thus only try to look up refs in
1160 * the graph which are not in that namespace to not
1161 * regress performance in repositories with many
1162 * annotated tags.
1164 if (!starts_with(rm->name, "refs/tags/"))
1165 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1166 if (!commit) {
1167 commit = lookup_commit_reference_gently(the_repository,
1168 &rm->old_oid,
1170 if (!commit)
1171 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1175 if (rm->fetch_head_status != want_status)
1176 continue;
1178 if (rm->peer_ref) {
1179 ref = alloc_ref(rm->peer_ref->name);
1180 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1181 oidcpy(&ref->new_oid, &rm->old_oid);
1182 ref->force = rm->peer_ref->force;
1185 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1186 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1187 check_for_new_submodule_commits(&rm->old_oid);
1190 if (!strcmp(rm->name, "HEAD")) {
1191 kind = "";
1192 what = "";
1193 } else if (skip_prefix(rm->name, "refs/heads/", &what)) {
1194 kind = "branch";
1195 } else if (skip_prefix(rm->name, "refs/tags/", &what)) {
1196 kind = "tag";
1197 } else if (skip_prefix(rm->name, "refs/remotes/", &what)) {
1198 kind = "remote-tracking branch";
1199 } else {
1200 kind = "";
1201 what = rm->name;
1204 strbuf_reset(&note);
1205 if (*what) {
1206 if (*kind)
1207 strbuf_addf(&note, "%s ", kind);
1208 strbuf_addf(&note, "'%s' of ", what);
1211 append_fetch_head(fetch_head, &rm->old_oid,
1212 rm->fetch_head_status,
1213 note.buf, display_state->url,
1214 display_state->url_len);
1216 if (ref) {
1217 rc |= update_local_ref(ref, transaction, display_state,
1218 rm, summary_width);
1219 free(ref);
1220 } else if (write_fetch_head || dry_run) {
1222 * Display fetches written to FETCH_HEAD (or
1223 * would be written to FETCH_HEAD, if --dry-run
1224 * is set).
1226 display_ref_update(display_state, '*',
1227 *kind ? kind : "branch", NULL,
1228 rm->name,
1229 "FETCH_HEAD", summary_width);
1234 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1235 error(_("some local refs could not be updated; try running\n"
1236 " 'git remote prune %s' to remove any old, conflicting "
1237 "branches"), remote_name);
1239 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1240 if (!fetch_show_forced_updates) {
1241 warning(_(warn_show_forced_updates));
1242 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1243 warning(_(warn_time_show_forced_updates),
1244 forced_updates_ms / 1000.0);
1248 abort:
1249 strbuf_release(&note);
1250 return rc;
1254 * We would want to bypass the object transfer altogether if
1255 * everything we are going to fetch already exists and is connected
1256 * locally.
1258 static int check_exist_and_connected(struct ref *ref_map)
1260 struct ref *rm = ref_map;
1261 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1262 struct ref *r;
1265 * If we are deepening a shallow clone we already have these
1266 * objects reachable. Running rev-list here will return with
1267 * a good (0) exit status and we'll bypass the fetch that we
1268 * really need to perform. Claiming failure now will ensure
1269 * we perform the network exchange to deepen our history.
1271 if (deepen)
1272 return -1;
1275 * Similarly, if we need to refetch, we always want to perform a full
1276 * fetch ignoring existing objects.
1278 if (refetch)
1279 return -1;
1283 * check_connected() allows objects to merely be promised, but
1284 * we need all direct targets to exist.
1286 for (r = rm; r; r = r->next) {
1287 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1288 OBJECT_INFO_SKIP_FETCH_OBJECT))
1289 return -1;
1292 opt.quiet = 1;
1293 opt.exclude_hidden_refs_section = "fetch";
1294 return check_connected(iterate_ref_map, &rm, &opt);
1297 static int fetch_and_consume_refs(struct display_state *display_state,
1298 struct transport *transport,
1299 struct ref_transaction *transaction,
1300 struct ref *ref_map,
1301 struct fetch_head *fetch_head)
1303 int connectivity_checked = 1;
1304 int ret;
1307 * We don't need to perform a fetch in case we can already satisfy all
1308 * refs.
1310 ret = check_exist_and_connected(ref_map);
1311 if (ret) {
1312 trace2_region_enter("fetch", "fetch_refs", the_repository);
1313 ret = transport_fetch_refs(transport, ref_map);
1314 trace2_region_leave("fetch", "fetch_refs", the_repository);
1315 if (ret)
1316 goto out;
1317 connectivity_checked = transport->smart_options ?
1318 transport->smart_options->connectivity_checked : 0;
1321 trace2_region_enter("fetch", "consume_refs", the_repository);
1322 ret = store_updated_refs(display_state, transport->remote->name,
1323 connectivity_checked, transaction, ref_map,
1324 fetch_head);
1325 trace2_region_leave("fetch", "consume_refs", the_repository);
1327 out:
1328 transport_unlock_pack(transport, 0);
1329 return ret;
1332 static int prune_refs(struct display_state *display_state,
1333 struct refspec *rs,
1334 struct ref_transaction *transaction,
1335 struct ref *ref_map)
1337 int result = 0;
1338 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1339 struct strbuf err = STRBUF_INIT;
1340 const char *dangling_msg = dry_run
1341 ? _(" (%s will become dangling)")
1342 : _(" (%s has become dangling)");
1344 if (!dry_run) {
1345 if (transaction) {
1346 for (ref = stale_refs; ref; ref = ref->next) {
1347 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1348 "fetch: prune", &err);
1349 if (result)
1350 goto cleanup;
1352 } else {
1353 struct string_list refnames = STRING_LIST_INIT_NODUP;
1355 for (ref = stale_refs; ref; ref = ref->next)
1356 string_list_append(&refnames, ref->name);
1358 result = delete_refs("fetch: prune", &refnames, 0);
1359 string_list_clear(&refnames, 0);
1363 if (verbosity >= 0) {
1364 int summary_width = transport_summary_width(stale_refs);
1366 for (ref = stale_refs; ref; ref = ref->next) {
1367 display_ref_update(display_state, '-', _("[deleted]"), NULL,
1368 _("(none)"), ref->name,
1369 summary_width);
1370 warn_dangling_symref(stderr, dangling_msg, ref->name);
1374 cleanup:
1375 strbuf_release(&err);
1376 free_refs(stale_refs);
1377 return result;
1380 static void check_not_current_branch(struct ref *ref_map)
1382 const char *path;
1383 for (; ref_map; ref_map = ref_map->next)
1384 if (ref_map->peer_ref &&
1385 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1386 (path = branch_checked_out(ref_map->peer_ref->name)))
1387 die(_("refusing to fetch into branch '%s' "
1388 "checked out at '%s'"),
1389 ref_map->peer_ref->name, path);
1392 static int truncate_fetch_head(void)
1394 const char *filename = git_path_fetch_head(the_repository);
1395 FILE *fp = fopen_for_writing(filename);
1397 if (!fp)
1398 return error_errno(_("cannot open '%s'"), filename);
1399 fclose(fp);
1400 return 0;
1403 static void set_option(struct transport *transport, const char *name, const char *value)
1405 int r = transport_set_option(transport, name, value);
1406 if (r < 0)
1407 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1408 name, value, transport->url);
1409 if (r > 0)
1410 warning(_("option \"%s\" is ignored for %s\n"),
1411 name, transport->url);
1415 static int add_oid(const char *refname UNUSED,
1416 const struct object_id *oid,
1417 int flags UNUSED, void *cb_data)
1419 struct oid_array *oids = cb_data;
1421 oid_array_append(oids, oid);
1422 return 0;
1425 static void add_negotiation_tips(struct git_transport_options *smart_options)
1427 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1428 int i;
1430 for (i = 0; i < negotiation_tip.nr; i++) {
1431 const char *s = negotiation_tip.items[i].string;
1432 int old_nr;
1433 if (!has_glob_specials(s)) {
1434 struct object_id oid;
1435 if (repo_get_oid(the_repository, s, &oid))
1436 die(_("%s is not a valid object"), s);
1437 if (!has_object(the_repository, &oid, 0))
1438 die(_("the object %s does not exist"), s);
1439 oid_array_append(oids, &oid);
1440 continue;
1442 old_nr = oids->nr;
1443 for_each_glob_ref(add_oid, s, oids);
1444 if (old_nr == oids->nr)
1445 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1448 smart_options->negotiation_tips = oids;
1451 static struct transport *prepare_transport(struct remote *remote, int deepen)
1453 struct transport *transport;
1455 transport = transport_get(remote, NULL);
1456 transport_set_verbosity(transport, verbosity, progress);
1457 transport->family = family;
1458 if (upload_pack)
1459 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1460 if (keep)
1461 set_option(transport, TRANS_OPT_KEEP, "yes");
1462 if (depth)
1463 set_option(transport, TRANS_OPT_DEPTH, depth);
1464 if (deepen && deepen_since)
1465 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1466 if (deepen && deepen_not.nr)
1467 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1468 (const char *)&deepen_not);
1469 if (deepen_relative)
1470 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1471 if (update_shallow)
1472 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1473 if (refetch)
1474 set_option(transport, TRANS_OPT_REFETCH, "yes");
1475 if (filter_options.choice) {
1476 const char *spec =
1477 expand_list_objects_filter_spec(&filter_options);
1478 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1479 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1481 if (negotiation_tip.nr) {
1482 if (transport->smart_options)
1483 add_negotiation_tips(transport->smart_options);
1484 else
1485 warning("ignoring --negotiation-tip because the protocol does not support it");
1487 return transport;
1490 static int backfill_tags(struct display_state *display_state,
1491 struct transport *transport,
1492 struct ref_transaction *transaction,
1493 struct ref *ref_map,
1494 struct fetch_head *fetch_head)
1496 int retcode, cannot_reuse;
1499 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1500 * when remote helper is used (setting it to an empty string
1501 * is not unsetting). We could extend the remote helper
1502 * protocol for that, but for now, just force a new connection
1503 * without deepen-since. Similar story for deepen-not.
1505 cannot_reuse = transport->cannot_reuse ||
1506 deepen_since || deepen_not.nr;
1507 if (cannot_reuse) {
1508 gsecondary = prepare_transport(transport->remote, 0);
1509 transport = gsecondary;
1512 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1513 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1514 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1515 retcode = fetch_and_consume_refs(display_state, transport, transaction, ref_map, fetch_head);
1517 if (gsecondary) {
1518 transport_disconnect(gsecondary);
1519 gsecondary = NULL;
1522 return retcode;
1525 static int do_fetch(struct transport *transport,
1526 struct refspec *rs,
1527 enum display_format display_format)
1529 struct ref_transaction *transaction = NULL;
1530 struct ref *ref_map = NULL;
1531 struct display_state display_state = { 0 };
1532 int autotags = (transport->remote->fetch_tags == 1);
1533 int retcode = 0;
1534 const struct ref *remote_refs;
1535 struct transport_ls_refs_options transport_ls_refs_options =
1536 TRANSPORT_LS_REFS_OPTIONS_INIT;
1537 int must_list_refs = 1;
1538 struct fetch_head fetch_head = { 0 };
1539 struct strbuf err = STRBUF_INIT;
1541 if (tags == TAGS_DEFAULT) {
1542 if (transport->remote->fetch_tags == 2)
1543 tags = TAGS_SET;
1544 if (transport->remote->fetch_tags == -1)
1545 tags = TAGS_UNSET;
1548 /* if not appending, truncate FETCH_HEAD */
1549 if (!append && write_fetch_head) {
1550 retcode = truncate_fetch_head();
1551 if (retcode)
1552 goto cleanup;
1555 if (rs->nr) {
1556 int i;
1558 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1561 * We can avoid listing refs if all of them are exact
1562 * OIDs
1564 must_list_refs = 0;
1565 for (i = 0; i < rs->nr; i++) {
1566 if (!rs->items[i].exact_sha1) {
1567 must_list_refs = 1;
1568 break;
1571 } else {
1572 struct branch *branch = branch_get(NULL);
1574 if (transport->remote->fetch.nr)
1575 refspec_ref_prefixes(&transport->remote->fetch,
1576 &transport_ls_refs_options.ref_prefixes);
1577 if (branch_has_merge_config(branch) &&
1578 !strcmp(branch->remote_name, transport->remote->name)) {
1579 int i;
1580 for (i = 0; i < branch->merge_nr; i++) {
1581 strvec_push(&transport_ls_refs_options.ref_prefixes,
1582 branch->merge[i]->src);
1587 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1588 must_list_refs = 1;
1589 if (transport_ls_refs_options.ref_prefixes.nr)
1590 strvec_push(&transport_ls_refs_options.ref_prefixes,
1591 "refs/tags/");
1594 if (must_list_refs) {
1595 trace2_region_enter("fetch", "remote_refs", the_repository);
1596 remote_refs = transport_get_remote_refs(transport,
1597 &transport_ls_refs_options);
1598 trace2_region_leave("fetch", "remote_refs", the_repository);
1599 } else
1600 remote_refs = NULL;
1602 transport_ls_refs_options_release(&transport_ls_refs_options);
1604 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1605 tags, &autotags);
1606 if (!update_head_ok)
1607 check_not_current_branch(ref_map);
1609 retcode = open_fetch_head(&fetch_head);
1610 if (retcode)
1611 goto cleanup;
1613 display_state_init(&display_state, ref_map, transport->url, display_format);
1615 if (atomic_fetch) {
1616 transaction = ref_transaction_begin(&err);
1617 if (!transaction) {
1618 retcode = error("%s", err.buf);
1619 goto cleanup;
1623 if (tags == TAGS_DEFAULT && autotags)
1624 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1625 if (prune) {
1627 * We only prune based on refspecs specified
1628 * explicitly (via command line or configuration); we
1629 * don't care whether --tags was specified.
1631 if (rs->nr) {
1632 retcode = prune_refs(&display_state, rs, transaction, ref_map);
1633 } else {
1634 retcode = prune_refs(&display_state, &transport->remote->fetch,
1635 transaction, ref_map);
1637 if (retcode != 0)
1638 retcode = 1;
1641 if (fetch_and_consume_refs(&display_state, transport, transaction, ref_map, &fetch_head)) {
1642 retcode = 1;
1643 goto cleanup;
1647 * If neither --no-tags nor --tags was specified, do automated tag
1648 * following.
1650 if (tags == TAGS_DEFAULT && autotags) {
1651 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1653 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1654 if (tags_ref_map) {
1656 * If backfilling of tags fails then we want to tell
1657 * the user so, but we have to continue regardless to
1658 * populate upstream information of the references we
1659 * have already fetched above. The exception though is
1660 * when `--atomic` is passed: in that case we'll abort
1661 * the transaction and don't commit anything.
1663 if (backfill_tags(&display_state, transport, transaction, tags_ref_map,
1664 &fetch_head))
1665 retcode = 1;
1668 free_refs(tags_ref_map);
1671 if (transaction) {
1672 if (retcode)
1673 goto cleanup;
1675 retcode = ref_transaction_commit(transaction, &err);
1676 if (retcode) {
1677 error("%s", err.buf);
1678 ref_transaction_free(transaction);
1679 transaction = NULL;
1680 goto cleanup;
1684 commit_fetch_head(&fetch_head);
1686 if (set_upstream) {
1687 struct branch *branch = branch_get("HEAD");
1688 struct ref *rm;
1689 struct ref *source_ref = NULL;
1692 * We're setting the upstream configuration for the
1693 * current branch. The relevant upstream is the
1694 * fetched branch that is meant to be merged with the
1695 * current one, i.e. the one fetched to FETCH_HEAD.
1697 * When there are several such branches, consider the
1698 * request ambiguous and err on the safe side by doing
1699 * nothing and just emit a warning.
1701 for (rm = ref_map; rm; rm = rm->next) {
1702 if (!rm->peer_ref) {
1703 if (source_ref) {
1704 warning(_("multiple branches detected, incompatible with --set-upstream"));
1705 goto cleanup;
1706 } else {
1707 source_ref = rm;
1711 if (source_ref) {
1712 if (!branch) {
1713 const char *shortname = source_ref->name;
1714 skip_prefix(shortname, "refs/heads/", &shortname);
1716 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1717 "it does not point to any branch."),
1718 shortname, transport->remote->name);
1719 goto cleanup;
1722 if (!strcmp(source_ref->name, "HEAD") ||
1723 starts_with(source_ref->name, "refs/heads/"))
1724 install_branch_config(0,
1725 branch->name,
1726 transport->remote->name,
1727 source_ref->name);
1728 else if (starts_with(source_ref->name, "refs/remotes/"))
1729 warning(_("not setting upstream for a remote remote-tracking branch"));
1730 else if (starts_with(source_ref->name, "refs/tags/"))
1731 warning(_("not setting upstream for a remote tag"));
1732 else
1733 warning(_("unknown branch type"));
1734 } else {
1735 warning(_("no source branch found;\n"
1736 "you need to specify exactly one branch with the --set-upstream option"));
1740 cleanup:
1741 if (retcode && transaction) {
1742 ref_transaction_abort(transaction, &err);
1743 error("%s", err.buf);
1746 display_state_release(&display_state);
1747 close_fetch_head(&fetch_head);
1748 strbuf_release(&err);
1749 free_refs(ref_map);
1750 return retcode;
1753 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1755 struct string_list *list = priv;
1756 if (!remote->skip_default_update)
1757 string_list_append(list, remote->name);
1758 return 0;
1761 struct remote_group_data {
1762 const char *name;
1763 struct string_list *list;
1766 static int get_remote_group(const char *key, const char *value, void *priv)
1768 struct remote_group_data *g = priv;
1770 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1771 /* split list by white space */
1772 while (*value) {
1773 size_t wordlen = strcspn(value, " \t\n");
1775 if (wordlen >= 1)
1776 string_list_append_nodup(g->list,
1777 xstrndup(value, wordlen));
1778 value += wordlen + (value[wordlen] != '\0');
1782 return 0;
1785 static int add_remote_or_group(const char *name, struct string_list *list)
1787 int prev_nr = list->nr;
1788 struct remote_group_data g;
1789 g.name = name; g.list = list;
1791 git_config(get_remote_group, &g);
1792 if (list->nr == prev_nr) {
1793 struct remote *remote = remote_get(name);
1794 if (!remote_is_configured(remote, 0))
1795 return 0;
1796 string_list_append(list, remote->name);
1798 return 1;
1801 static void add_options_to_argv(struct strvec *argv)
1803 if (dry_run)
1804 strvec_push(argv, "--dry-run");
1805 if (prune != -1)
1806 strvec_push(argv, prune ? "--prune" : "--no-prune");
1807 if (prune_tags != -1)
1808 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1809 if (update_head_ok)
1810 strvec_push(argv, "--update-head-ok");
1811 if (force)
1812 strvec_push(argv, "--force");
1813 if (keep)
1814 strvec_push(argv, "--keep");
1815 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1816 strvec_push(argv, "--recurse-submodules");
1817 else if (recurse_submodules == RECURSE_SUBMODULES_OFF)
1818 strvec_push(argv, "--no-recurse-submodules");
1819 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1820 strvec_push(argv, "--recurse-submodules=on-demand");
1821 if (tags == TAGS_SET)
1822 strvec_push(argv, "--tags");
1823 else if (tags == TAGS_UNSET)
1824 strvec_push(argv, "--no-tags");
1825 if (verbosity >= 2)
1826 strvec_push(argv, "-v");
1827 if (verbosity >= 1)
1828 strvec_push(argv, "-v");
1829 else if (verbosity < 0)
1830 strvec_push(argv, "-q");
1831 if (family == TRANSPORT_FAMILY_IPV4)
1832 strvec_push(argv, "--ipv4");
1833 else if (family == TRANSPORT_FAMILY_IPV6)
1834 strvec_push(argv, "--ipv6");
1835 if (!write_fetch_head)
1836 strvec_push(argv, "--no-write-fetch-head");
1839 /* Fetch multiple remotes in parallel */
1841 struct parallel_fetch_state {
1842 const char **argv;
1843 struct string_list *remotes;
1844 int next, result;
1847 static int fetch_next_remote(struct child_process *cp,
1848 struct strbuf *out UNUSED,
1849 void *cb, void **task_cb)
1851 struct parallel_fetch_state *state = cb;
1852 char *remote;
1854 if (state->next < 0 || state->next >= state->remotes->nr)
1855 return 0;
1857 remote = state->remotes->items[state->next++].string;
1858 *task_cb = remote;
1860 strvec_pushv(&cp->args, state->argv);
1861 strvec_push(&cp->args, remote);
1862 cp->git_cmd = 1;
1864 if (verbosity >= 0)
1865 printf(_("Fetching %s\n"), remote);
1867 return 1;
1870 static int fetch_failed_to_start(struct strbuf *out UNUSED,
1871 void *cb, void *task_cb)
1873 struct parallel_fetch_state *state = cb;
1874 const char *remote = task_cb;
1876 state->result = error(_("could not fetch %s"), remote);
1878 return 0;
1881 static int fetch_finished(int result, struct strbuf *out,
1882 void *cb, void *task_cb)
1884 struct parallel_fetch_state *state = cb;
1885 const char *remote = task_cb;
1887 if (result) {
1888 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1889 remote, result);
1890 state->result = -1;
1893 return 0;
1896 static int fetch_multiple(struct string_list *list, int max_children)
1898 int i, result = 0;
1899 struct strvec argv = STRVEC_INIT;
1901 if (!append && write_fetch_head) {
1902 int errcode = truncate_fetch_head();
1903 if (errcode)
1904 return errcode;
1908 * Cancel out the fetch.bundleURI config when running subprocesses,
1909 * to avoid fetching from the same bundle list multiple times.
1911 strvec_pushl(&argv, "-c", "fetch.bundleURI=",
1912 "fetch", "--append", "--no-auto-gc",
1913 "--no-write-commit-graph", NULL);
1914 add_options_to_argv(&argv);
1916 if (max_children != 1 && list->nr != 1) {
1917 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1918 const struct run_process_parallel_opts opts = {
1919 .tr2_category = "fetch",
1920 .tr2_label = "parallel/fetch",
1922 .processes = max_children,
1924 .get_next_task = &fetch_next_remote,
1925 .start_failure = &fetch_failed_to_start,
1926 .task_finished = &fetch_finished,
1927 .data = &state,
1930 strvec_push(&argv, "--end-of-options");
1932 run_processes_parallel(&opts);
1933 result = state.result;
1934 } else
1935 for (i = 0; i < list->nr; i++) {
1936 const char *name = list->items[i].string;
1937 struct child_process cmd = CHILD_PROCESS_INIT;
1939 strvec_pushv(&cmd.args, argv.v);
1940 strvec_push(&cmd.args, name);
1941 if (verbosity >= 0)
1942 printf(_("Fetching %s\n"), name);
1943 cmd.git_cmd = 1;
1944 if (run_command(&cmd)) {
1945 error(_("could not fetch %s"), name);
1946 result = 1;
1950 strvec_clear(&argv);
1951 return !!result;
1955 * Fetching from the promisor remote should use the given filter-spec
1956 * or inherit the default filter-spec from the config.
1958 static inline void fetch_one_setup_partial(struct remote *remote)
1961 * Explicit --no-filter argument overrides everything, regardless
1962 * of any prior partial clones and fetches.
1964 if (filter_options.no_filter)
1965 return;
1968 * If no prior partial clone/fetch and the current fetch DID NOT
1969 * request a partial-fetch, do a normal fetch.
1971 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
1972 return;
1975 * If this is a partial-fetch request, we enable partial on
1976 * this repo if not already enabled and remember the given
1977 * filter-spec as the default for subsequent fetches to this
1978 * remote if there is currently no default filter-spec.
1980 if (filter_options.choice) {
1981 partial_clone_register(remote->name, &filter_options);
1982 return;
1986 * Do a partial-fetch from the promisor remote using either the
1987 * explicitly given filter-spec or inherit the filter-spec from
1988 * the config.
1990 if (!filter_options.choice)
1991 partial_clone_get_default_filter_spec(&filter_options, remote->name);
1992 return;
1995 static int fetch_one(struct remote *remote, int argc, const char **argv,
1996 int prune_tags_ok, int use_stdin_refspecs,
1997 enum display_format display_format)
1999 struct refspec rs = REFSPEC_INIT_FETCH;
2000 int i;
2001 int exit_code;
2002 int maybe_prune_tags;
2003 int remote_via_config = remote_is_configured(remote, 0);
2005 if (!remote)
2006 die(_("no remote repository specified; please specify either a URL or a\n"
2007 "remote name from which new revisions should be fetched"));
2009 gtransport = prepare_transport(remote, 1);
2011 if (prune < 0) {
2012 /* no command line request */
2013 if (0 <= remote->prune)
2014 prune = remote->prune;
2015 else if (0 <= fetch_prune_config)
2016 prune = fetch_prune_config;
2017 else
2018 prune = PRUNE_BY_DEFAULT;
2021 if (prune_tags < 0) {
2022 /* no command line request */
2023 if (0 <= remote->prune_tags)
2024 prune_tags = remote->prune_tags;
2025 else if (0 <= fetch_prune_tags_config)
2026 prune_tags = fetch_prune_tags_config;
2027 else
2028 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2031 maybe_prune_tags = prune_tags_ok && prune_tags;
2032 if (maybe_prune_tags && remote_via_config)
2033 refspec_append(&remote->fetch, TAG_REFSPEC);
2035 if (maybe_prune_tags && (argc || !remote_via_config))
2036 refspec_append(&rs, TAG_REFSPEC);
2038 for (i = 0; i < argc; i++) {
2039 if (!strcmp(argv[i], "tag")) {
2040 i++;
2041 if (i >= argc)
2042 die(_("you need to specify a tag name"));
2044 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2045 argv[i], argv[i]);
2046 } else {
2047 refspec_append(&rs, argv[i]);
2051 if (use_stdin_refspecs) {
2052 struct strbuf line = STRBUF_INIT;
2053 while (strbuf_getline_lf(&line, stdin) != EOF)
2054 refspec_append(&rs, line.buf);
2055 strbuf_release(&line);
2058 if (server_options.nr)
2059 gtransport->server_options = &server_options;
2061 sigchain_push_common(unlock_pack_on_signal);
2062 atexit(unlock_pack_atexit);
2063 sigchain_push(SIGPIPE, SIG_IGN);
2064 exit_code = do_fetch(gtransport, &rs, display_format);
2065 sigchain_pop(SIGPIPE);
2066 refspec_clear(&rs);
2067 transport_disconnect(gtransport);
2068 gtransport = NULL;
2069 return exit_code;
2072 int cmd_fetch(int argc, const char **argv, const char *prefix)
2074 struct fetch_config config = {
2075 .display_format = DISPLAY_FORMAT_FULL,
2077 const char *submodule_prefix = "";
2078 const char *bundle_uri;
2079 struct string_list list = STRING_LIST_INIT_DUP;
2080 struct remote *remote = NULL;
2081 int all = 0, multiple = 0;
2082 int result = 0;
2083 int prune_tags_ok = 1;
2084 int enable_auto_gc = 1;
2085 int unshallow = 0;
2086 int max_jobs = -1;
2087 int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
2088 int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
2089 int fetch_write_commit_graph = -1;
2090 int stdin_refspecs = 0;
2091 int negotiate_only = 0;
2092 int i;
2094 struct option builtin_fetch_options[] = {
2095 OPT__VERBOSITY(&verbosity),
2096 OPT_BOOL(0, "all", &all,
2097 N_("fetch from all remotes")),
2098 OPT_BOOL(0, "set-upstream", &set_upstream,
2099 N_("set upstream for git pull/fetch")),
2100 OPT_BOOL('a', "append", &append,
2101 N_("append to .git/FETCH_HEAD instead of overwriting")),
2102 OPT_BOOL(0, "atomic", &atomic_fetch,
2103 N_("use atomic transaction to update references")),
2104 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
2105 N_("path to upload pack on remote end")),
2106 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
2107 OPT_BOOL('m', "multiple", &multiple,
2108 N_("fetch from multiple remotes")),
2109 OPT_SET_INT('t', "tags", &tags,
2110 N_("fetch all tags and associated objects"), TAGS_SET),
2111 OPT_SET_INT('n', NULL, &tags,
2112 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
2113 OPT_INTEGER('j', "jobs", &max_jobs,
2114 N_("number of submodules fetched in parallel")),
2115 OPT_BOOL(0, "prefetch", &prefetch,
2116 N_("modify the refspec to place all refs within refs/prefetch/")),
2117 OPT_BOOL('p', "prune", &prune,
2118 N_("prune remote-tracking branches no longer on remote")),
2119 OPT_BOOL('P', "prune-tags", &prune_tags,
2120 N_("prune local tags no longer on remote and clobber changed tags")),
2121 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
2122 N_("control recursive fetching of submodules"),
2123 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
2124 OPT_BOOL(0, "dry-run", &dry_run,
2125 N_("dry run")),
2126 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
2127 N_("write fetched references to the FETCH_HEAD file")),
2128 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
2129 OPT_BOOL('u', "update-head-ok", &update_head_ok,
2130 N_("allow updating of HEAD ref")),
2131 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
2132 OPT_STRING(0, "depth", &depth, N_("depth"),
2133 N_("deepen history of shallow clone")),
2134 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
2135 N_("deepen history of shallow repository based on time")),
2136 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
2137 N_("deepen history of shallow clone, excluding rev")),
2138 OPT_INTEGER(0, "deepen", &deepen_relative,
2139 N_("deepen history of shallow clone")),
2140 OPT_SET_INT_F(0, "unshallow", &unshallow,
2141 N_("convert to a complete repository"),
2142 1, PARSE_OPT_NONEG),
2143 OPT_SET_INT_F(0, "refetch", &refetch,
2144 N_("re-fetch without negotiating common commits"),
2145 1, PARSE_OPT_NONEG),
2146 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
2147 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
2148 OPT_CALLBACK_F(0, "recurse-submodules-default",
2149 &recurse_submodules_default, N_("on-demand"),
2150 N_("default for recursive fetching of submodules "
2151 "(lower priority than config files)"),
2152 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
2153 OPT_BOOL(0, "update-shallow", &update_shallow,
2154 N_("accept refs that update .git/shallow")),
2155 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
2156 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
2157 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
2158 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
2159 TRANSPORT_FAMILY_IPV4),
2160 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
2161 TRANSPORT_FAMILY_IPV6),
2162 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
2163 N_("report that we have only objects reachable from this object")),
2164 OPT_BOOL(0, "negotiate-only", &negotiate_only,
2165 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
2166 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
2167 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
2168 N_("run 'maintenance --auto' after fetching")),
2169 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
2170 N_("run 'maintenance --auto' after fetching")),
2171 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
2172 N_("check for forced-updates on all updated branches")),
2173 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
2174 N_("write the commit-graph after fetching")),
2175 OPT_BOOL(0, "stdin", &stdin_refspecs,
2176 N_("accept refspecs from stdin")),
2177 OPT_END()
2180 packet_trace_identity("fetch");
2182 /* Record the command line for the reflog */
2183 strbuf_addstr(&default_rla, "fetch");
2184 for (i = 1; i < argc; i++) {
2185 /* This handles non-URLs gracefully */
2186 char *anon = transport_anonymize_url(argv[i]);
2188 strbuf_addf(&default_rla, " %s", anon);
2189 free(anon);
2192 git_config(git_fetch_config, &config);
2193 if (the_repository->gitdir) {
2194 prepare_repo_settings(the_repository);
2195 the_repository->settings.command_requires_full_index = 0;
2198 argc = parse_options(argc, argv, prefix,
2199 builtin_fetch_options, builtin_fetch_usage, 0);
2201 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2202 recurse_submodules = recurse_submodules_cli;
2204 if (negotiate_only) {
2205 switch (recurse_submodules_cli) {
2206 case RECURSE_SUBMODULES_OFF:
2207 case RECURSE_SUBMODULES_DEFAULT:
2209 * --negotiate-only should never recurse into
2210 * submodules. Skip it by setting recurse_submodules to
2211 * RECURSE_SUBMODULES_OFF.
2213 recurse_submodules = RECURSE_SUBMODULES_OFF;
2214 break;
2216 default:
2217 die(_("options '%s' and '%s' cannot be used together"),
2218 "--negotiate-only", "--recurse-submodules");
2222 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2223 int *sfjc = submodule_fetch_jobs_config == -1
2224 ? &submodule_fetch_jobs_config : NULL;
2225 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2226 ? &recurse_submodules : NULL;
2228 fetch_config_from_gitmodules(sfjc, rs);
2231 if (negotiate_only && !negotiation_tip.nr)
2232 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2234 if (deepen_relative) {
2235 if (deepen_relative < 0)
2236 die(_("negative depth in --deepen is not supported"));
2237 if (depth)
2238 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2239 depth = xstrfmt("%d", deepen_relative);
2241 if (unshallow) {
2242 if (depth)
2243 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2244 else if (!is_repository_shallow(the_repository))
2245 die(_("--unshallow on a complete repository does not make sense"));
2246 else
2247 depth = xstrfmt("%d", INFINITE_DEPTH);
2250 /* no need to be strict, transport_set_option() will validate it again */
2251 if (depth && atoi(depth) < 1)
2252 die(_("depth %s is not a positive number"), depth);
2253 if (depth || deepen_since || deepen_not.nr)
2254 deepen = 1;
2256 /* FETCH_HEAD never gets updated in --dry-run mode */
2257 if (dry_run)
2258 write_fetch_head = 0;
2260 if (!max_jobs)
2261 max_jobs = online_cpus();
2263 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2264 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2265 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2267 if (all) {
2268 if (argc == 1)
2269 die(_("fetch --all does not take a repository argument"));
2270 else if (argc > 1)
2271 die(_("fetch --all does not make sense with refspecs"));
2272 (void) for_each_remote(get_one_remote_for_fetch, &list);
2274 /* do not do fetch_multiple() of one */
2275 if (list.nr == 1)
2276 remote = remote_get(list.items[0].string);
2277 } else if (argc == 0) {
2278 /* No arguments -- use default remote */
2279 remote = remote_get(NULL);
2280 } else if (multiple) {
2281 /* All arguments are assumed to be remotes or groups */
2282 for (i = 0; i < argc; i++)
2283 if (!add_remote_or_group(argv[i], &list))
2284 die(_("no such remote or remote group: %s"),
2285 argv[i]);
2286 } else {
2287 /* Single remote or group */
2288 (void) add_remote_or_group(argv[0], &list);
2289 if (list.nr > 1) {
2290 /* More than one remote */
2291 if (argc > 1)
2292 die(_("fetching a group and specifying refspecs does not make sense"));
2293 } else {
2294 /* Zero or one remotes */
2295 remote = remote_get(argv[0]);
2296 prune_tags_ok = (argc == 1);
2297 argc--;
2298 argv++;
2301 string_list_remove_duplicates(&list, 0);
2303 if (negotiate_only) {
2304 struct oidset acked_commits = OIDSET_INIT;
2305 struct oidset_iter iter;
2306 const struct object_id *oid;
2308 if (!remote)
2309 die(_("must supply remote when using --negotiate-only"));
2310 gtransport = prepare_transport(remote, 1);
2311 if (gtransport->smart_options) {
2312 gtransport->smart_options->acked_commits = &acked_commits;
2313 } else {
2314 warning(_("protocol does not support --negotiate-only, exiting"));
2315 result = 1;
2316 goto cleanup;
2318 if (server_options.nr)
2319 gtransport->server_options = &server_options;
2320 result = transport_fetch_refs(gtransport, NULL);
2322 oidset_iter_init(&acked_commits, &iter);
2323 while ((oid = oidset_iter_next(&iter)))
2324 printf("%s\n", oid_to_hex(oid));
2325 oidset_clear(&acked_commits);
2326 } else if (remote) {
2327 if (filter_options.choice || repo_has_promisor_remote(the_repository))
2328 fetch_one_setup_partial(remote);
2329 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs,
2330 config.display_format);
2331 } else {
2332 int max_children = max_jobs;
2334 if (filter_options.choice)
2335 die(_("--filter can only be used with the remote "
2336 "configured in extensions.partialclone"));
2338 if (atomic_fetch)
2339 die(_("--atomic can only be used when fetching "
2340 "from one remote"));
2342 if (stdin_refspecs)
2343 die(_("--stdin can only be used when fetching "
2344 "from one remote"));
2346 if (max_children < 0)
2347 max_children = fetch_parallel_config;
2349 /* TODO should this also die if we have a previous partial-clone? */
2350 result = fetch_multiple(&list, max_children);
2355 * This is only needed after fetch_one(), which does not fetch
2356 * submodules by itself.
2358 * When we fetch from multiple remotes, fetch_multiple() has
2359 * already updated submodules to grab commits necessary for
2360 * the fetched history from each remote, so there is no need
2361 * to fetch submodules from here.
2363 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2364 struct strvec options = STRVEC_INIT;
2365 int max_children = max_jobs;
2367 if (max_children < 0)
2368 max_children = submodule_fetch_jobs_config;
2369 if (max_children < 0)
2370 max_children = fetch_parallel_config;
2372 add_options_to_argv(&options);
2373 result = fetch_submodules(the_repository,
2374 &options,
2375 submodule_prefix,
2376 recurse_submodules,
2377 recurse_submodules_default,
2378 verbosity < 0,
2379 max_children);
2380 strvec_clear(&options);
2384 * Skip irrelevant tasks because we know objects were not
2385 * fetched.
2387 * NEEDSWORK: as a future optimization, we can return early
2388 * whenever objects were not fetched e.g. if we already have all
2389 * of them.
2391 if (negotiate_only)
2392 goto cleanup;
2394 prepare_repo_settings(the_repository);
2395 if (fetch_write_commit_graph > 0 ||
2396 (fetch_write_commit_graph < 0 &&
2397 the_repository->settings.fetch_write_commit_graph)) {
2398 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2400 if (progress)
2401 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2403 write_commit_graph_reachable(the_repository->objects->odb,
2404 commit_graph_flags,
2405 NULL);
2408 if (enable_auto_gc) {
2409 if (refetch) {
2411 * Hint auto-maintenance strongly to encourage repacking,
2412 * but respect config settings disabling it.
2414 int opt_val;
2415 if (git_config_get_int("gc.autopacklimit", &opt_val))
2416 opt_val = -1;
2417 if (opt_val != 0)
2418 git_config_push_parameter("gc.autoPackLimit=1");
2420 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2421 opt_val = -1;
2422 if (opt_val != 0)
2423 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2425 run_auto_maintenance(verbosity < 0);
2428 cleanup:
2429 string_list_clear(&list, 0);
2430 return result;