upload-pack: drop separate v2 "haves" array
[alt-git.git] / builtin / fetch.c
blob3aedfd1bb6361c6bbfd651970f9e9767d0595734
1 /*
2 * "git fetch"
3 */
4 #include "builtin.h"
5 #include "advice.h"
6 #include "config.h"
7 #include "gettext.h"
8 #include "environment.h"
9 #include "hex.h"
10 #include "repository.h"
11 #include "refs.h"
12 #include "refspec.h"
13 #include "object-name.h"
14 #include "object-store-ll.h"
15 #include "oidset.h"
16 #include "oid-array.h"
17 #include "commit.h"
18 #include "string-list.h"
19 #include "remote.h"
20 #include "transport.h"
21 #include "run-command.h"
22 #include "parse-options.h"
23 #include "sigchain.h"
24 #include "submodule-config.h"
25 #include "submodule.h"
26 #include "connected.h"
27 #include "strvec.h"
28 #include "utf8.h"
29 #include "pager.h"
30 #include "path.h"
31 #include "pkt-line.h"
32 #include "list-objects-filter-options.h"
33 #include "commit-reach.h"
34 #include "branch.h"
35 #include "promisor-remote.h"
36 #include "commit-graph.h"
37 #include "shallow.h"
38 #include "trace.h"
39 #include "trace2.h"
40 #include "bundle-uri.h"
42 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
44 static const char * const builtin_fetch_usage[] = {
45 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
46 N_("git fetch [<options>] <group>"),
47 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
48 N_("git fetch --all [<options>]"),
49 NULL
52 enum {
53 TAGS_UNSET = 0,
54 TAGS_DEFAULT = 1,
55 TAGS_SET = 2
58 enum display_format {
59 DISPLAY_FORMAT_FULL,
60 DISPLAY_FORMAT_COMPACT,
61 DISPLAY_FORMAT_PORCELAIN,
64 struct display_state {
65 struct strbuf buf;
67 int refcol_width;
68 enum display_format format;
70 char *url;
71 int url_len, shown_url;
74 static uint64_t forced_updates_ms = 0;
75 static int prefetch = 0;
76 static int prune = -1; /* unspecified */
77 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
79 static int prune_tags = -1; /* unspecified */
80 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
82 static int append, dry_run, force, keep, update_head_ok;
83 static int write_fetch_head = 1;
84 static int verbosity, deepen_relative, set_upstream, refetch;
85 static int progress = -1;
86 static int tags = TAGS_DEFAULT, update_shallow, deepen;
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 struct refspec refmap = REFSPEC_INIT_FETCH;
97 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
98 static struct string_list server_options = STRING_LIST_INIT_DUP;
99 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
101 struct fetch_config {
102 enum display_format display_format;
103 int all;
104 int prune;
105 int prune_tags;
106 int show_forced_updates;
107 int recurse_submodules;
108 int parallel;
109 int submodule_fetch_jobs;
112 static int git_fetch_config(const char *k, const char *v,
113 const struct config_context *ctx, void *cb)
115 struct fetch_config *fetch_config = cb;
117 if (!strcmp(k, "fetch.all")) {
118 fetch_config->all = git_config_bool(k, v);
119 return 0;
122 if (!strcmp(k, "fetch.prune")) {
123 fetch_config->prune = git_config_bool(k, v);
124 return 0;
127 if (!strcmp(k, "fetch.prunetags")) {
128 fetch_config->prune_tags = git_config_bool(k, v);
129 return 0;
132 if (!strcmp(k, "fetch.showforcedupdates")) {
133 fetch_config->show_forced_updates = git_config_bool(k, v);
134 return 0;
137 if (!strcmp(k, "submodule.recurse")) {
138 int r = git_config_bool(k, v) ?
139 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
140 fetch_config->recurse_submodules = r;
143 if (!strcmp(k, "submodule.fetchjobs")) {
144 fetch_config->submodule_fetch_jobs = parse_submodule_fetchjobs(k, v, ctx->kvi);
145 return 0;
146 } else if (!strcmp(k, "fetch.recursesubmodules")) {
147 fetch_config->recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
148 return 0;
151 if (!strcmp(k, "fetch.parallel")) {
152 fetch_config->parallel = git_config_int(k, v, ctx->kvi);
153 if (fetch_config->parallel < 0)
154 die(_("fetch.parallel cannot be negative"));
155 if (!fetch_config->parallel)
156 fetch_config->parallel = online_cpus();
157 return 0;
160 if (!strcmp(k, "fetch.output")) {
161 if (!v)
162 return config_error_nonbool(k);
163 else if (!strcasecmp(v, "full"))
164 fetch_config->display_format = DISPLAY_FORMAT_FULL;
165 else if (!strcasecmp(v, "compact"))
166 fetch_config->display_format = DISPLAY_FORMAT_COMPACT;
167 else
168 die(_("invalid value for '%s': '%s'"),
169 "fetch.output", v);
172 return git_default_config(k, v, ctx, cb);
175 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
177 BUG_ON_OPT_NEG(unset);
180 * "git fetch --refmap='' origin foo"
181 * can be used to tell the command not to store anywhere
183 refspec_append(opt->value, arg);
185 return 0;
188 static void unlock_pack(unsigned int flags)
190 if (gtransport)
191 transport_unlock_pack(gtransport, flags);
192 if (gsecondary)
193 transport_unlock_pack(gsecondary, flags);
196 static void unlock_pack_atexit(void)
198 unlock_pack(0);
201 static void unlock_pack_on_signal(int signo)
203 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
204 sigchain_pop(signo);
205 raise(signo);
208 static void add_merge_config(struct ref **head,
209 const struct ref *remote_refs,
210 struct branch *branch,
211 struct ref ***tail)
213 int i;
215 for (i = 0; i < branch->merge_nr; i++) {
216 struct ref *rm, **old_tail = *tail;
217 struct refspec_item refspec;
219 for (rm = *head; rm; rm = rm->next) {
220 if (branch_merge_matches(branch, i, rm->name)) {
221 rm->fetch_head_status = FETCH_HEAD_MERGE;
222 break;
225 if (rm)
226 continue;
229 * Not fetched to a remote-tracking branch? We need to fetch
230 * it anyway to allow this branch's "branch.$name.merge"
231 * to be honored by 'git pull', but we do not have to
232 * fail if branch.$name.merge is misconfigured to point
233 * at a nonexisting branch. If we were indeed called by
234 * 'git pull', it will notice the misconfiguration because
235 * there is no entry in the resulting FETCH_HEAD marked
236 * for merging.
238 memset(&refspec, 0, sizeof(refspec));
239 refspec.src = branch->merge[i]->src;
240 get_fetch_map(remote_refs, &refspec, tail, 1);
241 for (rm = *old_tail; rm; rm = rm->next)
242 rm->fetch_head_status = FETCH_HEAD_MERGE;
246 static void create_fetch_oidset(struct ref **head, struct oidset *out)
248 struct ref *rm = *head;
249 while (rm) {
250 oidset_insert(out, &rm->old_oid);
251 rm = rm->next;
255 struct refname_hash_entry {
256 struct hashmap_entry ent;
257 struct object_id oid;
258 int ignore;
259 char refname[FLEX_ARRAY];
262 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
263 const struct hashmap_entry *eptr,
264 const struct hashmap_entry *entry_or_key,
265 const void *keydata)
267 const struct refname_hash_entry *e1, *e2;
269 e1 = container_of(eptr, const struct refname_hash_entry, ent);
270 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
271 return strcmp(e1->refname, keydata ? keydata : e2->refname);
274 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
275 const char *refname,
276 const struct object_id *oid)
278 struct refname_hash_entry *ent;
279 size_t len = strlen(refname);
281 FLEX_ALLOC_MEM(ent, refname, refname, len);
282 hashmap_entry_init(&ent->ent, strhash(refname));
283 oidcpy(&ent->oid, oid);
284 hashmap_add(map, &ent->ent);
285 return ent;
288 static int add_one_refname(const char *refname,
289 const struct object_id *oid,
290 int flag UNUSED, void *cbdata)
292 struct hashmap *refname_map = cbdata;
294 (void) refname_hash_add(refname_map, refname, oid);
295 return 0;
298 static void refname_hash_init(struct hashmap *map)
300 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
303 static int refname_hash_exists(struct hashmap *map, const char *refname)
305 return !!hashmap_get_from_hash(map, strhash(refname), refname);
308 static void clear_item(struct refname_hash_entry *item)
310 item->ignore = 1;
314 static void add_already_queued_tags(const char *refname,
315 const struct object_id *old_oid UNUSED,
316 const struct object_id *new_oid,
317 void *cb_data)
319 struct hashmap *queued_tags = cb_data;
320 if (starts_with(refname, "refs/tags/") && new_oid)
321 (void) refname_hash_add(queued_tags, refname, new_oid);
324 static void find_non_local_tags(const struct ref *refs,
325 struct ref_transaction *transaction,
326 struct ref **head,
327 struct ref ***tail)
329 struct hashmap existing_refs;
330 struct hashmap remote_refs;
331 struct oidset fetch_oids = OIDSET_INIT;
332 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
333 struct string_list_item *remote_ref_item;
334 const struct ref *ref;
335 struct refname_hash_entry *item = NULL;
336 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
338 refname_hash_init(&existing_refs);
339 refname_hash_init(&remote_refs);
340 create_fetch_oidset(head, &fetch_oids);
342 for_each_ref(add_one_refname, &existing_refs);
345 * If we already have a transaction, then we need to filter out all
346 * tags which have already been queued up.
348 if (transaction)
349 ref_transaction_for_each_queued_update(transaction,
350 add_already_queued_tags,
351 &existing_refs);
353 for (ref = refs; ref; ref = ref->next) {
354 if (!starts_with(ref->name, "refs/tags/"))
355 continue;
358 * The peeled ref always follows the matching base
359 * ref, so if we see a peeled ref that we don't want
360 * to fetch then we can mark the ref entry in the list
361 * as one to ignore by setting util to NULL.
363 if (ends_with(ref->name, "^{}")) {
364 if (item &&
365 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
366 !oidset_contains(&fetch_oids, &ref->old_oid) &&
367 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
368 !oidset_contains(&fetch_oids, &item->oid))
369 clear_item(item);
370 item = NULL;
371 continue;
375 * If item is non-NULL here, then we previously saw a
376 * ref not followed by a peeled reference, so we need
377 * to check if it is a lightweight tag that we want to
378 * fetch.
380 if (item &&
381 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
382 !oidset_contains(&fetch_oids, &item->oid))
383 clear_item(item);
385 item = NULL;
387 /* skip duplicates and refs that we already have */
388 if (refname_hash_exists(&remote_refs, ref->name) ||
389 refname_hash_exists(&existing_refs, ref->name))
390 continue;
392 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
393 string_list_insert(&remote_refs_list, ref->name);
395 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
398 * We may have a final lightweight tag that needs to be
399 * checked to see if it needs fetching.
401 if (item &&
402 !repo_has_object_file_with_flags(the_repository, &item->oid, quick_flags) &&
403 !oidset_contains(&fetch_oids, &item->oid))
404 clear_item(item);
407 * For all the tags in the remote_refs_list,
408 * add them to the list of refs to be fetched
410 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
411 const char *refname = remote_ref_item->string;
412 struct ref *rm;
413 unsigned int hash = strhash(refname);
415 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
416 struct refname_hash_entry, ent);
417 if (!item)
418 BUG("unseen remote ref?");
420 /* Unless we have already decided to ignore this item... */
421 if (item->ignore)
422 continue;
424 rm = alloc_ref(item->refname);
425 rm->peer_ref = alloc_ref(item->refname);
426 oidcpy(&rm->old_oid, &item->oid);
427 **tail = rm;
428 *tail = &rm->next;
430 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
431 string_list_clear(&remote_refs_list, 0);
432 oidset_clear(&fetch_oids);
435 static void filter_prefetch_refspec(struct refspec *rs)
437 int i;
439 if (!prefetch)
440 return;
442 for (i = 0; i < rs->nr; i++) {
443 struct strbuf new_dst = STRBUF_INIT;
444 char *old_dst;
445 const char *sub = NULL;
447 if (rs->items[i].negative)
448 continue;
449 if (!rs->items[i].dst ||
450 (rs->items[i].src &&
451 !strncmp(rs->items[i].src,
452 ref_namespace[NAMESPACE_TAGS].ref,
453 strlen(ref_namespace[NAMESPACE_TAGS].ref)))) {
454 int j;
456 free(rs->items[i].src);
457 free(rs->items[i].dst);
459 for (j = i + 1; j < rs->nr; j++) {
460 rs->items[j - 1] = rs->items[j];
461 rs->raw[j - 1] = rs->raw[j];
463 rs->nr--;
464 i--;
465 continue;
468 old_dst = rs->items[i].dst;
469 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
472 * If old_dst starts with "refs/", then place
473 * sub after that prefix. Otherwise, start at
474 * the beginning of the string.
476 if (!skip_prefix(old_dst, "refs/", &sub))
477 sub = old_dst;
478 strbuf_addstr(&new_dst, sub);
480 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
481 rs->items[i].force = 1;
483 free(old_dst);
487 static struct ref *get_ref_map(struct remote *remote,
488 const struct ref *remote_refs,
489 struct refspec *rs,
490 int tags, int *autotags)
492 int i;
493 struct ref *rm;
494 struct ref *ref_map = NULL;
495 struct ref **tail = &ref_map;
497 /* opportunistically-updated references: */
498 struct ref *orefs = NULL, **oref_tail = &orefs;
500 struct hashmap existing_refs;
501 int existing_refs_populated = 0;
503 filter_prefetch_refspec(rs);
504 if (remote)
505 filter_prefetch_refspec(&remote->fetch);
507 if (rs->nr) {
508 struct refspec *fetch_refspec;
510 for (i = 0; i < rs->nr; i++) {
511 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
512 if (rs->items[i].dst && rs->items[i].dst[0])
513 *autotags = 1;
515 /* Merge everything on the command line (but not --tags) */
516 for (rm = ref_map; rm; rm = rm->next)
517 rm->fetch_head_status = FETCH_HEAD_MERGE;
520 * For any refs that we happen to be fetching via
521 * command-line arguments, the destination ref might
522 * have been missing or have been different than the
523 * remote-tracking ref that would be derived from the
524 * configured refspec. In these cases, we want to
525 * take the opportunity to update their configured
526 * remote-tracking reference. However, we do not want
527 * to mention these entries in FETCH_HEAD at all, as
528 * they would simply be duplicates of existing
529 * entries, so we set them FETCH_HEAD_IGNORE below.
531 * We compute these entries now, based only on the
532 * refspecs specified on the command line. But we add
533 * them to the list following the refspecs resulting
534 * from the tags option so that one of the latter,
535 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
536 * by ref_remove_duplicates() in favor of one of these
537 * opportunistic entries with FETCH_HEAD_IGNORE.
539 if (refmap.nr)
540 fetch_refspec = &refmap;
541 else
542 fetch_refspec = &remote->fetch;
544 for (i = 0; i < fetch_refspec->nr; i++)
545 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
546 } else if (refmap.nr) {
547 die("--refmap option is only meaningful with command-line refspec(s)");
548 } else {
549 /* Use the defaults */
550 struct branch *branch = branch_get(NULL);
551 int has_merge = branch_has_merge_config(branch);
552 if (remote &&
553 (remote->fetch.nr ||
554 /* Note: has_merge implies non-NULL branch->remote_name */
555 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
556 for (i = 0; i < remote->fetch.nr; i++) {
557 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
558 if (remote->fetch.items[i].dst &&
559 remote->fetch.items[i].dst[0])
560 *autotags = 1;
561 if (!i && !has_merge && ref_map &&
562 !remote->fetch.items[0].pattern)
563 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
566 * if the remote we're fetching from is the same
567 * as given in branch.<name>.remote, we add the
568 * ref given in branch.<name>.merge, too.
570 * Note: has_merge implies non-NULL branch->remote_name
572 if (has_merge &&
573 !strcmp(branch->remote_name, remote->name))
574 add_merge_config(&ref_map, remote_refs, branch, &tail);
575 } else if (!prefetch) {
576 ref_map = get_remote_ref(remote_refs, "HEAD");
577 if (!ref_map)
578 die(_("couldn't find remote ref HEAD"));
579 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
580 tail = &ref_map->next;
584 if (tags == TAGS_SET)
585 /* also fetch all tags */
586 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
587 else if (tags == TAGS_DEFAULT && *autotags)
588 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
590 /* Now append any refs to be updated opportunistically: */
591 *tail = orefs;
592 for (rm = orefs; rm; rm = rm->next) {
593 rm->fetch_head_status = FETCH_HEAD_IGNORE;
594 tail = &rm->next;
598 * apply negative refspecs first, before we remove duplicates. This is
599 * necessary as negative refspecs might remove an otherwise conflicting
600 * duplicate.
602 if (rs->nr)
603 ref_map = apply_negative_refspecs(ref_map, rs);
604 else
605 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
607 ref_map = ref_remove_duplicates(ref_map);
609 for (rm = ref_map; rm; rm = rm->next) {
610 if (rm->peer_ref) {
611 const char *refname = rm->peer_ref->name;
612 struct refname_hash_entry *peer_item;
613 unsigned int hash = strhash(refname);
615 if (!existing_refs_populated) {
616 refname_hash_init(&existing_refs);
617 for_each_ref(add_one_refname, &existing_refs);
618 existing_refs_populated = 1;
621 peer_item = hashmap_get_entry_from_hash(&existing_refs,
622 hash, refname,
623 struct refname_hash_entry, ent);
624 if (peer_item) {
625 struct object_id *old_oid = &peer_item->oid;
626 oidcpy(&rm->peer_ref->old_oid, old_oid);
630 if (existing_refs_populated)
631 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
633 return ref_map;
636 #define STORE_REF_ERROR_OTHER 1
637 #define STORE_REF_ERROR_DF_CONFLICT 2
639 static int s_update_ref(const char *action,
640 struct ref *ref,
641 struct ref_transaction *transaction,
642 int check_old)
644 char *msg;
645 char *rla = getenv("GIT_REFLOG_ACTION");
646 struct ref_transaction *our_transaction = NULL;
647 struct strbuf err = STRBUF_INIT;
648 int ret;
650 if (dry_run)
651 return 0;
652 if (!rla)
653 rla = default_rla.buf;
654 msg = xstrfmt("%s: %s", rla, action);
657 * If no transaction was passed to us, we manage the transaction
658 * ourselves. Otherwise, we trust the caller to handle the transaction
659 * lifecycle.
661 if (!transaction) {
662 transaction = our_transaction = ref_transaction_begin(&err);
663 if (!transaction) {
664 ret = STORE_REF_ERROR_OTHER;
665 goto out;
669 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
670 check_old ? &ref->old_oid : NULL,
671 0, msg, &err);
672 if (ret) {
673 ret = STORE_REF_ERROR_OTHER;
674 goto out;
677 if (our_transaction) {
678 switch (ref_transaction_commit(our_transaction, &err)) {
679 case 0:
680 break;
681 case TRANSACTION_NAME_CONFLICT:
682 ret = STORE_REF_ERROR_DF_CONFLICT;
683 goto out;
684 default:
685 ret = STORE_REF_ERROR_OTHER;
686 goto out;
690 out:
691 ref_transaction_free(our_transaction);
692 if (ret)
693 error("%s", err.buf);
694 strbuf_release(&err);
695 free(msg);
696 return ret;
699 static int refcol_width(const struct ref *ref_map, int compact_format)
701 const struct ref *ref;
702 int max, width = 10;
704 max = term_columns();
705 if (compact_format)
706 max = max * 2 / 3;
708 for (ref = ref_map; ref; ref = ref->next) {
709 int rlen, llen = 0, len;
711 if (ref->status == REF_STATUS_REJECT_SHALLOW ||
712 !ref->peer_ref ||
713 !strcmp(ref->name, "HEAD"))
714 continue;
716 /* uptodate lines are only shown on high verbosity level */
717 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
718 continue;
720 rlen = utf8_strwidth(prettify_refname(ref->name));
721 if (!compact_format)
722 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
725 * rough estimation to see if the output line is too long and
726 * should not be counted (we can't do precise calculation
727 * anyway because we don't know if the error explanation part
728 * will be printed in update_local_ref)
730 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
731 if (len >= max)
732 continue;
734 if (width < rlen)
735 width = rlen;
738 return width;
741 static void display_state_init(struct display_state *display_state, struct ref *ref_map,
742 const char *raw_url, enum display_format format)
744 int i;
746 memset(display_state, 0, sizeof(*display_state));
747 strbuf_init(&display_state->buf, 0);
748 display_state->format = format;
750 if (raw_url)
751 display_state->url = transport_anonymize_url(raw_url);
752 else
753 display_state->url = xstrdup("foreign");
755 display_state->url_len = strlen(display_state->url);
756 for (i = display_state->url_len - 1; display_state->url[i] == '/' && 0 <= i; i--)
758 display_state->url_len = i + 1;
759 if (4 < i && !strncmp(".git", display_state->url + i - 3, 4))
760 display_state->url_len = i - 3;
762 if (verbosity < 0)
763 return;
765 switch (display_state->format) {
766 case DISPLAY_FORMAT_FULL:
767 case DISPLAY_FORMAT_COMPACT:
768 display_state->refcol_width = refcol_width(ref_map,
769 display_state->format == DISPLAY_FORMAT_COMPACT);
770 break;
771 case DISPLAY_FORMAT_PORCELAIN:
772 /* We don't need to precompute anything here. */
773 break;
774 default:
775 BUG("unexpected display format %d", display_state->format);
779 static void display_state_release(struct display_state *display_state)
781 strbuf_release(&display_state->buf);
782 free(display_state->url);
785 static void print_remote_to_local(struct display_state *display_state,
786 const char *remote, const char *local)
788 strbuf_addf(&display_state->buf, "%-*s -> %s",
789 display_state->refcol_width, remote, local);
792 static int find_and_replace(struct strbuf *haystack,
793 const char *needle,
794 const char *placeholder)
796 const char *p = NULL;
797 int plen, nlen;
799 nlen = strlen(needle);
800 if (ends_with(haystack->buf, needle))
801 p = haystack->buf + haystack->len - nlen;
802 else
803 p = strstr(haystack->buf, needle);
804 if (!p)
805 return 0;
807 if (p > haystack->buf && p[-1] != '/')
808 return 0;
810 plen = strlen(p);
811 if (plen > nlen && p[nlen] != '/')
812 return 0;
814 strbuf_splice(haystack, p - haystack->buf, nlen,
815 placeholder, strlen(placeholder));
816 return 1;
819 static void print_compact(struct display_state *display_state,
820 const char *remote, const char *local)
822 struct strbuf r = STRBUF_INIT;
823 struct strbuf l = STRBUF_INIT;
825 if (!strcmp(remote, local)) {
826 strbuf_addf(&display_state->buf, "%-*s -> *", display_state->refcol_width, remote);
827 return;
830 strbuf_addstr(&r, remote);
831 strbuf_addstr(&l, local);
833 if (!find_and_replace(&r, local, "*"))
834 find_and_replace(&l, remote, "*");
835 print_remote_to_local(display_state, r.buf, l.buf);
837 strbuf_release(&r);
838 strbuf_release(&l);
841 static void display_ref_update(struct display_state *display_state, char code,
842 const char *summary, const char *error,
843 const char *remote, const char *local,
844 const struct object_id *old_oid,
845 const struct object_id *new_oid,
846 int summary_width)
848 FILE *f = stderr;
850 if (verbosity < 0)
851 return;
853 strbuf_reset(&display_state->buf);
855 switch (display_state->format) {
856 case DISPLAY_FORMAT_FULL:
857 case DISPLAY_FORMAT_COMPACT: {
858 int width;
860 if (!display_state->shown_url) {
861 strbuf_addf(&display_state->buf, _("From %.*s\n"),
862 display_state->url_len, display_state->url);
863 display_state->shown_url = 1;
866 width = (summary_width + strlen(summary) - gettext_width(summary));
867 remote = prettify_refname(remote);
868 local = prettify_refname(local);
870 strbuf_addf(&display_state->buf, " %c %-*s ", code, width, summary);
872 if (display_state->format != DISPLAY_FORMAT_COMPACT)
873 print_remote_to_local(display_state, remote, local);
874 else
875 print_compact(display_state, remote, local);
877 if (error)
878 strbuf_addf(&display_state->buf, " (%s)", error);
880 break;
882 case DISPLAY_FORMAT_PORCELAIN:
883 strbuf_addf(&display_state->buf, "%c %s %s %s", code,
884 oid_to_hex(old_oid), oid_to_hex(new_oid), local);
885 f = stdout;
886 break;
887 default:
888 BUG("unexpected display format %d", display_state->format);
890 strbuf_addch(&display_state->buf, '\n');
892 fputs(display_state->buf.buf, f);
895 static int update_local_ref(struct ref *ref,
896 struct ref_transaction *transaction,
897 struct display_state *display_state,
898 const struct ref *remote_ref,
899 int summary_width,
900 const struct fetch_config *config)
902 struct commit *current = NULL, *updated;
903 int fast_forward = 0;
905 if (!repo_has_object_file(the_repository, &ref->new_oid))
906 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
908 if (oideq(&ref->old_oid, &ref->new_oid)) {
909 if (verbosity > 0)
910 display_ref_update(display_state, '=', _("[up to date]"), NULL,
911 remote_ref->name, ref->name,
912 &ref->old_oid, &ref->new_oid, summary_width);
913 return 0;
916 if (!update_head_ok &&
917 !is_null_oid(&ref->old_oid) &&
918 branch_checked_out(ref->name)) {
920 * If this is the head, and it's not okay to update
921 * the head, and the old value of the head isn't empty...
923 display_ref_update(display_state, '!', _("[rejected]"),
924 _("can't fetch into checked-out branch"),
925 remote_ref->name, ref->name,
926 &ref->old_oid, &ref->new_oid, summary_width);
927 return 1;
930 if (!is_null_oid(&ref->old_oid) &&
931 starts_with(ref->name, "refs/tags/")) {
932 if (force || ref->force) {
933 int r;
934 r = s_update_ref("updating tag", ref, transaction, 0);
935 display_ref_update(display_state, r ? '!' : 't', _("[tag update]"),
936 r ? _("unable to update local ref") : NULL,
937 remote_ref->name, ref->name,
938 &ref->old_oid, &ref->new_oid, summary_width);
939 return r;
940 } else {
941 display_ref_update(display_state, '!', _("[rejected]"),
942 _("would clobber existing tag"),
943 remote_ref->name, ref->name,
944 &ref->old_oid, &ref->new_oid, summary_width);
945 return 1;
949 current = lookup_commit_reference_gently(the_repository,
950 &ref->old_oid, 1);
951 updated = lookup_commit_reference_gently(the_repository,
952 &ref->new_oid, 1);
953 if (!current || !updated) {
954 const char *msg;
955 const char *what;
956 int r;
958 * Nicely describe the new ref we're fetching.
959 * Base this on the remote's ref name, as it's
960 * more likely to follow a standard layout.
962 if (starts_with(remote_ref->name, "refs/tags/")) {
963 msg = "storing tag";
964 what = _("[new tag]");
965 } else if (starts_with(remote_ref->name, "refs/heads/")) {
966 msg = "storing head";
967 what = _("[new branch]");
968 } else {
969 msg = "storing ref";
970 what = _("[new ref]");
973 r = s_update_ref(msg, ref, transaction, 0);
974 display_ref_update(display_state, r ? '!' : '*', what,
975 r ? _("unable to update local ref") : NULL,
976 remote_ref->name, ref->name,
977 &ref->old_oid, &ref->new_oid, summary_width);
978 return r;
981 if (config->show_forced_updates) {
982 uint64_t t_before = getnanotime();
983 fast_forward = repo_in_merge_bases(the_repository, current,
984 updated);
985 forced_updates_ms += (getnanotime() - t_before) / 1000000;
986 } else {
987 fast_forward = 1;
990 if (fast_forward) {
991 struct strbuf quickref = STRBUF_INIT;
992 int r;
994 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
995 strbuf_addstr(&quickref, "..");
996 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
997 r = s_update_ref("fast-forward", ref, transaction, 1);
998 display_ref_update(display_state, r ? '!' : ' ', quickref.buf,
999 r ? _("unable to update local ref") : NULL,
1000 remote_ref->name, ref->name,
1001 &ref->old_oid, &ref->new_oid, summary_width);
1002 strbuf_release(&quickref);
1003 return r;
1004 } else if (force || ref->force) {
1005 struct strbuf quickref = STRBUF_INIT;
1006 int r;
1007 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1008 strbuf_addstr(&quickref, "...");
1009 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1010 r = s_update_ref("forced-update", ref, transaction, 1);
1011 display_ref_update(display_state, r ? '!' : '+', quickref.buf,
1012 r ? _("unable to update local ref") : _("forced update"),
1013 remote_ref->name, ref->name,
1014 &ref->old_oid, &ref->new_oid, summary_width);
1015 strbuf_release(&quickref);
1016 return r;
1017 } else {
1018 display_ref_update(display_state, '!', _("[rejected]"), _("non-fast-forward"),
1019 remote_ref->name, ref->name,
1020 &ref->old_oid, &ref->new_oid, summary_width);
1021 return 1;
1025 static const struct object_id *iterate_ref_map(void *cb_data)
1027 struct ref **rm = cb_data;
1028 struct ref *ref = *rm;
1030 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1031 ref = ref->next;
1032 if (!ref)
1033 return NULL;
1034 *rm = ref->next;
1035 return &ref->old_oid;
1038 struct fetch_head {
1039 FILE *fp;
1040 struct strbuf buf;
1043 static int open_fetch_head(struct fetch_head *fetch_head)
1045 const char *filename = git_path_fetch_head(the_repository);
1047 if (write_fetch_head) {
1048 fetch_head->fp = fopen(filename, "a");
1049 if (!fetch_head->fp)
1050 return error_errno(_("cannot open '%s'"), filename);
1051 strbuf_init(&fetch_head->buf, 0);
1052 } else {
1053 fetch_head->fp = NULL;
1056 return 0;
1059 static void append_fetch_head(struct fetch_head *fetch_head,
1060 const struct object_id *old_oid,
1061 enum fetch_head_status fetch_head_status,
1062 const char *note,
1063 const char *url, size_t url_len)
1065 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1066 const char *merge_status_marker;
1067 size_t i;
1069 if (!fetch_head->fp)
1070 return;
1072 switch (fetch_head_status) {
1073 case FETCH_HEAD_NOT_FOR_MERGE:
1074 merge_status_marker = "not-for-merge";
1075 break;
1076 case FETCH_HEAD_MERGE:
1077 merge_status_marker = "";
1078 break;
1079 default:
1080 /* do not write anything to FETCH_HEAD */
1081 return;
1084 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1085 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1086 for (i = 0; i < url_len; ++i)
1087 if ('\n' == url[i])
1088 strbuf_addstr(&fetch_head->buf, "\\n");
1089 else
1090 strbuf_addch(&fetch_head->buf, url[i]);
1091 strbuf_addch(&fetch_head->buf, '\n');
1094 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1095 * any of the reference updates fails. We thus have to write all
1096 * updates to a buffer first and only commit it as soon as all
1097 * references have been successfully updated.
1099 if (!atomic_fetch) {
1100 strbuf_write(&fetch_head->buf, fetch_head->fp);
1101 strbuf_reset(&fetch_head->buf);
1105 static void commit_fetch_head(struct fetch_head *fetch_head)
1107 if (!fetch_head->fp || !atomic_fetch)
1108 return;
1109 strbuf_write(&fetch_head->buf, fetch_head->fp);
1112 static void close_fetch_head(struct fetch_head *fetch_head)
1114 if (!fetch_head->fp)
1115 return;
1117 fclose(fetch_head->fp);
1118 strbuf_release(&fetch_head->buf);
1121 static const char warn_show_forced_updates[] =
1122 N_("fetch normally indicates which branches had a forced update,\n"
1123 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1124 "flag or run 'git config fetch.showForcedUpdates true'");
1125 static const char warn_time_show_forced_updates[] =
1126 N_("it took %.2f seconds to check forced updates; you can use\n"
1127 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1128 "to avoid this check\n");
1130 static int store_updated_refs(struct display_state *display_state,
1131 const char *remote_name,
1132 int connectivity_checked,
1133 struct ref_transaction *transaction, struct ref *ref_map,
1134 struct fetch_head *fetch_head,
1135 const struct fetch_config *config)
1137 int rc = 0;
1138 struct strbuf note = STRBUF_INIT;
1139 const char *what, *kind;
1140 struct ref *rm;
1141 int want_status;
1142 int summary_width = 0;
1144 if (verbosity >= 0)
1145 summary_width = transport_summary_width(ref_map);
1147 if (!connectivity_checked) {
1148 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1150 opt.exclude_hidden_refs_section = "fetch";
1151 rm = ref_map;
1152 if (check_connected(iterate_ref_map, &rm, &opt)) {
1153 rc = error(_("%s did not send all necessary objects\n"),
1154 display_state->url);
1155 goto abort;
1160 * We do a pass for each fetch_head_status type in their enum order, so
1161 * merged entries are written before not-for-merge. That lets readers
1162 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1164 for (want_status = FETCH_HEAD_MERGE;
1165 want_status <= FETCH_HEAD_IGNORE;
1166 want_status++) {
1167 for (rm = ref_map; rm; rm = rm->next) {
1168 struct ref *ref = NULL;
1170 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1171 if (want_status == FETCH_HEAD_MERGE)
1172 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1173 rm->peer_ref ? rm->peer_ref->name : rm->name);
1174 continue;
1178 * When writing FETCH_HEAD we need to determine whether
1179 * we already have the commit or not. If not, then the
1180 * reference is not for merge and needs to be written
1181 * to the reflog after other commits which we already
1182 * have. We're not interested in this property though
1183 * in case FETCH_HEAD is not to be updated, so we can
1184 * skip the classification in that case.
1186 if (fetch_head->fp) {
1187 struct commit *commit = NULL;
1190 * References in "refs/tags/" are often going to point
1191 * to annotated tags, which are not part of the
1192 * commit-graph. We thus only try to look up refs in
1193 * the graph which are not in that namespace to not
1194 * regress performance in repositories with many
1195 * annotated tags.
1197 if (!starts_with(rm->name, "refs/tags/"))
1198 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1199 if (!commit) {
1200 commit = lookup_commit_reference_gently(the_repository,
1201 &rm->old_oid,
1203 if (!commit)
1204 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1208 if (rm->fetch_head_status != want_status)
1209 continue;
1211 if (rm->peer_ref) {
1212 ref = alloc_ref(rm->peer_ref->name);
1213 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1214 oidcpy(&ref->new_oid, &rm->old_oid);
1215 ref->force = rm->peer_ref->force;
1218 if (config->recurse_submodules != RECURSE_SUBMODULES_OFF &&
1219 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1220 check_for_new_submodule_commits(&rm->old_oid);
1223 if (!strcmp(rm->name, "HEAD")) {
1224 kind = "";
1225 what = "";
1226 } else if (skip_prefix(rm->name, "refs/heads/", &what)) {
1227 kind = "branch";
1228 } else if (skip_prefix(rm->name, "refs/tags/", &what)) {
1229 kind = "tag";
1230 } else if (skip_prefix(rm->name, "refs/remotes/", &what)) {
1231 kind = "remote-tracking branch";
1232 } else {
1233 kind = "";
1234 what = rm->name;
1237 strbuf_reset(&note);
1238 if (*what) {
1239 if (*kind)
1240 strbuf_addf(&note, "%s ", kind);
1241 strbuf_addf(&note, "'%s' of ", what);
1244 append_fetch_head(fetch_head, &rm->old_oid,
1245 rm->fetch_head_status,
1246 note.buf, display_state->url,
1247 display_state->url_len);
1249 if (ref) {
1250 rc |= update_local_ref(ref, transaction, display_state,
1251 rm, summary_width, config);
1252 free(ref);
1253 } else if (write_fetch_head || dry_run) {
1255 * Display fetches written to FETCH_HEAD (or
1256 * would be written to FETCH_HEAD, if --dry-run
1257 * is set).
1259 display_ref_update(display_state, '*',
1260 *kind ? kind : "branch", NULL,
1261 rm->name,
1262 "FETCH_HEAD",
1263 &rm->new_oid, &rm->old_oid,
1264 summary_width);
1269 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1270 error(_("some local refs could not be updated; try running\n"
1271 " 'git remote prune %s' to remove any old, conflicting "
1272 "branches"), remote_name);
1274 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1275 if (!config->show_forced_updates) {
1276 warning(_(warn_show_forced_updates));
1277 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1278 warning(_(warn_time_show_forced_updates),
1279 forced_updates_ms / 1000.0);
1283 abort:
1284 strbuf_release(&note);
1285 return rc;
1289 * We would want to bypass the object transfer altogether if
1290 * everything we are going to fetch already exists and is connected
1291 * locally.
1293 static int check_exist_and_connected(struct ref *ref_map)
1295 struct ref *rm = ref_map;
1296 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1297 struct ref *r;
1300 * If we are deepening a shallow clone we already have these
1301 * objects reachable. Running rev-list here will return with
1302 * a good (0) exit status and we'll bypass the fetch that we
1303 * really need to perform. Claiming failure now will ensure
1304 * we perform the network exchange to deepen our history.
1306 if (deepen)
1307 return -1;
1310 * Similarly, if we need to refetch, we always want to perform a full
1311 * fetch ignoring existing objects.
1313 if (refetch)
1314 return -1;
1318 * check_connected() allows objects to merely be promised, but
1319 * we need all direct targets to exist.
1321 for (r = rm; r; r = r->next) {
1322 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1323 OBJECT_INFO_SKIP_FETCH_OBJECT))
1324 return -1;
1327 opt.quiet = 1;
1328 opt.exclude_hidden_refs_section = "fetch";
1329 return check_connected(iterate_ref_map, &rm, &opt);
1332 static int fetch_and_consume_refs(struct display_state *display_state,
1333 struct transport *transport,
1334 struct ref_transaction *transaction,
1335 struct ref *ref_map,
1336 struct fetch_head *fetch_head,
1337 const struct fetch_config *config)
1339 int connectivity_checked = 1;
1340 int ret;
1343 * We don't need to perform a fetch in case we can already satisfy all
1344 * refs.
1346 ret = check_exist_and_connected(ref_map);
1347 if (ret) {
1348 trace2_region_enter("fetch", "fetch_refs", the_repository);
1349 ret = transport_fetch_refs(transport, ref_map);
1350 trace2_region_leave("fetch", "fetch_refs", the_repository);
1351 if (ret)
1352 goto out;
1353 connectivity_checked = transport->smart_options ?
1354 transport->smart_options->connectivity_checked : 0;
1357 trace2_region_enter("fetch", "consume_refs", the_repository);
1358 ret = store_updated_refs(display_state, transport->remote->name,
1359 connectivity_checked, transaction, ref_map,
1360 fetch_head, config);
1361 trace2_region_leave("fetch", "consume_refs", the_repository);
1363 out:
1364 transport_unlock_pack(transport, 0);
1365 return ret;
1368 static int prune_refs(struct display_state *display_state,
1369 struct refspec *rs,
1370 struct ref_transaction *transaction,
1371 struct ref *ref_map)
1373 int result = 0;
1374 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1375 struct strbuf err = STRBUF_INIT;
1376 const char *dangling_msg = dry_run
1377 ? _(" (%s will become dangling)")
1378 : _(" (%s has become dangling)");
1380 if (!dry_run) {
1381 if (transaction) {
1382 for (ref = stale_refs; ref; ref = ref->next) {
1383 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1384 "fetch: prune", &err);
1385 if (result)
1386 goto cleanup;
1388 } else {
1389 struct string_list refnames = STRING_LIST_INIT_NODUP;
1391 for (ref = stale_refs; ref; ref = ref->next)
1392 string_list_append(&refnames, ref->name);
1394 result = delete_refs("fetch: prune", &refnames, 0);
1395 string_list_clear(&refnames, 0);
1399 if (verbosity >= 0) {
1400 int summary_width = transport_summary_width(stale_refs);
1402 for (ref = stale_refs; ref; ref = ref->next) {
1403 display_ref_update(display_state, '-', _("[deleted]"), NULL,
1404 _("(none)"), ref->name,
1405 &ref->new_oid, &ref->old_oid,
1406 summary_width);
1407 warn_dangling_symref(stderr, dangling_msg, ref->name);
1411 cleanup:
1412 strbuf_release(&err);
1413 free_refs(stale_refs);
1414 return result;
1417 static void check_not_current_branch(struct ref *ref_map)
1419 const char *path;
1420 for (; ref_map; ref_map = ref_map->next)
1421 if (ref_map->peer_ref &&
1422 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1423 (path = branch_checked_out(ref_map->peer_ref->name)))
1424 die(_("refusing to fetch into branch '%s' "
1425 "checked out at '%s'"),
1426 ref_map->peer_ref->name, path);
1429 static int truncate_fetch_head(void)
1431 const char *filename = git_path_fetch_head(the_repository);
1432 FILE *fp = fopen_for_writing(filename);
1434 if (!fp)
1435 return error_errno(_("cannot open '%s'"), filename);
1436 fclose(fp);
1437 return 0;
1440 static void set_option(struct transport *transport, const char *name, const char *value)
1442 int r = transport_set_option(transport, name, value);
1443 if (r < 0)
1444 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1445 name, value, transport->url);
1446 if (r > 0)
1447 warning(_("option \"%s\" is ignored for %s\n"),
1448 name, transport->url);
1452 static int add_oid(const char *refname UNUSED,
1453 const struct object_id *oid,
1454 int flags UNUSED, void *cb_data)
1456 struct oid_array *oids = cb_data;
1458 oid_array_append(oids, oid);
1459 return 0;
1462 static void add_negotiation_tips(struct git_transport_options *smart_options)
1464 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1465 int i;
1467 for (i = 0; i < negotiation_tip.nr; i++) {
1468 const char *s = negotiation_tip.items[i].string;
1469 int old_nr;
1470 if (!has_glob_specials(s)) {
1471 struct object_id oid;
1472 if (repo_get_oid(the_repository, s, &oid))
1473 die(_("%s is not a valid object"), s);
1474 if (!has_object(the_repository, &oid, 0))
1475 die(_("the object %s does not exist"), s);
1476 oid_array_append(oids, &oid);
1477 continue;
1479 old_nr = oids->nr;
1480 for_each_glob_ref(add_oid, s, oids);
1481 if (old_nr == oids->nr)
1482 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1485 smart_options->negotiation_tips = oids;
1488 static struct transport *prepare_transport(struct remote *remote, int deepen)
1490 struct transport *transport;
1492 transport = transport_get(remote, NULL);
1493 transport_set_verbosity(transport, verbosity, progress);
1494 transport->family = family;
1495 if (upload_pack)
1496 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1497 if (keep)
1498 set_option(transport, TRANS_OPT_KEEP, "yes");
1499 if (depth)
1500 set_option(transport, TRANS_OPT_DEPTH, depth);
1501 if (deepen && deepen_since)
1502 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1503 if (deepen && deepen_not.nr)
1504 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1505 (const char *)&deepen_not);
1506 if (deepen_relative)
1507 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1508 if (update_shallow)
1509 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1510 if (refetch)
1511 set_option(transport, TRANS_OPT_REFETCH, "yes");
1512 if (filter_options.choice) {
1513 const char *spec =
1514 expand_list_objects_filter_spec(&filter_options);
1515 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1516 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1518 if (negotiation_tip.nr) {
1519 if (transport->smart_options)
1520 add_negotiation_tips(transport->smart_options);
1521 else
1522 warning("ignoring --negotiation-tip because the protocol does not support it");
1524 return transport;
1527 static int backfill_tags(struct display_state *display_state,
1528 struct transport *transport,
1529 struct ref_transaction *transaction,
1530 struct ref *ref_map,
1531 struct fetch_head *fetch_head,
1532 const struct fetch_config *config)
1534 int retcode, cannot_reuse;
1537 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1538 * when remote helper is used (setting it to an empty string
1539 * is not unsetting). We could extend the remote helper
1540 * protocol for that, but for now, just force a new connection
1541 * without deepen-since. Similar story for deepen-not.
1543 cannot_reuse = transport->cannot_reuse ||
1544 deepen_since || deepen_not.nr;
1545 if (cannot_reuse) {
1546 gsecondary = prepare_transport(transport->remote, 0);
1547 transport = gsecondary;
1550 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1551 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1552 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1553 retcode = fetch_and_consume_refs(display_state, transport, transaction, ref_map,
1554 fetch_head, config);
1556 if (gsecondary) {
1557 transport_disconnect(gsecondary);
1558 gsecondary = NULL;
1561 return retcode;
1564 static int do_fetch(struct transport *transport,
1565 struct refspec *rs,
1566 const struct fetch_config *config)
1568 struct ref_transaction *transaction = NULL;
1569 struct ref *ref_map = NULL;
1570 struct display_state display_state = { 0 };
1571 int autotags = (transport->remote->fetch_tags == 1);
1572 int retcode = 0;
1573 const struct ref *remote_refs;
1574 struct transport_ls_refs_options transport_ls_refs_options =
1575 TRANSPORT_LS_REFS_OPTIONS_INIT;
1576 int must_list_refs = 1;
1577 struct fetch_head fetch_head = { 0 };
1578 struct strbuf err = STRBUF_INIT;
1580 if (tags == TAGS_DEFAULT) {
1581 if (transport->remote->fetch_tags == 2)
1582 tags = TAGS_SET;
1583 if (transport->remote->fetch_tags == -1)
1584 tags = TAGS_UNSET;
1587 /* if not appending, truncate FETCH_HEAD */
1588 if (!append && write_fetch_head) {
1589 retcode = truncate_fetch_head();
1590 if (retcode)
1591 goto cleanup;
1594 if (rs->nr) {
1595 int i;
1597 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1600 * We can avoid listing refs if all of them are exact
1601 * OIDs
1603 must_list_refs = 0;
1604 for (i = 0; i < rs->nr; i++) {
1605 if (!rs->items[i].exact_sha1) {
1606 must_list_refs = 1;
1607 break;
1610 } else {
1611 struct branch *branch = branch_get(NULL);
1613 if (transport->remote->fetch.nr)
1614 refspec_ref_prefixes(&transport->remote->fetch,
1615 &transport_ls_refs_options.ref_prefixes);
1616 if (branch_has_merge_config(branch) &&
1617 !strcmp(branch->remote_name, transport->remote->name)) {
1618 int i;
1619 for (i = 0; i < branch->merge_nr; i++) {
1620 strvec_push(&transport_ls_refs_options.ref_prefixes,
1621 branch->merge[i]->src);
1626 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1627 must_list_refs = 1;
1628 if (transport_ls_refs_options.ref_prefixes.nr)
1629 strvec_push(&transport_ls_refs_options.ref_prefixes,
1630 "refs/tags/");
1633 if (must_list_refs) {
1634 trace2_region_enter("fetch", "remote_refs", the_repository);
1635 remote_refs = transport_get_remote_refs(transport,
1636 &transport_ls_refs_options);
1637 trace2_region_leave("fetch", "remote_refs", the_repository);
1638 } else
1639 remote_refs = NULL;
1641 transport_ls_refs_options_release(&transport_ls_refs_options);
1643 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1644 tags, &autotags);
1645 if (!update_head_ok)
1646 check_not_current_branch(ref_map);
1648 retcode = open_fetch_head(&fetch_head);
1649 if (retcode)
1650 goto cleanup;
1652 display_state_init(&display_state, ref_map, transport->url,
1653 config->display_format);
1655 if (atomic_fetch) {
1656 transaction = ref_transaction_begin(&err);
1657 if (!transaction) {
1658 retcode = -1;
1659 goto cleanup;
1663 if (tags == TAGS_DEFAULT && autotags)
1664 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1665 if (prune) {
1667 * We only prune based on refspecs specified
1668 * explicitly (via command line or configuration); we
1669 * don't care whether --tags was specified.
1671 if (rs->nr) {
1672 retcode = prune_refs(&display_state, rs, transaction, ref_map);
1673 } else {
1674 retcode = prune_refs(&display_state, &transport->remote->fetch,
1675 transaction, ref_map);
1677 if (retcode != 0)
1678 retcode = 1;
1681 if (fetch_and_consume_refs(&display_state, transport, transaction, ref_map,
1682 &fetch_head, config)) {
1683 retcode = 1;
1684 goto cleanup;
1688 * If neither --no-tags nor --tags was specified, do automated tag
1689 * following.
1691 if (tags == TAGS_DEFAULT && autotags) {
1692 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1694 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1695 if (tags_ref_map) {
1697 * If backfilling of tags fails then we want to tell
1698 * the user so, but we have to continue regardless to
1699 * populate upstream information of the references we
1700 * have already fetched above. The exception though is
1701 * when `--atomic` is passed: in that case we'll abort
1702 * the transaction and don't commit anything.
1704 if (backfill_tags(&display_state, transport, transaction, tags_ref_map,
1705 &fetch_head, config))
1706 retcode = 1;
1709 free_refs(tags_ref_map);
1712 if (transaction) {
1713 if (retcode)
1714 goto cleanup;
1716 retcode = ref_transaction_commit(transaction, &err);
1717 if (retcode) {
1718 ref_transaction_free(transaction);
1719 transaction = NULL;
1720 goto cleanup;
1724 commit_fetch_head(&fetch_head);
1726 if (set_upstream) {
1727 struct branch *branch = branch_get("HEAD");
1728 struct ref *rm;
1729 struct ref *source_ref = NULL;
1732 * We're setting the upstream configuration for the
1733 * current branch. The relevant upstream is the
1734 * fetched branch that is meant to be merged with the
1735 * current one, i.e. the one fetched to FETCH_HEAD.
1737 * When there are several such branches, consider the
1738 * request ambiguous and err on the safe side by doing
1739 * nothing and just emit a warning.
1741 for (rm = ref_map; rm; rm = rm->next) {
1742 if (!rm->peer_ref) {
1743 if (source_ref) {
1744 warning(_("multiple branches detected, incompatible with --set-upstream"));
1745 goto cleanup;
1746 } else {
1747 source_ref = rm;
1751 if (source_ref) {
1752 if (!branch) {
1753 const char *shortname = source_ref->name;
1754 skip_prefix(shortname, "refs/heads/", &shortname);
1756 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1757 "it does not point to any branch."),
1758 shortname, transport->remote->name);
1759 goto cleanup;
1762 if (!strcmp(source_ref->name, "HEAD") ||
1763 starts_with(source_ref->name, "refs/heads/"))
1764 install_branch_config(0,
1765 branch->name,
1766 transport->remote->name,
1767 source_ref->name);
1768 else if (starts_with(source_ref->name, "refs/remotes/"))
1769 warning(_("not setting upstream for a remote remote-tracking branch"));
1770 else if (starts_with(source_ref->name, "refs/tags/"))
1771 warning(_("not setting upstream for a remote tag"));
1772 else
1773 warning(_("unknown branch type"));
1774 } else {
1775 warning(_("no source branch found;\n"
1776 "you need to specify exactly one branch with the --set-upstream option"));
1780 cleanup:
1781 if (retcode) {
1782 if (err.len) {
1783 error("%s", err.buf);
1784 strbuf_reset(&err);
1786 if (transaction && ref_transaction_abort(transaction, &err) &&
1787 err.len)
1788 error("%s", err.buf);
1791 display_state_release(&display_state);
1792 close_fetch_head(&fetch_head);
1793 strbuf_release(&err);
1794 free_refs(ref_map);
1795 return retcode;
1798 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1800 struct string_list *list = priv;
1801 if (!remote->skip_default_update)
1802 string_list_append(list, remote->name);
1803 return 0;
1806 struct remote_group_data {
1807 const char *name;
1808 struct string_list *list;
1811 static int get_remote_group(const char *key, const char *value,
1812 const struct config_context *ctx UNUSED,
1813 void *priv)
1815 struct remote_group_data *g = priv;
1817 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1818 /* split list by white space */
1819 while (*value) {
1820 size_t wordlen = strcspn(value, " \t\n");
1822 if (wordlen >= 1)
1823 string_list_append_nodup(g->list,
1824 xstrndup(value, wordlen));
1825 value += wordlen + (value[wordlen] != '\0');
1829 return 0;
1832 static int add_remote_or_group(const char *name, struct string_list *list)
1834 int prev_nr = list->nr;
1835 struct remote_group_data g;
1836 g.name = name; g.list = list;
1838 git_config(get_remote_group, &g);
1839 if (list->nr == prev_nr) {
1840 struct remote *remote = remote_get(name);
1841 if (!remote_is_configured(remote, 0))
1842 return 0;
1843 string_list_append(list, remote->name);
1845 return 1;
1848 static void add_options_to_argv(struct strvec *argv,
1849 const struct fetch_config *config)
1851 if (dry_run)
1852 strvec_push(argv, "--dry-run");
1853 if (prune != -1)
1854 strvec_push(argv, prune ? "--prune" : "--no-prune");
1855 if (prune_tags != -1)
1856 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1857 if (update_head_ok)
1858 strvec_push(argv, "--update-head-ok");
1859 if (force)
1860 strvec_push(argv, "--force");
1861 if (keep)
1862 strvec_push(argv, "--keep");
1863 if (config->recurse_submodules == RECURSE_SUBMODULES_ON)
1864 strvec_push(argv, "--recurse-submodules");
1865 else if (config->recurse_submodules == RECURSE_SUBMODULES_OFF)
1866 strvec_push(argv, "--no-recurse-submodules");
1867 else if (config->recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1868 strvec_push(argv, "--recurse-submodules=on-demand");
1869 if (tags == TAGS_SET)
1870 strvec_push(argv, "--tags");
1871 else if (tags == TAGS_UNSET)
1872 strvec_push(argv, "--no-tags");
1873 if (verbosity >= 2)
1874 strvec_push(argv, "-v");
1875 if (verbosity >= 1)
1876 strvec_push(argv, "-v");
1877 else if (verbosity < 0)
1878 strvec_push(argv, "-q");
1879 if (family == TRANSPORT_FAMILY_IPV4)
1880 strvec_push(argv, "--ipv4");
1881 else if (family == TRANSPORT_FAMILY_IPV6)
1882 strvec_push(argv, "--ipv6");
1883 if (!write_fetch_head)
1884 strvec_push(argv, "--no-write-fetch-head");
1885 if (config->display_format == DISPLAY_FORMAT_PORCELAIN)
1886 strvec_pushf(argv, "--porcelain");
1889 /* Fetch multiple remotes in parallel */
1891 struct parallel_fetch_state {
1892 const char **argv;
1893 struct string_list *remotes;
1894 int next, result;
1895 const struct fetch_config *config;
1898 static int fetch_next_remote(struct child_process *cp,
1899 struct strbuf *out UNUSED,
1900 void *cb, void **task_cb)
1902 struct parallel_fetch_state *state = cb;
1903 char *remote;
1905 if (state->next < 0 || state->next >= state->remotes->nr)
1906 return 0;
1908 remote = state->remotes->items[state->next++].string;
1909 *task_cb = remote;
1911 strvec_pushv(&cp->args, state->argv);
1912 strvec_push(&cp->args, remote);
1913 cp->git_cmd = 1;
1915 if (verbosity >= 0 && state->config->display_format != DISPLAY_FORMAT_PORCELAIN)
1916 printf(_("Fetching %s\n"), remote);
1918 return 1;
1921 static int fetch_failed_to_start(struct strbuf *out UNUSED,
1922 void *cb, void *task_cb)
1924 struct parallel_fetch_state *state = cb;
1925 const char *remote = task_cb;
1927 state->result = error(_("could not fetch %s"), remote);
1929 return 0;
1932 static int fetch_finished(int result, struct strbuf *out,
1933 void *cb, void *task_cb)
1935 struct parallel_fetch_state *state = cb;
1936 const char *remote = task_cb;
1938 if (result) {
1939 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1940 remote, result);
1941 state->result = -1;
1944 return 0;
1947 static int fetch_multiple(struct string_list *list, int max_children,
1948 const struct fetch_config *config)
1950 int i, result = 0;
1951 struct strvec argv = STRVEC_INIT;
1953 if (!append && write_fetch_head) {
1954 int errcode = truncate_fetch_head();
1955 if (errcode)
1956 return errcode;
1960 * Cancel out the fetch.bundleURI config when running subprocesses,
1961 * to avoid fetching from the same bundle list multiple times.
1963 strvec_pushl(&argv, "-c", "fetch.bundleURI=",
1964 "fetch", "--append", "--no-auto-gc",
1965 "--no-write-commit-graph", NULL);
1966 add_options_to_argv(&argv, config);
1968 if (max_children != 1 && list->nr != 1) {
1969 struct parallel_fetch_state state = { argv.v, list, 0, 0, config };
1970 const struct run_process_parallel_opts opts = {
1971 .tr2_category = "fetch",
1972 .tr2_label = "parallel/fetch",
1974 .processes = max_children,
1976 .get_next_task = &fetch_next_remote,
1977 .start_failure = &fetch_failed_to_start,
1978 .task_finished = &fetch_finished,
1979 .data = &state,
1982 strvec_push(&argv, "--end-of-options");
1984 run_processes_parallel(&opts);
1985 result = state.result;
1986 } else
1987 for (i = 0; i < list->nr; i++) {
1988 const char *name = list->items[i].string;
1989 struct child_process cmd = CHILD_PROCESS_INIT;
1991 strvec_pushv(&cmd.args, argv.v);
1992 strvec_push(&cmd.args, name);
1993 if (verbosity >= 0 && config->display_format != DISPLAY_FORMAT_PORCELAIN)
1994 printf(_("Fetching %s\n"), name);
1995 cmd.git_cmd = 1;
1996 if (run_command(&cmd)) {
1997 error(_("could not fetch %s"), name);
1998 result = 1;
2002 strvec_clear(&argv);
2003 return !!result;
2007 * Fetching from the promisor remote should use the given filter-spec
2008 * or inherit the default filter-spec from the config.
2010 static inline void fetch_one_setup_partial(struct remote *remote)
2013 * Explicit --no-filter argument overrides everything, regardless
2014 * of any prior partial clones and fetches.
2016 if (filter_options.no_filter)
2017 return;
2020 * If no prior partial clone/fetch and the current fetch DID NOT
2021 * request a partial-fetch, do a normal fetch.
2023 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
2024 return;
2027 * If this is a partial-fetch request, we enable partial on
2028 * this repo if not already enabled and remember the given
2029 * filter-spec as the default for subsequent fetches to this
2030 * remote if there is currently no default filter-spec.
2032 if (filter_options.choice) {
2033 partial_clone_register(remote->name, &filter_options);
2034 return;
2038 * Do a partial-fetch from the promisor remote using either the
2039 * explicitly given filter-spec or inherit the filter-spec from
2040 * the config.
2042 if (!filter_options.choice)
2043 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2044 return;
2047 static int fetch_one(struct remote *remote, int argc, const char **argv,
2048 int prune_tags_ok, int use_stdin_refspecs,
2049 const struct fetch_config *config)
2051 struct refspec rs = REFSPEC_INIT_FETCH;
2052 int i;
2053 int exit_code;
2054 int maybe_prune_tags;
2055 int remote_via_config = remote_is_configured(remote, 0);
2057 if (!remote)
2058 die(_("no remote repository specified; please specify either a URL or a\n"
2059 "remote name from which new revisions should be fetched"));
2061 gtransport = prepare_transport(remote, 1);
2063 if (prune < 0) {
2064 /* no command line request */
2065 if (0 <= remote->prune)
2066 prune = remote->prune;
2067 else if (0 <= config->prune)
2068 prune = config->prune;
2069 else
2070 prune = PRUNE_BY_DEFAULT;
2073 if (prune_tags < 0) {
2074 /* no command line request */
2075 if (0 <= remote->prune_tags)
2076 prune_tags = remote->prune_tags;
2077 else if (0 <= config->prune_tags)
2078 prune_tags = config->prune_tags;
2079 else
2080 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2083 maybe_prune_tags = prune_tags_ok && prune_tags;
2084 if (maybe_prune_tags && remote_via_config)
2085 refspec_append(&remote->fetch, TAG_REFSPEC);
2087 if (maybe_prune_tags && (argc || !remote_via_config))
2088 refspec_append(&rs, TAG_REFSPEC);
2090 for (i = 0; i < argc; i++) {
2091 if (!strcmp(argv[i], "tag")) {
2092 i++;
2093 if (i >= argc)
2094 die(_("you need to specify a tag name"));
2096 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2097 argv[i], argv[i]);
2098 } else {
2099 refspec_append(&rs, argv[i]);
2103 if (use_stdin_refspecs) {
2104 struct strbuf line = STRBUF_INIT;
2105 while (strbuf_getline_lf(&line, stdin) != EOF)
2106 refspec_append(&rs, line.buf);
2107 strbuf_release(&line);
2110 if (server_options.nr)
2111 gtransport->server_options = &server_options;
2113 sigchain_push_common(unlock_pack_on_signal);
2114 atexit(unlock_pack_atexit);
2115 sigchain_push(SIGPIPE, SIG_IGN);
2116 exit_code = do_fetch(gtransport, &rs, config);
2117 sigchain_pop(SIGPIPE);
2118 refspec_clear(&rs);
2119 transport_disconnect(gtransport);
2120 gtransport = NULL;
2121 return exit_code;
2124 int cmd_fetch(int argc, const char **argv, const char *prefix)
2126 struct fetch_config config = {
2127 .display_format = DISPLAY_FORMAT_FULL,
2128 .prune = -1,
2129 .prune_tags = -1,
2130 .show_forced_updates = 1,
2131 .recurse_submodules = RECURSE_SUBMODULES_DEFAULT,
2132 .parallel = 1,
2133 .submodule_fetch_jobs = -1,
2135 const char *submodule_prefix = "";
2136 const char *bundle_uri;
2137 struct string_list list = STRING_LIST_INIT_DUP;
2138 struct remote *remote = NULL;
2139 int all = -1, multiple = 0;
2140 int result = 0;
2141 int prune_tags_ok = 1;
2142 int enable_auto_gc = 1;
2143 int unshallow = 0;
2144 int max_jobs = -1;
2145 int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
2146 int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
2147 int fetch_write_commit_graph = -1;
2148 int stdin_refspecs = 0;
2149 int negotiate_only = 0;
2150 int porcelain = 0;
2151 int i;
2153 struct option builtin_fetch_options[] = {
2154 OPT__VERBOSITY(&verbosity),
2155 OPT_BOOL(0, "all", &all,
2156 N_("fetch from all remotes")),
2157 OPT_BOOL(0, "set-upstream", &set_upstream,
2158 N_("set upstream for git pull/fetch")),
2159 OPT_BOOL('a', "append", &append,
2160 N_("append to .git/FETCH_HEAD instead of overwriting")),
2161 OPT_BOOL(0, "atomic", &atomic_fetch,
2162 N_("use atomic transaction to update references")),
2163 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
2164 N_("path to upload pack on remote end")),
2165 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
2166 OPT_BOOL('m', "multiple", &multiple,
2167 N_("fetch from multiple remotes")),
2168 OPT_SET_INT('t', "tags", &tags,
2169 N_("fetch all tags and associated objects"), TAGS_SET),
2170 OPT_SET_INT('n', NULL, &tags,
2171 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
2172 OPT_INTEGER('j', "jobs", &max_jobs,
2173 N_("number of submodules fetched in parallel")),
2174 OPT_BOOL(0, "prefetch", &prefetch,
2175 N_("modify the refspec to place all refs within refs/prefetch/")),
2176 OPT_BOOL('p', "prune", &prune,
2177 N_("prune remote-tracking branches no longer on remote")),
2178 OPT_BOOL('P', "prune-tags", &prune_tags,
2179 N_("prune local tags no longer on remote and clobber changed tags")),
2180 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
2181 N_("control recursive fetching of submodules"),
2182 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
2183 OPT_BOOL(0, "dry-run", &dry_run,
2184 N_("dry run")),
2185 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
2186 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
2187 N_("write fetched references to the FETCH_HEAD file")),
2188 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
2189 OPT_BOOL('u', "update-head-ok", &update_head_ok,
2190 N_("allow updating of HEAD ref")),
2191 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
2192 OPT_STRING(0, "depth", &depth, N_("depth"),
2193 N_("deepen history of shallow clone")),
2194 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
2195 N_("deepen history of shallow repository based on time")),
2196 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
2197 N_("deepen history of shallow clone, excluding rev")),
2198 OPT_INTEGER(0, "deepen", &deepen_relative,
2199 N_("deepen history of shallow clone")),
2200 OPT_SET_INT_F(0, "unshallow", &unshallow,
2201 N_("convert to a complete repository"),
2202 1, PARSE_OPT_NONEG),
2203 OPT_SET_INT_F(0, "refetch", &refetch,
2204 N_("re-fetch without negotiating common commits"),
2205 1, PARSE_OPT_NONEG),
2206 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
2207 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
2208 OPT_CALLBACK_F(0, "recurse-submodules-default",
2209 &recurse_submodules_default, N_("on-demand"),
2210 N_("default for recursive fetching of submodules "
2211 "(lower priority than config files)"),
2212 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
2213 OPT_BOOL(0, "update-shallow", &update_shallow,
2214 N_("accept refs that update .git/shallow")),
2215 OPT_CALLBACK_F(0, "refmap", &refmap, N_("refmap"),
2216 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
2217 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
2218 OPT_IPVERSION(&family),
2219 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
2220 N_("report that we have only objects reachable from this object")),
2221 OPT_BOOL(0, "negotiate-only", &negotiate_only,
2222 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
2223 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
2224 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
2225 N_("run 'maintenance --auto' after fetching")),
2226 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
2227 N_("run 'maintenance --auto' after fetching")),
2228 OPT_BOOL(0, "show-forced-updates", &config.show_forced_updates,
2229 N_("check for forced-updates on all updated branches")),
2230 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
2231 N_("write the commit-graph after fetching")),
2232 OPT_BOOL(0, "stdin", &stdin_refspecs,
2233 N_("accept refspecs from stdin")),
2234 OPT_END()
2237 packet_trace_identity("fetch");
2239 /* Record the command line for the reflog */
2240 strbuf_addstr(&default_rla, "fetch");
2241 for (i = 1; i < argc; i++) {
2242 /* This handles non-URLs gracefully */
2243 char *anon = transport_anonymize_url(argv[i]);
2245 strbuf_addf(&default_rla, " %s", anon);
2246 free(anon);
2249 git_config(git_fetch_config, &config);
2250 if (the_repository->gitdir) {
2251 prepare_repo_settings(the_repository);
2252 the_repository->settings.command_requires_full_index = 0;
2255 argc = parse_options(argc, argv, prefix,
2256 builtin_fetch_options, builtin_fetch_usage, 0);
2258 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2259 config.recurse_submodules = recurse_submodules_cli;
2261 if (negotiate_only) {
2262 switch (recurse_submodules_cli) {
2263 case RECURSE_SUBMODULES_OFF:
2264 case RECURSE_SUBMODULES_DEFAULT:
2266 * --negotiate-only should never recurse into
2267 * submodules. Skip it by setting recurse_submodules to
2268 * RECURSE_SUBMODULES_OFF.
2270 config.recurse_submodules = RECURSE_SUBMODULES_OFF;
2271 break;
2273 default:
2274 die(_("options '%s' and '%s' cannot be used together"),
2275 "--negotiate-only", "--recurse-submodules");
2279 if (config.recurse_submodules != RECURSE_SUBMODULES_OFF) {
2280 int *sfjc = config.submodule_fetch_jobs == -1
2281 ? &config.submodule_fetch_jobs : NULL;
2282 int *rs = config.recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2283 ? &config.recurse_submodules : NULL;
2285 fetch_config_from_gitmodules(sfjc, rs);
2289 if (porcelain) {
2290 switch (recurse_submodules_cli) {
2291 case RECURSE_SUBMODULES_OFF:
2292 case RECURSE_SUBMODULES_DEFAULT:
2294 * Reference updates in submodules would be ambiguous
2295 * in porcelain mode, so we reject this combination.
2297 config.recurse_submodules = RECURSE_SUBMODULES_OFF;
2298 break;
2300 default:
2301 die(_("options '%s' and '%s' cannot be used together"),
2302 "--porcelain", "--recurse-submodules");
2305 config.display_format = DISPLAY_FORMAT_PORCELAIN;
2308 if (negotiate_only && !negotiation_tip.nr)
2309 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2311 if (deepen_relative) {
2312 if (deepen_relative < 0)
2313 die(_("negative depth in --deepen is not supported"));
2314 if (depth)
2315 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2316 depth = xstrfmt("%d", deepen_relative);
2318 if (unshallow) {
2319 if (depth)
2320 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2321 else if (!is_repository_shallow(the_repository))
2322 die(_("--unshallow on a complete repository does not make sense"));
2323 else
2324 depth = xstrfmt("%d", INFINITE_DEPTH);
2327 /* no need to be strict, transport_set_option() will validate it again */
2328 if (depth && atoi(depth) < 1)
2329 die(_("depth %s is not a positive number"), depth);
2330 if (depth || deepen_since || deepen_not.nr)
2331 deepen = 1;
2333 /* FETCH_HEAD never gets updated in --dry-run mode */
2334 if (dry_run)
2335 write_fetch_head = 0;
2337 if (!max_jobs)
2338 max_jobs = online_cpus();
2340 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2341 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2342 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2344 if (all < 0) {
2346 * no --[no-]all given;
2347 * only use config option if no remote was explicitly specified
2349 all = (!argc) ? config.all : 0;
2352 if (all) {
2353 if (argc == 1)
2354 die(_("fetch --all does not take a repository argument"));
2355 else if (argc > 1)
2356 die(_("fetch --all does not make sense with refspecs"));
2358 (void) for_each_remote(get_one_remote_for_fetch, &list);
2360 /* do not do fetch_multiple() of one */
2361 if (list.nr == 1)
2362 remote = remote_get(list.items[0].string);
2363 } else if (argc == 0) {
2364 /* No arguments -- use default remote */
2365 remote = remote_get(NULL);
2366 } else if (multiple) {
2367 /* All arguments are assumed to be remotes or groups */
2368 for (i = 0; i < argc; i++)
2369 if (!add_remote_or_group(argv[i], &list))
2370 die(_("no such remote or remote group: %s"),
2371 argv[i]);
2372 } else {
2373 /* Single remote or group */
2374 (void) add_remote_or_group(argv[0], &list);
2375 if (list.nr > 1) {
2376 /* More than one remote */
2377 if (argc > 1)
2378 die(_("fetching a group and specifying refspecs does not make sense"));
2379 } else {
2380 /* Zero or one remotes */
2381 remote = remote_get(argv[0]);
2382 prune_tags_ok = (argc == 1);
2383 argc--;
2384 argv++;
2387 string_list_remove_duplicates(&list, 0);
2389 if (negotiate_only) {
2390 struct oidset acked_commits = OIDSET_INIT;
2391 struct oidset_iter iter;
2392 const struct object_id *oid;
2394 if (!remote)
2395 die(_("must supply remote when using --negotiate-only"));
2396 gtransport = prepare_transport(remote, 1);
2397 if (gtransport->smart_options) {
2398 gtransport->smart_options->acked_commits = &acked_commits;
2399 } else {
2400 warning(_("protocol does not support --negotiate-only, exiting"));
2401 result = 1;
2402 goto cleanup;
2404 if (server_options.nr)
2405 gtransport->server_options = &server_options;
2406 result = transport_fetch_refs(gtransport, NULL);
2408 oidset_iter_init(&acked_commits, &iter);
2409 while ((oid = oidset_iter_next(&iter)))
2410 printf("%s\n", oid_to_hex(oid));
2411 oidset_clear(&acked_commits);
2412 } else if (remote) {
2413 if (filter_options.choice || repo_has_promisor_remote(the_repository))
2414 fetch_one_setup_partial(remote);
2415 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs,
2416 &config);
2417 } else {
2418 int max_children = max_jobs;
2420 if (filter_options.choice)
2421 die(_("--filter can only be used with the remote "
2422 "configured in extensions.partialclone"));
2424 if (atomic_fetch)
2425 die(_("--atomic can only be used when fetching "
2426 "from one remote"));
2428 if (stdin_refspecs)
2429 die(_("--stdin can only be used when fetching "
2430 "from one remote"));
2432 if (max_children < 0)
2433 max_children = config.parallel;
2435 /* TODO should this also die if we have a previous partial-clone? */
2436 result = fetch_multiple(&list, max_children, &config);
2440 * This is only needed after fetch_one(), which does not fetch
2441 * submodules by itself.
2443 * When we fetch from multiple remotes, fetch_multiple() has
2444 * already updated submodules to grab commits necessary for
2445 * the fetched history from each remote, so there is no need
2446 * to fetch submodules from here.
2448 if (!result && remote && (config.recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2449 struct strvec options = STRVEC_INIT;
2450 int max_children = max_jobs;
2452 if (max_children < 0)
2453 max_children = config.submodule_fetch_jobs;
2454 if (max_children < 0)
2455 max_children = config.parallel;
2457 add_options_to_argv(&options, &config);
2458 result = fetch_submodules(the_repository,
2459 &options,
2460 submodule_prefix,
2461 config.recurse_submodules,
2462 recurse_submodules_default,
2463 verbosity < 0,
2464 max_children);
2465 strvec_clear(&options);
2469 * Skip irrelevant tasks because we know objects were not
2470 * fetched.
2472 * NEEDSWORK: as a future optimization, we can return early
2473 * whenever objects were not fetched e.g. if we already have all
2474 * of them.
2476 if (negotiate_only)
2477 goto cleanup;
2479 prepare_repo_settings(the_repository);
2480 if (fetch_write_commit_graph > 0 ||
2481 (fetch_write_commit_graph < 0 &&
2482 the_repository->settings.fetch_write_commit_graph)) {
2483 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2485 if (progress)
2486 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2488 write_commit_graph_reachable(the_repository->objects->odb,
2489 commit_graph_flags,
2490 NULL);
2493 if (enable_auto_gc) {
2494 if (refetch) {
2496 * Hint auto-maintenance strongly to encourage repacking,
2497 * but respect config settings disabling it.
2499 int opt_val;
2500 if (git_config_get_int("gc.autopacklimit", &opt_val))
2501 opt_val = -1;
2502 if (opt_val != 0)
2503 git_config_push_parameter("gc.autoPackLimit=1");
2505 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2506 opt_val = -1;
2507 if (opt_val != 0)
2508 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2510 run_auto_maintenance(verbosity < 0);
2513 cleanup:
2514 string_list_clear(&list, 0);
2515 return result;