]> git.ipfire.org Git - thirdparty/git.git/blame_incremental - builtin/fetch.c
The fifth batch
[thirdparty/git.git] / builtin / fetch.c
... / ...
CommitLineData
1/*
2 * "git fetch"
3 */
4
5#define USE_THE_REPOSITORY_VARIABLE
6#define DISABLE_SIGN_COMPARE_WARNINGS
7
8#include "builtin.h"
9#include "advice.h"
10#include "config.h"
11#include "gettext.h"
12#include "environment.h"
13#include "hex.h"
14#include "refs.h"
15#include "refspec.h"
16#include "object-name.h"
17#include "object-store.h"
18#include "oidset.h"
19#include "oid-array.h"
20#include "commit.h"
21#include "string-list.h"
22#include "remote.h"
23#include "transport.h"
24#include "run-command.h"
25#include "parse-options.h"
26#include "sigchain.h"
27#include "submodule-config.h"
28#include "submodule.h"
29#include "connected.h"
30#include "strvec.h"
31#include "utf8.h"
32#include "pager.h"
33#include "path.h"
34#include "pkt-line.h"
35#include "list-objects-filter-options.h"
36#include "commit-reach.h"
37#include "branch.h"
38#include "promisor-remote.h"
39#include "commit-graph.h"
40#include "shallow.h"
41#include "trace.h"
42#include "trace2.h"
43#include "bundle-uri.h"
44
45#define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
46
47static const char * const builtin_fetch_usage[] = {
48 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
49 N_("git fetch [<options>] <group>"),
50 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
51 N_("git fetch --all [<options>]"),
52 NULL
53};
54
55enum {
56 TAGS_UNSET = 0,
57 TAGS_DEFAULT = 1,
58 TAGS_SET = 2
59};
60
61enum display_format {
62 DISPLAY_FORMAT_FULL,
63 DISPLAY_FORMAT_COMPACT,
64 DISPLAY_FORMAT_PORCELAIN,
65};
66
67struct display_state {
68 struct strbuf buf;
69
70 int refcol_width;
71 enum display_format format;
72
73 char *url;
74 int url_len, shown_url;
75};
76
77static uint64_t forced_updates_ms = 0;
78static int prefetch = 0;
79static int prune = -1; /* unspecified */
80#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
81
82static int prune_tags = -1; /* unspecified */
83#define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
84
85static int append, dry_run, force, keep, update_head_ok;
86static int write_fetch_head = 1;
87static int verbosity, deepen_relative, set_upstream, refetch;
88static int progress = -1;
89static int tags = TAGS_DEFAULT, update_shallow, deepen;
90static int atomic_fetch;
91static enum transport_family family;
92static const char *depth;
93static const char *deepen_since;
94static const char *upload_pack;
95static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
96static struct strbuf default_rla = STRBUF_INIT;
97static struct transport *gtransport;
98static struct transport *gsecondary;
99static struct refspec refmap = REFSPEC_INIT_FETCH;
100static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
101static struct string_list server_options = STRING_LIST_INIT_DUP;
102static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
103
104struct fetch_config {
105 enum display_format display_format;
106 int all;
107 int prune;
108 int prune_tags;
109 int show_forced_updates;
110 int recurse_submodules;
111 int parallel;
112 int submodule_fetch_jobs;
113};
114
115static int git_fetch_config(const char *k, const char *v,
116 const struct config_context *ctx, void *cb)
117{
118 struct fetch_config *fetch_config = cb;
119
120 if (!strcmp(k, "fetch.all")) {
121 fetch_config->all = git_config_bool(k, v);
122 return 0;
123 }
124
125 if (!strcmp(k, "fetch.prune")) {
126 fetch_config->prune = git_config_bool(k, v);
127 return 0;
128 }
129
130 if (!strcmp(k, "fetch.prunetags")) {
131 fetch_config->prune_tags = git_config_bool(k, v);
132 return 0;
133 }
134
135 if (!strcmp(k, "fetch.showforcedupdates")) {
136 fetch_config->show_forced_updates = git_config_bool(k, v);
137 return 0;
138 }
139
140 if (!strcmp(k, "submodule.recurse")) {
141 int r = git_config_bool(k, v) ?
142 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
143 fetch_config->recurse_submodules = r;
144 return 0;
145 }
146
147 if (!strcmp(k, "submodule.fetchjobs")) {
148 fetch_config->submodule_fetch_jobs = parse_submodule_fetchjobs(k, v, ctx->kvi);
149 return 0;
150 } else if (!strcmp(k, "fetch.recursesubmodules")) {
151 fetch_config->recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
152 return 0;
153 }
154
155 if (!strcmp(k, "fetch.parallel")) {
156 fetch_config->parallel = git_config_int(k, v, ctx->kvi);
157 if (fetch_config->parallel < 0)
158 die(_("fetch.parallel cannot be negative"));
159 if (!fetch_config->parallel)
160 fetch_config->parallel = online_cpus();
161 return 0;
162 }
163
164 if (!strcmp(k, "fetch.output")) {
165 if (!v)
166 return config_error_nonbool(k);
167 else if (!strcasecmp(v, "full"))
168 fetch_config->display_format = DISPLAY_FORMAT_FULL;
169 else if (!strcasecmp(v, "compact"))
170 fetch_config->display_format = DISPLAY_FORMAT_COMPACT;
171 else
172 die(_("invalid value for '%s': '%s'"),
173 "fetch.output", v);
174 }
175
176 return git_default_config(k, v, ctx, cb);
177}
178
179static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
180{
181 BUG_ON_OPT_NEG(unset);
182
183 /*
184 * "git fetch --refmap='' origin foo"
185 * can be used to tell the command not to store anywhere
186 */
187 refspec_append(opt->value, arg);
188
189 return 0;
190}
191
192static void unlock_pack(unsigned int flags)
193{
194 if (gtransport)
195 transport_unlock_pack(gtransport, flags);
196 if (gsecondary)
197 transport_unlock_pack(gsecondary, flags);
198}
199
200static void unlock_pack_atexit(void)
201{
202 unlock_pack(0);
203}
204
205static void unlock_pack_on_signal(int signo)
206{
207 unlock_pack(TRANSPORT_UNLOCK_PACK_IN_SIGNAL_HANDLER);
208 sigchain_pop(signo);
209 raise(signo);
210}
211
212static void add_merge_config(struct ref **head,
213 const struct ref *remote_refs,
214 struct branch *branch,
215 struct ref ***tail)
216{
217 int i;
218
219 for (i = 0; i < branch->merge_nr; i++) {
220 struct ref *rm, **old_tail = *tail;
221 struct refspec_item refspec;
222
223 for (rm = *head; rm; rm = rm->next) {
224 if (branch_merge_matches(branch, i, rm->name)) {
225 rm->fetch_head_status = FETCH_HEAD_MERGE;
226 break;
227 }
228 }
229 if (rm)
230 continue;
231
232 /*
233 * Not fetched to a remote-tracking branch? We need to fetch
234 * it anyway to allow this branch's "branch.$name.merge"
235 * to be honored by 'git pull', but we do not have to
236 * fail if branch.$name.merge is misconfigured to point
237 * at a nonexisting branch. If we were indeed called by
238 * 'git pull', it will notice the misconfiguration because
239 * there is no entry in the resulting FETCH_HEAD marked
240 * for merging.
241 */
242 memset(&refspec, 0, sizeof(refspec));
243 refspec.src = branch->merge[i]->src;
244 get_fetch_map(remote_refs, &refspec, tail, 1);
245 for (rm = *old_tail; rm; rm = rm->next)
246 rm->fetch_head_status = FETCH_HEAD_MERGE;
247 }
248}
249
250static void create_fetch_oidset(struct ref **head, struct oidset *out)
251{
252 struct ref *rm = *head;
253 while (rm) {
254 oidset_insert(out, &rm->old_oid);
255 rm = rm->next;
256 }
257}
258
259struct refname_hash_entry {
260 struct hashmap_entry ent;
261 struct object_id oid;
262 int ignore;
263 char refname[FLEX_ARRAY];
264};
265
266static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data UNUSED,
267 const struct hashmap_entry *eptr,
268 const struct hashmap_entry *entry_or_key,
269 const void *keydata)
270{
271 const struct refname_hash_entry *e1, *e2;
272
273 e1 = container_of(eptr, const struct refname_hash_entry, ent);
274 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
275 return strcmp(e1->refname, keydata ? keydata : e2->refname);
276}
277
278static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
279 const char *refname,
280 const struct object_id *oid)
281{
282 struct refname_hash_entry *ent;
283 size_t len = strlen(refname);
284
285 FLEX_ALLOC_MEM(ent, refname, refname, len);
286 hashmap_entry_init(&ent->ent, strhash(refname));
287 oidcpy(&ent->oid, oid);
288 hashmap_add(map, &ent->ent);
289 return ent;
290}
291
292static int add_one_refname(const char *refname, const char *referent UNUSED,
293 const struct object_id *oid,
294 int flag UNUSED, void *cbdata)
295{
296 struct hashmap *refname_map = cbdata;
297
298 (void) refname_hash_add(refname_map, refname, oid);
299 return 0;
300}
301
302static void refname_hash_init(struct hashmap *map)
303{
304 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
305}
306
307static int refname_hash_exists(struct hashmap *map, const char *refname)
308{
309 return !!hashmap_get_from_hash(map, strhash(refname), refname);
310}
311
312static void clear_item(struct refname_hash_entry *item)
313{
314 item->ignore = 1;
315}
316
317
318static void add_already_queued_tags(const char *refname,
319 const struct object_id *old_oid UNUSED,
320 const struct object_id *new_oid,
321 void *cb_data)
322{
323 struct hashmap *queued_tags = cb_data;
324 if (starts_with(refname, "refs/tags/") && new_oid)
325 (void) refname_hash_add(queued_tags, refname, new_oid);
326}
327
328static void find_non_local_tags(const struct ref *refs,
329 struct ref_transaction *transaction,
330 struct ref **head,
331 struct ref ***tail)
332{
333 struct hashmap existing_refs;
334 struct hashmap remote_refs;
335 struct oidset fetch_oids = OIDSET_INIT;
336 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
337 struct string_list_item *remote_ref_item;
338 const struct ref *ref;
339 struct refname_hash_entry *item = NULL;
340
341 refname_hash_init(&existing_refs);
342 refname_hash_init(&remote_refs);
343 create_fetch_oidset(head, &fetch_oids);
344
345 refs_for_each_ref(get_main_ref_store(the_repository), add_one_refname,
346 &existing_refs);
347
348 /*
349 * If we already have a transaction, then we need to filter out all
350 * tags which have already been queued up.
351 */
352 if (transaction)
353 ref_transaction_for_each_queued_update(transaction,
354 add_already_queued_tags,
355 &existing_refs);
356
357 for (ref = refs; ref; ref = ref->next) {
358 if (!starts_with(ref->name, "refs/tags/"))
359 continue;
360
361 /*
362 * The peeled ref always follows the matching base
363 * ref, so if we see a peeled ref that we don't want
364 * to fetch then we can mark the ref entry in the list
365 * as one to ignore by setting util to NULL.
366 */
367 if (ends_with(ref->name, "^{}")) {
368 if (item &&
369 !has_object(the_repository, &ref->old_oid, 0) &&
370 !oidset_contains(&fetch_oids, &ref->old_oid) &&
371 !has_object(the_repository, &item->oid, 0) &&
372 !oidset_contains(&fetch_oids, &item->oid))
373 clear_item(item);
374 item = NULL;
375 continue;
376 }
377
378 /*
379 * If item is non-NULL here, then we previously saw a
380 * ref not followed by a peeled reference, so we need
381 * to check if it is a lightweight tag that we want to
382 * fetch.
383 */
384 if (item &&
385 !has_object(the_repository, &item->oid, 0) &&
386 !oidset_contains(&fetch_oids, &item->oid))
387 clear_item(item);
388
389 item = NULL;
390
391 /* skip duplicates and refs that we already have */
392 if (refname_hash_exists(&remote_refs, ref->name) ||
393 refname_hash_exists(&existing_refs, ref->name))
394 continue;
395
396 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
397 string_list_insert(&remote_refs_list, ref->name);
398 }
399 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
400
401 /*
402 * We may have a final lightweight tag that needs to be
403 * checked to see if it needs fetching.
404 */
405 if (item &&
406 !has_object(the_repository, &item->oid, 0) &&
407 !oidset_contains(&fetch_oids, &item->oid))
408 clear_item(item);
409
410 /*
411 * For all the tags in the remote_refs_list,
412 * add them to the list of refs to be fetched
413 */
414 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
415 const char *refname = remote_ref_item->string;
416 struct ref *rm;
417 unsigned int hash = strhash(refname);
418
419 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
420 struct refname_hash_entry, ent);
421 if (!item)
422 BUG("unseen remote ref?");
423
424 /* Unless we have already decided to ignore this item... */
425 if (item->ignore)
426 continue;
427
428 rm = alloc_ref(item->refname);
429 rm->peer_ref = alloc_ref(item->refname);
430 oidcpy(&rm->old_oid, &item->oid);
431 **tail = rm;
432 *tail = &rm->next;
433 }
434 hashmap_clear_and_free(&remote_refs, struct refname_hash_entry, ent);
435 string_list_clear(&remote_refs_list, 0);
436 oidset_clear(&fetch_oids);
437}
438
439static void filter_prefetch_refspec(struct refspec *rs)
440{
441 int i;
442
443 if (!prefetch)
444 return;
445
446 for (i = 0; i < rs->nr; i++) {
447 struct strbuf new_dst = STRBUF_INIT;
448 char *old_dst;
449 const char *sub = NULL;
450
451 if (rs->items[i].negative)
452 continue;
453 if (!rs->items[i].dst ||
454 (rs->items[i].src &&
455 starts_with(rs->items[i].src,
456 ref_namespace[NAMESPACE_TAGS].ref))) {
457 int j;
458
459 refspec_item_clear(&rs->items[i]);
460
461 for (j = i + 1; j < rs->nr; j++)
462 rs->items[j - 1] = rs->items[j];
463 rs->nr--;
464 i--;
465 continue;
466 }
467
468 old_dst = rs->items[i].dst;
469 strbuf_addstr(&new_dst, ref_namespace[NAMESPACE_PREFETCH].ref);
470
471 /*
472 * If old_dst starts with "refs/", then place
473 * sub after that prefix. Otherwise, start at
474 * the beginning of the string.
475 */
476 if (!skip_prefix(old_dst, "refs/", &sub))
477 sub = old_dst;
478 strbuf_addstr(&new_dst, sub);
479
480 rs->items[i].dst = strbuf_detach(&new_dst, NULL);
481 rs->items[i].force = 1;
482
483 free(old_dst);
484 }
485}
486
487static struct ref *get_ref_map(struct remote *remote,
488 const struct ref *remote_refs,
489 struct refspec *rs,
490 int tags, int *autotags)
491{
492 int i;
493 struct ref *rm;
494 struct ref *ref_map = NULL;
495 struct ref **tail = &ref_map;
496
497 /* opportunistically-updated references: */
498 struct ref *orefs = NULL, **oref_tail = &orefs;
499
500 struct hashmap existing_refs;
501 int existing_refs_populated = 0;
502
503 filter_prefetch_refspec(rs);
504 if (remote)
505 filter_prefetch_refspec(&remote->fetch);
506
507 if (rs->nr) {
508 struct refspec *fetch_refspec;
509
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;
514 }
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;
518
519 /*
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.
530 *
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.
538 */
539 if (refmap.nr)
540 fetch_refspec = &refmap;
541 else
542 fetch_refspec = &remote->fetch;
543
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;
564 }
565 /*
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.
569 *
570 * Note: has_merge implies non-NULL branch->remote_name
571 */
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;
581 }
582 }
583
584 if (tags == TAGS_SET) {
585 struct refspec_item tag_refspec;
586
587 /* also fetch all tags */
588 refspec_item_init_push(&tag_refspec, TAG_REFSPEC);
589 get_fetch_map(remote_refs, &tag_refspec, &tail, 0);
590 refspec_item_clear(&tag_refspec);
591 } else if (tags == TAGS_DEFAULT && *autotags) {
592 find_non_local_tags(remote_refs, NULL, &ref_map, &tail);
593 }
594
595 /* Now append any refs to be updated opportunistically: */
596 *tail = orefs;
597 for (rm = orefs; rm; rm = rm->next) {
598 rm->fetch_head_status = FETCH_HEAD_IGNORE;
599 tail = &rm->next;
600 }
601
602 /*
603 * apply negative refspecs first, before we remove duplicates. This is
604 * necessary as negative refspecs might remove an otherwise conflicting
605 * duplicate.
606 */
607 if (rs->nr)
608 ref_map = apply_negative_refspecs(ref_map, rs);
609 else
610 ref_map = apply_negative_refspecs(ref_map, &remote->fetch);
611
612 ref_map = ref_remove_duplicates(ref_map);
613
614 for (rm = ref_map; rm; rm = rm->next) {
615 if (rm->peer_ref) {
616 const char *refname = rm->peer_ref->name;
617 struct refname_hash_entry *peer_item;
618 unsigned int hash = strhash(refname);
619
620 if (!existing_refs_populated) {
621 refname_hash_init(&existing_refs);
622 refs_for_each_ref(get_main_ref_store(the_repository),
623 add_one_refname,
624 &existing_refs);
625 existing_refs_populated = 1;
626 }
627
628 peer_item = hashmap_get_entry_from_hash(&existing_refs,
629 hash, refname,
630 struct refname_hash_entry, ent);
631 if (peer_item) {
632 struct object_id *old_oid = &peer_item->oid;
633 oidcpy(&rm->peer_ref->old_oid, old_oid);
634 }
635 }
636 }
637 if (existing_refs_populated)
638 hashmap_clear_and_free(&existing_refs, struct refname_hash_entry, ent);
639
640 return ref_map;
641}
642
643#define STORE_REF_ERROR_OTHER 1
644#define STORE_REF_ERROR_DF_CONFLICT 2
645
646static int s_update_ref(const char *action,
647 struct ref *ref,
648 struct ref_transaction *transaction,
649 int check_old)
650{
651 char *msg;
652 char *rla = getenv("GIT_REFLOG_ACTION");
653 struct ref_transaction *our_transaction = NULL;
654 struct strbuf err = STRBUF_INIT;
655 int ret;
656
657 if (dry_run)
658 return 0;
659 if (!rla)
660 rla = default_rla.buf;
661 msg = xstrfmt("%s: %s", rla, action);
662
663 /*
664 * If no transaction was passed to us, we manage the transaction
665 * ourselves. Otherwise, we trust the caller to handle the transaction
666 * lifecycle.
667 */
668 if (!transaction) {
669 transaction = our_transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
670 0, &err);
671 if (!transaction) {
672 ret = STORE_REF_ERROR_OTHER;
673 goto out;
674 }
675 }
676
677 ret = ref_transaction_update(transaction, ref->name, &ref->new_oid,
678 check_old ? &ref->old_oid : NULL,
679 NULL, NULL, 0, msg, &err);
680 if (ret) {
681 ret = STORE_REF_ERROR_OTHER;
682 goto out;
683 }
684
685 if (our_transaction) {
686 switch (ref_transaction_commit(our_transaction, &err)) {
687 case 0:
688 break;
689 case REF_TRANSACTION_ERROR_NAME_CONFLICT:
690 ret = STORE_REF_ERROR_DF_CONFLICT;
691 goto out;
692 default:
693 ret = STORE_REF_ERROR_OTHER;
694 goto out;
695 }
696 }
697
698out:
699 ref_transaction_free(our_transaction);
700 if (ret)
701 error("%s", err.buf);
702 strbuf_release(&err);
703 free(msg);
704 return ret;
705}
706
707static int refcol_width(const struct ref *ref_map, int compact_format)
708{
709 const struct ref *ref;
710 int max, width = 10;
711
712 max = term_columns();
713 if (compact_format)
714 max = max * 2 / 3;
715
716 for (ref = ref_map; ref; ref = ref->next) {
717 int rlen, llen = 0, len;
718
719 if (ref->status == REF_STATUS_REJECT_SHALLOW ||
720 !ref->peer_ref ||
721 !strcmp(ref->name, "HEAD"))
722 continue;
723
724 /* uptodate lines are only shown on high verbosity level */
725 if (verbosity <= 0 && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
726 continue;
727
728 rlen = utf8_strwidth(prettify_refname(ref->name));
729 if (!compact_format)
730 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
731
732 /*
733 * rough estimation to see if the output line is too long and
734 * should not be counted (we can't do precise calculation
735 * anyway because we don't know if the error explanation part
736 * will be printed in update_local_ref)
737 */
738 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
739 if (len >= max)
740 continue;
741
742 if (width < rlen)
743 width = rlen;
744 }
745
746 return width;
747}
748
749static void display_state_init(struct display_state *display_state, struct ref *ref_map,
750 const char *raw_url, enum display_format format)
751{
752 int i;
753
754 memset(display_state, 0, sizeof(*display_state));
755 strbuf_init(&display_state->buf, 0);
756 display_state->format = format;
757
758 if (raw_url)
759 display_state->url = transport_anonymize_url(raw_url);
760 else
761 display_state->url = xstrdup("foreign");
762
763 display_state->url_len = strlen(display_state->url);
764 for (i = display_state->url_len - 1; display_state->url[i] == '/' && 0 <= i; i--)
765 ;
766 display_state->url_len = i + 1;
767 if (4 < i && !strncmp(".git", display_state->url + i - 3, 4))
768 display_state->url_len = i - 3;
769
770 if (verbosity < 0)
771 return;
772
773 switch (display_state->format) {
774 case DISPLAY_FORMAT_FULL:
775 case DISPLAY_FORMAT_COMPACT:
776 display_state->refcol_width = refcol_width(ref_map,
777 display_state->format == DISPLAY_FORMAT_COMPACT);
778 break;
779 case DISPLAY_FORMAT_PORCELAIN:
780 /* We don't need to precompute anything here. */
781 break;
782 default:
783 BUG("unexpected display format %d", display_state->format);
784 }
785}
786
787static void display_state_release(struct display_state *display_state)
788{
789 strbuf_release(&display_state->buf);
790 free(display_state->url);
791}
792
793static void print_remote_to_local(struct display_state *display_state,
794 const char *remote, const char *local)
795{
796 strbuf_addf(&display_state->buf, "%-*s -> %s",
797 display_state->refcol_width, remote, local);
798}
799
800static int find_and_replace(struct strbuf *haystack,
801 const char *needle,
802 const char *placeholder)
803{
804 const char *p = NULL;
805 int plen, nlen;
806
807 nlen = strlen(needle);
808 if (ends_with(haystack->buf, needle))
809 p = haystack->buf + haystack->len - nlen;
810 else
811 p = strstr(haystack->buf, needle);
812 if (!p)
813 return 0;
814
815 if (p > haystack->buf && p[-1] != '/')
816 return 0;
817
818 plen = strlen(p);
819 if (plen > nlen && p[nlen] != '/')
820 return 0;
821
822 strbuf_splice(haystack, p - haystack->buf, nlen,
823 placeholder, strlen(placeholder));
824 return 1;
825}
826
827static void print_compact(struct display_state *display_state,
828 const char *remote, const char *local)
829{
830 struct strbuf r = STRBUF_INIT;
831 struct strbuf l = STRBUF_INIT;
832
833 if (!strcmp(remote, local)) {
834 strbuf_addf(&display_state->buf, "%-*s -> *", display_state->refcol_width, remote);
835 return;
836 }
837
838 strbuf_addstr(&r, remote);
839 strbuf_addstr(&l, local);
840
841 if (!find_and_replace(&r, local, "*"))
842 find_and_replace(&l, remote, "*");
843 print_remote_to_local(display_state, r.buf, l.buf);
844
845 strbuf_release(&r);
846 strbuf_release(&l);
847}
848
849static void display_ref_update(struct display_state *display_state, char code,
850 const char *summary, const char *error,
851 const char *remote, const char *local,
852 const struct object_id *old_oid,
853 const struct object_id *new_oid,
854 int summary_width)
855{
856 FILE *f = stderr;
857
858 if (verbosity < 0)
859 return;
860
861 strbuf_reset(&display_state->buf);
862
863 switch (display_state->format) {
864 case DISPLAY_FORMAT_FULL:
865 case DISPLAY_FORMAT_COMPACT: {
866 int width;
867
868 if (!display_state->shown_url) {
869 strbuf_addf(&display_state->buf, _("From %.*s\n"),
870 display_state->url_len, display_state->url);
871 display_state->shown_url = 1;
872 }
873
874 width = (summary_width + strlen(summary) - gettext_width(summary));
875 remote = prettify_refname(remote);
876 local = prettify_refname(local);
877
878 strbuf_addf(&display_state->buf, " %c %-*s ", code, width, summary);
879
880 if (display_state->format != DISPLAY_FORMAT_COMPACT)
881 print_remote_to_local(display_state, remote, local);
882 else
883 print_compact(display_state, remote, local);
884
885 if (error)
886 strbuf_addf(&display_state->buf, " (%s)", error);
887
888 break;
889 }
890 case DISPLAY_FORMAT_PORCELAIN:
891 strbuf_addf(&display_state->buf, "%c %s %s %s", code,
892 oid_to_hex(old_oid), oid_to_hex(new_oid), local);
893 f = stdout;
894 break;
895 default:
896 BUG("unexpected display format %d", display_state->format);
897 };
898 strbuf_addch(&display_state->buf, '\n');
899
900 fputs(display_state->buf.buf, f);
901}
902
903static int update_local_ref(struct ref *ref,
904 struct ref_transaction *transaction,
905 struct display_state *display_state,
906 const struct ref *remote_ref,
907 int summary_width,
908 const struct fetch_config *config)
909{
910 struct commit *current = NULL, *updated;
911 int fast_forward = 0;
912
913 if (!has_object(the_repository, &ref->new_oid,
914 HAS_OBJECT_RECHECK_PACKED | HAS_OBJECT_FETCH_PROMISOR))
915 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
916
917 if (oideq(&ref->old_oid, &ref->new_oid)) {
918 if (verbosity > 0)
919 display_ref_update(display_state, '=', _("[up to date]"), NULL,
920 remote_ref->name, ref->name,
921 &ref->old_oid, &ref->new_oid, summary_width);
922 return 0;
923 }
924
925 if (!update_head_ok &&
926 !is_null_oid(&ref->old_oid) &&
927 branch_checked_out(ref->name)) {
928 /*
929 * If this is the head, and it's not okay to update
930 * the head, and the old value of the head isn't empty...
931 */
932 display_ref_update(display_state, '!', _("[rejected]"),
933 _("can't fetch into checked-out branch"),
934 remote_ref->name, ref->name,
935 &ref->old_oid, &ref->new_oid, summary_width);
936 return 1;
937 }
938
939 if (!is_null_oid(&ref->old_oid) &&
940 starts_with(ref->name, "refs/tags/")) {
941 if (force || ref->force) {
942 int r;
943 r = s_update_ref("updating tag", ref, transaction, 0);
944 display_ref_update(display_state, r ? '!' : 't', _("[tag update]"),
945 r ? _("unable to update local ref") : NULL,
946 remote_ref->name, ref->name,
947 &ref->old_oid, &ref->new_oid, summary_width);
948 return r;
949 } else {
950 display_ref_update(display_state, '!', _("[rejected]"),
951 _("would clobber existing tag"),
952 remote_ref->name, ref->name,
953 &ref->old_oid, &ref->new_oid, summary_width);
954 return 1;
955 }
956 }
957
958 current = lookup_commit_reference_gently(the_repository,
959 &ref->old_oid, 1);
960 updated = lookup_commit_reference_gently(the_repository,
961 &ref->new_oid, 1);
962 if (!current || !updated) {
963 const char *msg;
964 const char *what;
965 int r;
966 /*
967 * Nicely describe the new ref we're fetching.
968 * Base this on the remote's ref name, as it's
969 * more likely to follow a standard layout.
970 */
971 if (starts_with(remote_ref->name, "refs/tags/")) {
972 msg = "storing tag";
973 what = _("[new tag]");
974 } else if (starts_with(remote_ref->name, "refs/heads/")) {
975 msg = "storing head";
976 what = _("[new branch]");
977 } else {
978 msg = "storing ref";
979 what = _("[new ref]");
980 }
981
982 r = s_update_ref(msg, ref, transaction, 0);
983 display_ref_update(display_state, r ? '!' : '*', what,
984 r ? _("unable to update local ref") : NULL,
985 remote_ref->name, ref->name,
986 &ref->old_oid, &ref->new_oid, summary_width);
987 return r;
988 }
989
990 if (config->show_forced_updates) {
991 uint64_t t_before = getnanotime();
992 fast_forward = repo_in_merge_bases(the_repository, current,
993 updated);
994 if (fast_forward < 0)
995 die(NULL);
996 forced_updates_ms += (getnanotime() - t_before) / 1000000;
997 } else {
998 fast_forward = 1;
999 }
1000
1001 if (fast_forward) {
1002 struct strbuf quickref = STRBUF_INIT;
1003 int r;
1004
1005 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1006 strbuf_addstr(&quickref, "..");
1007 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1008 r = s_update_ref("fast-forward", ref, transaction, 1);
1009 display_ref_update(display_state, r ? '!' : ' ', quickref.buf,
1010 r ? _("unable to update local ref") : NULL,
1011 remote_ref->name, ref->name,
1012 &ref->old_oid, &ref->new_oid, summary_width);
1013 strbuf_release(&quickref);
1014 return r;
1015 } else if (force || ref->force) {
1016 struct strbuf quickref = STRBUF_INIT;
1017 int r;
1018 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
1019 strbuf_addstr(&quickref, "...");
1020 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
1021 r = s_update_ref("forced-update", ref, transaction, 1);
1022 display_ref_update(display_state, r ? '!' : '+', quickref.buf,
1023 r ? _("unable to update local ref") : _("forced update"),
1024 remote_ref->name, ref->name,
1025 &ref->old_oid, &ref->new_oid, summary_width);
1026 strbuf_release(&quickref);
1027 return r;
1028 } else {
1029 display_ref_update(display_state, '!', _("[rejected]"), _("non-fast-forward"),
1030 remote_ref->name, ref->name,
1031 &ref->old_oid, &ref->new_oid, summary_width);
1032 return 1;
1033 }
1034}
1035
1036static const struct object_id *iterate_ref_map(void *cb_data)
1037{
1038 struct ref **rm = cb_data;
1039 struct ref *ref = *rm;
1040
1041 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1042 ref = ref->next;
1043 if (!ref)
1044 return NULL;
1045 *rm = ref->next;
1046 return &ref->old_oid;
1047}
1048
1049struct fetch_head {
1050 FILE *fp;
1051 struct strbuf buf;
1052};
1053
1054static int open_fetch_head(struct fetch_head *fetch_head)
1055{
1056 const char *filename = git_path_fetch_head(the_repository);
1057
1058 if (write_fetch_head) {
1059 fetch_head->fp = fopen(filename, "a");
1060 if (!fetch_head->fp)
1061 return error_errno(_("cannot open '%s'"), filename);
1062 strbuf_init(&fetch_head->buf, 0);
1063 } else {
1064 fetch_head->fp = NULL;
1065 }
1066
1067 return 0;
1068}
1069
1070static void append_fetch_head(struct fetch_head *fetch_head,
1071 const struct object_id *old_oid,
1072 enum fetch_head_status fetch_head_status,
1073 const char *note,
1074 const char *url, size_t url_len)
1075{
1076 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1077 const char *merge_status_marker;
1078 size_t i;
1079
1080 if (!fetch_head->fp)
1081 return;
1082
1083 switch (fetch_head_status) {
1084 case FETCH_HEAD_NOT_FOR_MERGE:
1085 merge_status_marker = "not-for-merge";
1086 break;
1087 case FETCH_HEAD_MERGE:
1088 merge_status_marker = "";
1089 break;
1090 default:
1091 /* do not write anything to FETCH_HEAD */
1092 return;
1093 }
1094
1095 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1096 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1097 for (i = 0; i < url_len; ++i)
1098 if ('\n' == url[i])
1099 strbuf_addstr(&fetch_head->buf, "\\n");
1100 else
1101 strbuf_addch(&fetch_head->buf, url[i]);
1102 strbuf_addch(&fetch_head->buf, '\n');
1103
1104 /*
1105 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1106 * any of the reference updates fails. We thus have to write all
1107 * updates to a buffer first and only commit it as soon as all
1108 * references have been successfully updated.
1109 */
1110 if (!atomic_fetch) {
1111 strbuf_write(&fetch_head->buf, fetch_head->fp);
1112 strbuf_reset(&fetch_head->buf);
1113 }
1114}
1115
1116static void commit_fetch_head(struct fetch_head *fetch_head)
1117{
1118 if (!fetch_head->fp || !atomic_fetch)
1119 return;
1120 strbuf_write(&fetch_head->buf, fetch_head->fp);
1121}
1122
1123static void close_fetch_head(struct fetch_head *fetch_head)
1124{
1125 if (!fetch_head->fp)
1126 return;
1127
1128 fclose(fetch_head->fp);
1129 strbuf_release(&fetch_head->buf);
1130}
1131
1132static const char warn_show_forced_updates[] =
1133N_("fetch normally indicates which branches had a forced update,\n"
1134 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1135 "flag or run 'git config fetch.showForcedUpdates true'");
1136static const char warn_time_show_forced_updates[] =
1137N_("it took %.2f seconds to check forced updates; you can use\n"
1138 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1139 "to avoid this check\n");
1140
1141static int store_updated_refs(struct display_state *display_state,
1142 const char *remote_name,
1143 int connectivity_checked,
1144 struct ref_transaction *transaction, struct ref *ref_map,
1145 struct fetch_head *fetch_head,
1146 const struct fetch_config *config)
1147{
1148 int rc = 0;
1149 struct strbuf note = STRBUF_INIT;
1150 const char *what, *kind;
1151 struct ref *rm;
1152 int want_status;
1153 int summary_width = 0;
1154
1155 if (verbosity >= 0)
1156 summary_width = transport_summary_width(ref_map);
1157
1158 if (!connectivity_checked) {
1159 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1160
1161 opt.exclude_hidden_refs_section = "fetch";
1162 rm = ref_map;
1163 if (check_connected(iterate_ref_map, &rm, &opt)) {
1164 rc = error(_("%s did not send all necessary objects"),
1165 display_state->url);
1166 goto abort;
1167 }
1168 }
1169
1170 /*
1171 * We do a pass for each fetch_head_status type in their enum order, so
1172 * merged entries are written before not-for-merge. That lets readers
1173 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1174 */
1175 for (want_status = FETCH_HEAD_MERGE;
1176 want_status <= FETCH_HEAD_IGNORE;
1177 want_status++) {
1178 for (rm = ref_map; rm; rm = rm->next) {
1179 struct ref *ref = NULL;
1180
1181 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1182 if (want_status == FETCH_HEAD_MERGE)
1183 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1184 rm->peer_ref ? rm->peer_ref->name : rm->name);
1185 continue;
1186 }
1187
1188 /*
1189 * When writing FETCH_HEAD we need to determine whether
1190 * we already have the commit or not. If not, then the
1191 * reference is not for merge and needs to be written
1192 * to the reflog after other commits which we already
1193 * have. We're not interested in this property though
1194 * in case FETCH_HEAD is not to be updated, so we can
1195 * skip the classification in that case.
1196 */
1197 if (fetch_head->fp) {
1198 struct commit *commit = NULL;
1199
1200 /*
1201 * References in "refs/tags/" are often going to point
1202 * to annotated tags, which are not part of the
1203 * commit-graph. We thus only try to look up refs in
1204 * the graph which are not in that namespace to not
1205 * regress performance in repositories with many
1206 * annotated tags.
1207 */
1208 if (!starts_with(rm->name, "refs/tags/"))
1209 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1210 if (!commit) {
1211 commit = lookup_commit_reference_gently(the_repository,
1212 &rm->old_oid,
1213 1);
1214 if (!commit)
1215 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1216 }
1217 }
1218
1219 if (rm->fetch_head_status != want_status)
1220 continue;
1221
1222 if (rm->peer_ref) {
1223 ref = alloc_ref(rm->peer_ref->name);
1224 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1225 oidcpy(&ref->new_oid, &rm->old_oid);
1226 ref->force = rm->peer_ref->force;
1227 }
1228
1229 if (config->recurse_submodules != RECURSE_SUBMODULES_OFF &&
1230 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1231 check_for_new_submodule_commits(&rm->old_oid);
1232 }
1233
1234 if (!strcmp(rm->name, "HEAD")) {
1235 kind = "";
1236 what = "";
1237 } else if (skip_prefix(rm->name, "refs/heads/", &what)) {
1238 kind = "branch";
1239 } else if (skip_prefix(rm->name, "refs/tags/", &what)) {
1240 kind = "tag";
1241 } else if (skip_prefix(rm->name, "refs/remotes/", &what)) {
1242 kind = "remote-tracking branch";
1243 } else {
1244 kind = "";
1245 what = rm->name;
1246 }
1247
1248 strbuf_reset(&note);
1249 if (*what) {
1250 if (*kind)
1251 strbuf_addf(&note, "%s ", kind);
1252 strbuf_addf(&note, "'%s' of ", what);
1253 }
1254
1255 append_fetch_head(fetch_head, &rm->old_oid,
1256 rm->fetch_head_status,
1257 note.buf, display_state->url,
1258 display_state->url_len);
1259
1260 if (ref) {
1261 rc |= update_local_ref(ref, transaction, display_state,
1262 rm, summary_width, config);
1263 free(ref);
1264 } else if (write_fetch_head || dry_run) {
1265 /*
1266 * Display fetches written to FETCH_HEAD (or
1267 * would be written to FETCH_HEAD, if --dry-run
1268 * is set).
1269 */
1270 display_ref_update(display_state, '*',
1271 *kind ? kind : "branch", NULL,
1272 rm->name,
1273 "FETCH_HEAD",
1274 &rm->new_oid, &rm->old_oid,
1275 summary_width);
1276 }
1277 }
1278 }
1279
1280 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1281 error(_("some local refs could not be updated; try running\n"
1282 " 'git remote prune %s' to remove any old, conflicting "
1283 "branches"), remote_name);
1284
1285 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1286 if (!config->show_forced_updates) {
1287 warning(_(warn_show_forced_updates));
1288 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1289 warning(_(warn_time_show_forced_updates),
1290 forced_updates_ms / 1000.0);
1291 }
1292 }
1293
1294 abort:
1295 strbuf_release(&note);
1296 return rc;
1297}
1298
1299/*
1300 * We would want to bypass the object transfer altogether if
1301 * everything we are going to fetch already exists and is connected
1302 * locally.
1303 */
1304static int check_exist_and_connected(struct ref *ref_map)
1305{
1306 struct ref *rm = ref_map;
1307 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1308 struct ref *r;
1309
1310 /*
1311 * If we are deepening a shallow clone we already have these
1312 * objects reachable. Running rev-list here will return with
1313 * a good (0) exit status and we'll bypass the fetch that we
1314 * really need to perform. Claiming failure now will ensure
1315 * we perform the network exchange to deepen our history.
1316 */
1317 if (deepen)
1318 return -1;
1319
1320 /*
1321 * Similarly, if we need to refetch, we always want to perform a full
1322 * fetch ignoring existing objects.
1323 */
1324 if (refetch)
1325 return -1;
1326
1327
1328 /*
1329 * check_connected() allows objects to merely be promised, but
1330 * we need all direct targets to exist.
1331 */
1332 for (r = rm; r; r = r->next) {
1333 if (!has_object(the_repository, &r->old_oid, HAS_OBJECT_RECHECK_PACKED))
1334 return -1;
1335 }
1336
1337 opt.quiet = 1;
1338 opt.exclude_hidden_refs_section = "fetch";
1339 return check_connected(iterate_ref_map, &rm, &opt);
1340}
1341
1342static int fetch_and_consume_refs(struct display_state *display_state,
1343 struct transport *transport,
1344 struct ref_transaction *transaction,
1345 struct ref *ref_map,
1346 struct fetch_head *fetch_head,
1347 const struct fetch_config *config)
1348{
1349 int connectivity_checked = 1;
1350 int ret;
1351
1352 /*
1353 * We don't need to perform a fetch in case we can already satisfy all
1354 * refs.
1355 */
1356 ret = check_exist_and_connected(ref_map);
1357 if (ret) {
1358 trace2_region_enter("fetch", "fetch_refs", the_repository);
1359 ret = transport_fetch_refs(transport, ref_map);
1360 trace2_region_leave("fetch", "fetch_refs", the_repository);
1361 if (ret)
1362 goto out;
1363 connectivity_checked = transport->smart_options ?
1364 transport->smart_options->connectivity_checked : 0;
1365 }
1366
1367 trace2_region_enter("fetch", "consume_refs", the_repository);
1368 ret = store_updated_refs(display_state, transport->remote->name,
1369 connectivity_checked, transaction, ref_map,
1370 fetch_head, config);
1371 trace2_region_leave("fetch", "consume_refs", the_repository);
1372
1373out:
1374 transport_unlock_pack(transport, 0);
1375 return ret;
1376}
1377
1378static int prune_refs(struct display_state *display_state,
1379 struct refspec *rs,
1380 struct ref_transaction *transaction,
1381 struct ref *ref_map)
1382{
1383 int result = 0;
1384 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1385 struct strbuf err = STRBUF_INIT;
1386 const char *dangling_msg = dry_run
1387 ? _(" (%s will become dangling)")
1388 : _(" (%s has become dangling)");
1389
1390 if (!dry_run) {
1391 if (transaction) {
1392 for (ref = stale_refs; ref; ref = ref->next) {
1393 result = ref_transaction_delete(transaction, ref->name, NULL,
1394 NULL, 0, "fetch: prune", &err);
1395 if (result)
1396 goto cleanup;
1397 }
1398 } else {
1399 struct string_list refnames = STRING_LIST_INIT_NODUP;
1400
1401 for (ref = stale_refs; ref; ref = ref->next)
1402 string_list_append(&refnames, ref->name);
1403
1404 result = refs_delete_refs(get_main_ref_store(the_repository),
1405 "fetch: prune", &refnames,
1406 0);
1407 string_list_clear(&refnames, 0);
1408 }
1409 }
1410
1411 if (verbosity >= 0) {
1412 int summary_width = transport_summary_width(stale_refs);
1413
1414 for (ref = stale_refs; ref; ref = ref->next) {
1415 display_ref_update(display_state, '-', _("[deleted]"), NULL,
1416 _("(none)"), ref->name,
1417 &ref->new_oid, &ref->old_oid,
1418 summary_width);
1419 refs_warn_dangling_symref(get_main_ref_store(the_repository),
1420 stderr, dangling_msg, ref->name);
1421 }
1422 }
1423
1424cleanup:
1425 strbuf_release(&err);
1426 free_refs(stale_refs);
1427 return result;
1428}
1429
1430static void check_not_current_branch(struct ref *ref_map)
1431{
1432 const char *path;
1433 for (; ref_map; ref_map = ref_map->next)
1434 if (ref_map->peer_ref &&
1435 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1436 (path = branch_checked_out(ref_map->peer_ref->name)))
1437 die(_("refusing to fetch into branch '%s' "
1438 "checked out at '%s'"),
1439 ref_map->peer_ref->name, path);
1440}
1441
1442static int truncate_fetch_head(void)
1443{
1444 const char *filename = git_path_fetch_head(the_repository);
1445 FILE *fp = fopen_for_writing(filename);
1446
1447 if (!fp)
1448 return error_errno(_("cannot open '%s'"), filename);
1449 fclose(fp);
1450 return 0;
1451}
1452
1453static void set_option(struct transport *transport, const char *name, const char *value)
1454{
1455 int r = transport_set_option(transport, name, value);
1456 if (r < 0)
1457 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1458 name, value, transport->url);
1459 if (r > 0)
1460 warning(_("option \"%s\" is ignored for %s"),
1461 name, transport->url);
1462}
1463
1464
1465static int add_oid(const char *refname UNUSED,
1466 const char *referent UNUSED,
1467 const struct object_id *oid,
1468 int flags UNUSED, void *cb_data)
1469{
1470 struct oid_array *oids = cb_data;
1471
1472 oid_array_append(oids, oid);
1473 return 0;
1474}
1475
1476static void add_negotiation_tips(struct git_transport_options *smart_options)
1477{
1478 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1479 int i;
1480
1481 for (i = 0; i < negotiation_tip.nr; i++) {
1482 const char *s = negotiation_tip.items[i].string;
1483 int old_nr;
1484 if (!has_glob_specials(s)) {
1485 struct object_id oid;
1486 if (repo_get_oid(the_repository, s, &oid))
1487 die(_("%s is not a valid object"), s);
1488 if (!has_object(the_repository, &oid, 0))
1489 die(_("the object %s does not exist"), s);
1490 oid_array_append(oids, &oid);
1491 continue;
1492 }
1493 old_nr = oids->nr;
1494 refs_for_each_glob_ref(get_main_ref_store(the_repository),
1495 add_oid, s, oids);
1496 if (old_nr == oids->nr)
1497 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1498 s);
1499 }
1500 smart_options->negotiation_tips = oids;
1501}
1502
1503static struct transport *prepare_transport(struct remote *remote, int deepen)
1504{
1505 struct transport *transport;
1506
1507 transport = transport_get(remote, NULL);
1508 transport_set_verbosity(transport, verbosity, progress);
1509 transport->family = family;
1510 if (upload_pack)
1511 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1512 if (keep)
1513 set_option(transport, TRANS_OPT_KEEP, "yes");
1514 if (depth)
1515 set_option(transport, TRANS_OPT_DEPTH, depth);
1516 if (deepen && deepen_since)
1517 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1518 if (deepen && deepen_not.nr)
1519 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1520 (const char *)&deepen_not);
1521 if (deepen_relative)
1522 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1523 if (update_shallow)
1524 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1525 if (refetch)
1526 set_option(transport, TRANS_OPT_REFETCH, "yes");
1527 if (filter_options.choice) {
1528 const char *spec =
1529 expand_list_objects_filter_spec(&filter_options);
1530 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1531 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1532 }
1533 if (negotiation_tip.nr) {
1534 if (transport->smart_options)
1535 add_negotiation_tips(transport->smart_options);
1536 else
1537 warning("ignoring --negotiation-tip because the protocol does not support it");
1538 }
1539 return transport;
1540}
1541
1542static int backfill_tags(struct display_state *display_state,
1543 struct transport *transport,
1544 struct ref_transaction *transaction,
1545 struct ref *ref_map,
1546 struct fetch_head *fetch_head,
1547 const struct fetch_config *config)
1548{
1549 int retcode, cannot_reuse;
1550
1551 /*
1552 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1553 * when remote helper is used (setting it to an empty string
1554 * is not unsetting). We could extend the remote helper
1555 * protocol for that, but for now, just force a new connection
1556 * without deepen-since. Similar story for deepen-not.
1557 */
1558 cannot_reuse = transport->cannot_reuse ||
1559 deepen_since || deepen_not.nr;
1560 if (cannot_reuse) {
1561 gsecondary = prepare_transport(transport->remote, 0);
1562 transport = gsecondary;
1563 }
1564
1565 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1566 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1567 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1568 retcode = fetch_and_consume_refs(display_state, transport, transaction, ref_map,
1569 fetch_head, config);
1570
1571 if (gsecondary) {
1572 transport_disconnect(gsecondary);
1573 gsecondary = NULL;
1574 }
1575
1576 return retcode;
1577}
1578
1579static const char *strip_refshead(const char *name){
1580 skip_prefix(name, "refs/heads/", &name);
1581 return name;
1582}
1583
1584static void set_head_advice_msg(const char *remote, const char *head_name)
1585{
1586 const char message_advice_set_head[] =
1587 N_("Run 'git remote set-head %s %s' to follow the change, or set\n"
1588 "'remote.%s.followRemoteHEAD' configuration option to a different value\n"
1589 "if you do not want to see this message. Specifically running\n"
1590 "'git config set remote.%s.followRemoteHEAD warn-if-not-branch-%s'\n"
1591 "will disable the warning until the remote changes HEAD to something else.");
1592
1593 advise_if_enabled(ADVICE_FETCH_SET_HEAD_WARN, _(message_advice_set_head),
1594 remote, head_name, remote, remote, head_name);
1595}
1596
1597static void report_set_head(const char *remote, const char *head_name,
1598 struct strbuf *buf_prev, int updateres) {
1599 struct strbuf buf_prefix = STRBUF_INIT;
1600 const char *prev_head = NULL;
1601
1602 strbuf_addf(&buf_prefix, "refs/remotes/%s/", remote);
1603 skip_prefix(buf_prev->buf, buf_prefix.buf, &prev_head);
1604
1605 if (prev_head && strcmp(prev_head, head_name)) {
1606 printf("'HEAD' at '%s' is '%s', but we have '%s' locally.\n",
1607 remote, head_name, prev_head);
1608 set_head_advice_msg(remote, head_name);
1609 }
1610 else if (updateres && buf_prev->len) {
1611 printf("'HEAD' at '%s' is '%s', "
1612 "but we have a detached HEAD pointing to '%s' locally.\n",
1613 remote, head_name, buf_prev->buf);
1614 set_head_advice_msg(remote, head_name);
1615 }
1616 strbuf_release(&buf_prefix);
1617}
1618
1619static int set_head(const struct ref *remote_refs, struct remote *remote)
1620{
1621 int result = 0, create_only, baremirror, was_detached;
1622 struct strbuf b_head = STRBUF_INIT, b_remote_head = STRBUF_INIT,
1623 b_local_head = STRBUF_INIT;
1624 int follow_remote_head = remote->follow_remote_head;
1625 const char *no_warn_branch = remote->no_warn_branch;
1626 char *head_name = NULL;
1627 struct ref *ref, *matches;
1628 struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
1629 struct refspec_item refspec = {
1630 .force = 0,
1631 .pattern = 1,
1632 .src = (char *) "refs/heads/*",
1633 .dst = (char *) "refs/heads/*",
1634 };
1635 struct string_list heads = STRING_LIST_INIT_DUP;
1636 struct ref_store *refs = get_main_ref_store(the_repository);
1637
1638 get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
1639 matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
1640 fetch_map, REMOTE_GUESS_HEAD_ALL);
1641 for (ref = matches; ref; ref = ref->next) {
1642 string_list_append(&heads, strip_refshead(ref->name));
1643 }
1644
1645 if (!heads.nr)
1646 result = 1;
1647 else if (heads.nr > 1)
1648 result = 1;
1649 else
1650 head_name = xstrdup(heads.items[0].string);
1651
1652 if (!head_name)
1653 goto cleanup;
1654 baremirror = is_bare_repository() && remote->mirror;
1655 create_only = follow_remote_head == FOLLOW_REMOTE_ALWAYS ? 0 : !baremirror;
1656 if (baremirror) {
1657 strbuf_addstr(&b_head, "HEAD");
1658 strbuf_addf(&b_remote_head, "refs/heads/%s", head_name);
1659 } else {
1660 strbuf_addf(&b_head, "refs/remotes/%s/HEAD", remote->name);
1661 strbuf_addf(&b_remote_head, "refs/remotes/%s/%s", remote->name, head_name);
1662 }
1663 /* make sure it's valid */
1664 if (!baremirror && !refs_ref_exists(refs, b_remote_head.buf)) {
1665 result = 1;
1666 goto cleanup;
1667 }
1668 was_detached = refs_update_symref_extended(refs, b_head.buf, b_remote_head.buf,
1669 "fetch", &b_local_head, create_only);
1670 if (was_detached == -1) {
1671 result = 1;
1672 goto cleanup;
1673 }
1674 if (verbosity >= 0 &&
1675 follow_remote_head == FOLLOW_REMOTE_WARN &&
1676 (!no_warn_branch || strcmp(no_warn_branch, head_name)))
1677 report_set_head(remote->name, head_name, &b_local_head, was_detached);
1678
1679cleanup:
1680 free(head_name);
1681 free_refs(fetch_map);
1682 free_refs(matches);
1683 string_list_clear(&heads, 0);
1684 strbuf_release(&b_head);
1685 strbuf_release(&b_local_head);
1686 strbuf_release(&b_remote_head);
1687 return result;
1688}
1689
1690static int do_fetch(struct transport *transport,
1691 struct refspec *rs,
1692 const struct fetch_config *config)
1693{
1694 struct ref_transaction *transaction = NULL;
1695 struct ref *ref_map = NULL;
1696 struct display_state display_state = { 0 };
1697 int autotags = (transport->remote->fetch_tags == 1);
1698 int retcode = 0;
1699 const struct ref *remote_refs;
1700 struct transport_ls_refs_options transport_ls_refs_options =
1701 TRANSPORT_LS_REFS_OPTIONS_INIT;
1702 struct fetch_head fetch_head = { 0 };
1703 struct strbuf err = STRBUF_INIT;
1704 int do_set_head = 0;
1705
1706 if (tags == TAGS_DEFAULT) {
1707 if (transport->remote->fetch_tags == 2)
1708 tags = TAGS_SET;
1709 if (transport->remote->fetch_tags == -1)
1710 tags = TAGS_UNSET;
1711 }
1712
1713 /* if not appending, truncate FETCH_HEAD */
1714 if (!append && write_fetch_head) {
1715 retcode = truncate_fetch_head();
1716 if (retcode)
1717 goto cleanup;
1718 }
1719
1720 if (rs->nr) {
1721 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1722 } else {
1723 struct branch *branch = branch_get(NULL);
1724
1725 if (transport->remote->fetch.nr) {
1726 refspec_ref_prefixes(&transport->remote->fetch,
1727 &transport_ls_refs_options.ref_prefixes);
1728 if (transport->remote->follow_remote_head != FOLLOW_REMOTE_NEVER)
1729 do_set_head = 1;
1730 }
1731 if (branch && branch_has_merge_config(branch) &&
1732 !strcmp(branch->remote_name, transport->remote->name)) {
1733 int i;
1734 for (i = 0; i < branch->merge_nr; i++) {
1735 strvec_push(&transport_ls_refs_options.ref_prefixes,
1736 branch->merge[i]->src);
1737 }
1738 }
1739
1740 /*
1741 * If there are no refs specified to fetch, then we just
1742 * fetch HEAD; mention that to narrow the advertisement.
1743 */
1744 if (!transport_ls_refs_options.ref_prefixes.nr)
1745 strvec_push(&transport_ls_refs_options.ref_prefixes,
1746 "HEAD");
1747 }
1748
1749 if (tags == TAGS_SET || tags == TAGS_DEFAULT)
1750 strvec_push(&transport_ls_refs_options.ref_prefixes,
1751 "refs/tags/");
1752
1753 if (do_set_head)
1754 strvec_push(&transport_ls_refs_options.ref_prefixes,
1755 "HEAD");
1756
1757 /*
1758 * Only initiate ref listing if we have at least one ref we want to
1759 * know about.
1760 */
1761 if (transport_ls_refs_options.ref_prefixes.nr) {
1762 trace2_region_enter("fetch", "remote_refs", the_repository);
1763 remote_refs = transport_get_remote_refs(transport,
1764 &transport_ls_refs_options);
1765 trace2_region_leave("fetch", "remote_refs", the_repository);
1766 } else
1767 remote_refs = NULL;
1768
1769 transport_ls_refs_options_release(&transport_ls_refs_options);
1770
1771 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1772 tags, &autotags);
1773 if (!update_head_ok)
1774 check_not_current_branch(ref_map);
1775
1776 retcode = open_fetch_head(&fetch_head);
1777 if (retcode)
1778 goto cleanup;
1779
1780 display_state_init(&display_state, ref_map, transport->url,
1781 config->display_format);
1782
1783 if (atomic_fetch) {
1784 transaction = ref_store_transaction_begin(get_main_ref_store(the_repository),
1785 0, &err);
1786 if (!transaction) {
1787 retcode = -1;
1788 goto cleanup;
1789 }
1790 }
1791
1792 if (tags == TAGS_DEFAULT && autotags)
1793 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1794 if (prune) {
1795 /*
1796 * We only prune based on refspecs specified
1797 * explicitly (via command line or configuration); we
1798 * don't care whether --tags was specified.
1799 */
1800 if (rs->nr) {
1801 retcode = prune_refs(&display_state, rs, transaction, ref_map);
1802 } else {
1803 retcode = prune_refs(&display_state, &transport->remote->fetch,
1804 transaction, ref_map);
1805 }
1806 if (retcode != 0)
1807 retcode = 1;
1808 }
1809
1810 if (fetch_and_consume_refs(&display_state, transport, transaction, ref_map,
1811 &fetch_head, config)) {
1812 retcode = 1;
1813 goto cleanup;
1814 }
1815
1816 /*
1817 * If neither --no-tags nor --tags was specified, do automated tag
1818 * following.
1819 */
1820 if (tags == TAGS_DEFAULT && autotags) {
1821 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1822
1823 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1824 if (tags_ref_map) {
1825 /*
1826 * If backfilling of tags fails then we want to tell
1827 * the user so, but we have to continue regardless to
1828 * populate upstream information of the references we
1829 * have already fetched above. The exception though is
1830 * when `--atomic` is passed: in that case we'll abort
1831 * the transaction and don't commit anything.
1832 */
1833 if (backfill_tags(&display_state, transport, transaction, tags_ref_map,
1834 &fetch_head, config))
1835 retcode = 1;
1836 }
1837
1838 free_refs(tags_ref_map);
1839 }
1840
1841 if (transaction) {
1842 if (retcode)
1843 goto cleanup;
1844
1845 retcode = ref_transaction_commit(transaction, &err);
1846 if (retcode) {
1847 /*
1848 * Explicitly handle transaction cleanup to avoid
1849 * aborting an already closed transaction.
1850 */
1851 ref_transaction_free(transaction);
1852 transaction = NULL;
1853 goto cleanup;
1854 }
1855 }
1856
1857 commit_fetch_head(&fetch_head);
1858
1859 if (set_upstream) {
1860 struct branch *branch = branch_get("HEAD");
1861 struct ref *rm;
1862 struct ref *source_ref = NULL;
1863
1864 /*
1865 * We're setting the upstream configuration for the
1866 * current branch. The relevant upstream is the
1867 * fetched branch that is meant to be merged with the
1868 * current one, i.e. the one fetched to FETCH_HEAD.
1869 *
1870 * When there are several such branches, consider the
1871 * request ambiguous and err on the safe side by doing
1872 * nothing and just emit a warning.
1873 */
1874 for (rm = ref_map; rm; rm = rm->next) {
1875 if (!rm->peer_ref) {
1876 if (source_ref) {
1877 warning(_("multiple branches detected, incompatible with --set-upstream"));
1878 goto cleanup;
1879 } else {
1880 source_ref = rm;
1881 }
1882 }
1883 }
1884 if (source_ref) {
1885 if (!branch) {
1886 const char *shortname = source_ref->name;
1887 skip_prefix(shortname, "refs/heads/", &shortname);
1888
1889 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1890 "it does not point to any branch."),
1891 shortname, transport->remote->name);
1892 goto cleanup;
1893 }
1894
1895 if (!strcmp(source_ref->name, "HEAD") ||
1896 starts_with(source_ref->name, "refs/heads/"))
1897 install_branch_config(0,
1898 branch->name,
1899 transport->remote->name,
1900 source_ref->name);
1901 else if (starts_with(source_ref->name, "refs/remotes/"))
1902 warning(_("not setting upstream for a remote remote-tracking branch"));
1903 else if (starts_with(source_ref->name, "refs/tags/"))
1904 warning(_("not setting upstream for a remote tag"));
1905 else
1906 warning(_("unknown branch type"));
1907 } else {
1908 warning(_("no source branch found;\n"
1909 "you need to specify exactly one branch with the --set-upstream option"));
1910 }
1911 }
1912 if (do_set_head) {
1913 /*
1914 * Way too many cases where this can go wrong so let's just
1915 * ignore errors and fail silently for now.
1916 */
1917 set_head(remote_refs, transport->remote);
1918 }
1919
1920cleanup:
1921 if (retcode) {
1922 if (err.len) {
1923 error("%s", err.buf);
1924 strbuf_reset(&err);
1925 }
1926 if (transaction && ref_transaction_abort(transaction, &err) &&
1927 err.len)
1928 error("%s", err.buf);
1929 transaction = NULL;
1930 }
1931
1932 if (transaction)
1933 ref_transaction_free(transaction);
1934 display_state_release(&display_state);
1935 close_fetch_head(&fetch_head);
1936 strbuf_release(&err);
1937 free_refs(ref_map);
1938 return retcode;
1939}
1940
1941static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1942{
1943 struct string_list *list = priv;
1944 if (!remote->skip_default_update)
1945 string_list_append(list, remote->name);
1946 return 0;
1947}
1948
1949struct remote_group_data {
1950 const char *name;
1951 struct string_list *list;
1952};
1953
1954static int get_remote_group(const char *key, const char *value,
1955 const struct config_context *ctx UNUSED,
1956 void *priv)
1957{
1958 struct remote_group_data *g = priv;
1959
1960 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1961 /* split list by white space */
1962 while (*value) {
1963 size_t wordlen = strcspn(value, " \t\n");
1964
1965 if (wordlen >= 1)
1966 string_list_append_nodup(g->list,
1967 xstrndup(value, wordlen));
1968 value += wordlen + (value[wordlen] != '\0');
1969 }
1970 }
1971
1972 return 0;
1973}
1974
1975static int add_remote_or_group(const char *name, struct string_list *list)
1976{
1977 int prev_nr = list->nr;
1978 struct remote_group_data g;
1979 g.name = name; g.list = list;
1980
1981 git_config(get_remote_group, &g);
1982 if (list->nr == prev_nr) {
1983 struct remote *remote = remote_get(name);
1984 if (!remote_is_configured(remote, 0))
1985 return 0;
1986 string_list_append(list, remote->name);
1987 }
1988 return 1;
1989}
1990
1991static void add_options_to_argv(struct strvec *argv,
1992 const struct fetch_config *config)
1993{
1994 if (dry_run)
1995 strvec_push(argv, "--dry-run");
1996 if (prune != -1)
1997 strvec_push(argv, prune ? "--prune" : "--no-prune");
1998 if (prune_tags != -1)
1999 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
2000 if (update_head_ok)
2001 strvec_push(argv, "--update-head-ok");
2002 if (force)
2003 strvec_push(argv, "--force");
2004 if (keep)
2005 strvec_push(argv, "--keep");
2006 if (config->recurse_submodules == RECURSE_SUBMODULES_ON)
2007 strvec_push(argv, "--recurse-submodules");
2008 else if (config->recurse_submodules == RECURSE_SUBMODULES_OFF)
2009 strvec_push(argv, "--no-recurse-submodules");
2010 else if (config->recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
2011 strvec_push(argv, "--recurse-submodules=on-demand");
2012 if (tags == TAGS_SET)
2013 strvec_push(argv, "--tags");
2014 else if (tags == TAGS_UNSET)
2015 strvec_push(argv, "--no-tags");
2016 if (verbosity >= 2)
2017 strvec_push(argv, "-v");
2018 if (verbosity >= 1)
2019 strvec_push(argv, "-v");
2020 else if (verbosity < 0)
2021 strvec_push(argv, "-q");
2022 if (family == TRANSPORT_FAMILY_IPV4)
2023 strvec_push(argv, "--ipv4");
2024 else if (family == TRANSPORT_FAMILY_IPV6)
2025 strvec_push(argv, "--ipv6");
2026 if (!write_fetch_head)
2027 strvec_push(argv, "--no-write-fetch-head");
2028 if (config->display_format == DISPLAY_FORMAT_PORCELAIN)
2029 strvec_pushf(argv, "--porcelain");
2030}
2031
2032/* Fetch multiple remotes in parallel */
2033
2034struct parallel_fetch_state {
2035 const char **argv;
2036 struct string_list *remotes;
2037 int next, result;
2038 const struct fetch_config *config;
2039};
2040
2041static int fetch_next_remote(struct child_process *cp,
2042 struct strbuf *out UNUSED,
2043 void *cb, void **task_cb)
2044{
2045 struct parallel_fetch_state *state = cb;
2046 char *remote;
2047
2048 if (state->next < 0 || state->next >= state->remotes->nr)
2049 return 0;
2050
2051 remote = state->remotes->items[state->next++].string;
2052 *task_cb = remote;
2053
2054 strvec_pushv(&cp->args, state->argv);
2055 strvec_push(&cp->args, remote);
2056 cp->git_cmd = 1;
2057
2058 if (verbosity >= 0 && state->config->display_format != DISPLAY_FORMAT_PORCELAIN)
2059 printf(_("Fetching %s\n"), remote);
2060
2061 return 1;
2062}
2063
2064static int fetch_failed_to_start(struct strbuf *out UNUSED,
2065 void *cb, void *task_cb)
2066{
2067 struct parallel_fetch_state *state = cb;
2068 const char *remote = task_cb;
2069
2070 state->result = error(_("could not fetch %s"), remote);
2071
2072 return 0;
2073}
2074
2075static int fetch_finished(int result, struct strbuf *out,
2076 void *cb, void *task_cb)
2077{
2078 struct parallel_fetch_state *state = cb;
2079 const char *remote = task_cb;
2080
2081 if (result) {
2082 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
2083 remote, result);
2084 state->result = -1;
2085 }
2086
2087 return 0;
2088}
2089
2090static int fetch_multiple(struct string_list *list, int max_children,
2091 const struct fetch_config *config)
2092{
2093 int i, result = 0;
2094 struct strvec argv = STRVEC_INIT;
2095
2096 if (!append && write_fetch_head) {
2097 int errcode = truncate_fetch_head();
2098 if (errcode)
2099 return errcode;
2100 }
2101
2102 /*
2103 * Cancel out the fetch.bundleURI config when running subprocesses,
2104 * to avoid fetching from the same bundle list multiple times.
2105 */
2106 strvec_pushl(&argv, "-c", "fetch.bundleURI=",
2107 "fetch", "--append", "--no-auto-gc",
2108 "--no-write-commit-graph", NULL);
2109 for (i = 0; i < server_options.nr; i++)
2110 strvec_pushf(&argv, "--server-option=%s", server_options.items[i].string);
2111 add_options_to_argv(&argv, config);
2112
2113 if (max_children != 1 && list->nr != 1) {
2114 struct parallel_fetch_state state = { argv.v, list, 0, 0, config };
2115 const struct run_process_parallel_opts opts = {
2116 .tr2_category = "fetch",
2117 .tr2_label = "parallel/fetch",
2118
2119 .processes = max_children,
2120
2121 .get_next_task = &fetch_next_remote,
2122 .start_failure = &fetch_failed_to_start,
2123 .task_finished = &fetch_finished,
2124 .data = &state,
2125 };
2126
2127 strvec_push(&argv, "--end-of-options");
2128
2129 run_processes_parallel(&opts);
2130 result = state.result;
2131 } else
2132 for (i = 0; i < list->nr; i++) {
2133 const char *name = list->items[i].string;
2134 struct child_process cmd = CHILD_PROCESS_INIT;
2135
2136 strvec_pushv(&cmd.args, argv.v);
2137 strvec_push(&cmd.args, name);
2138 if (verbosity >= 0 && config->display_format != DISPLAY_FORMAT_PORCELAIN)
2139 printf(_("Fetching %s\n"), name);
2140 cmd.git_cmd = 1;
2141 if (run_command(&cmd)) {
2142 error(_("could not fetch %s"), name);
2143 result = 1;
2144 }
2145 }
2146
2147 strvec_clear(&argv);
2148 return !!result;
2149}
2150
2151/*
2152 * Fetching from the promisor remote should use the given filter-spec
2153 * or inherit the default filter-spec from the config.
2154 */
2155static inline void fetch_one_setup_partial(struct remote *remote)
2156{
2157 /*
2158 * Explicit --no-filter argument overrides everything, regardless
2159 * of any prior partial clones and fetches.
2160 */
2161 if (filter_options.no_filter)
2162 return;
2163
2164 /*
2165 * If no prior partial clone/fetch and the current fetch DID NOT
2166 * request a partial-fetch, do a normal fetch.
2167 */
2168 if (!repo_has_promisor_remote(the_repository) && !filter_options.choice)
2169 return;
2170
2171 /*
2172 * If this is a partial-fetch request, we enable partial on
2173 * this repo if not already enabled and remember the given
2174 * filter-spec as the default for subsequent fetches to this
2175 * remote if there is currently no default filter-spec.
2176 */
2177 if (filter_options.choice) {
2178 partial_clone_register(remote->name, &filter_options);
2179 return;
2180 }
2181
2182 /*
2183 * Do a partial-fetch from the promisor remote using either the
2184 * explicitly given filter-spec or inherit the filter-spec from
2185 * the config.
2186 */
2187 if (!filter_options.choice)
2188 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2189 return;
2190}
2191
2192static int fetch_one(struct remote *remote, int argc, const char **argv,
2193 int prune_tags_ok, int use_stdin_refspecs,
2194 const struct fetch_config *config)
2195{
2196 struct refspec rs = REFSPEC_INIT_FETCH;
2197 int i;
2198 int exit_code;
2199 int maybe_prune_tags;
2200 int remote_via_config = remote_is_configured(remote, 0);
2201
2202 if (!remote)
2203 die(_("no remote repository specified; please specify either a URL or a\n"
2204 "remote name from which new revisions should be fetched"));
2205
2206 gtransport = prepare_transport(remote, 1);
2207
2208 if (prune < 0) {
2209 /* no command line request */
2210 if (0 <= remote->prune)
2211 prune = remote->prune;
2212 else if (0 <= config->prune)
2213 prune = config->prune;
2214 else
2215 prune = PRUNE_BY_DEFAULT;
2216 }
2217
2218 if (prune_tags < 0) {
2219 /* no command line request */
2220 if (0 <= remote->prune_tags)
2221 prune_tags = remote->prune_tags;
2222 else if (0 <= config->prune_tags)
2223 prune_tags = config->prune_tags;
2224 else
2225 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2226 }
2227
2228 maybe_prune_tags = prune_tags_ok && prune_tags;
2229 if (maybe_prune_tags && remote_via_config)
2230 refspec_append(&remote->fetch, TAG_REFSPEC);
2231
2232 if (maybe_prune_tags && (argc || !remote_via_config))
2233 refspec_append(&rs, TAG_REFSPEC);
2234
2235 for (i = 0; i < argc; i++) {
2236 if (!strcmp(argv[i], "tag")) {
2237 i++;
2238 if (i >= argc)
2239 die(_("you need to specify a tag name"));
2240
2241 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2242 argv[i], argv[i]);
2243 } else {
2244 refspec_append(&rs, argv[i]);
2245 }
2246 }
2247
2248 if (use_stdin_refspecs) {
2249 struct strbuf line = STRBUF_INIT;
2250 while (strbuf_getline_lf(&line, stdin) != EOF)
2251 refspec_append(&rs, line.buf);
2252 strbuf_release(&line);
2253 }
2254
2255 if (server_options.nr)
2256 gtransport->server_options = &server_options;
2257
2258 sigchain_push_common(unlock_pack_on_signal);
2259 atexit(unlock_pack_atexit);
2260 sigchain_push(SIGPIPE, SIG_IGN);
2261 exit_code = do_fetch(gtransport, &rs, config);
2262 sigchain_pop(SIGPIPE);
2263 refspec_clear(&rs);
2264 transport_disconnect(gtransport);
2265 gtransport = NULL;
2266 return exit_code;
2267}
2268
2269int cmd_fetch(int argc,
2270 const char **argv,
2271 const char *prefix,
2272 struct repository *repo UNUSED)
2273{
2274 struct fetch_config config = {
2275 .display_format = DISPLAY_FORMAT_FULL,
2276 .prune = -1,
2277 .prune_tags = -1,
2278 .show_forced_updates = 1,
2279 .recurse_submodules = RECURSE_SUBMODULES_DEFAULT,
2280 .parallel = 1,
2281 .submodule_fetch_jobs = -1,
2282 };
2283 const char *submodule_prefix = "";
2284 const char *bundle_uri;
2285 struct string_list list = STRING_LIST_INIT_DUP;
2286 struct remote *remote = NULL;
2287 int all = -1, multiple = 0;
2288 int result = 0;
2289 int prune_tags_ok = 1;
2290 int enable_auto_gc = 1;
2291 int unshallow = 0;
2292 int max_jobs = -1;
2293 int recurse_submodules_cli = RECURSE_SUBMODULES_DEFAULT;
2294 int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
2295 int fetch_write_commit_graph = -1;
2296 int stdin_refspecs = 0;
2297 int negotiate_only = 0;
2298 int porcelain = 0;
2299 int i;
2300
2301 struct option builtin_fetch_options[] = {
2302 OPT__VERBOSITY(&verbosity),
2303 OPT_BOOL(0, "all", &all,
2304 N_("fetch from all remotes")),
2305 OPT_BOOL(0, "set-upstream", &set_upstream,
2306 N_("set upstream for git pull/fetch")),
2307 OPT_BOOL('a', "append", &append,
2308 N_("append to .git/FETCH_HEAD instead of overwriting")),
2309 OPT_BOOL(0, "atomic", &atomic_fetch,
2310 N_("use atomic transaction to update references")),
2311 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
2312 N_("path to upload pack on remote end")),
2313 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
2314 OPT_BOOL('m', "multiple", &multiple,
2315 N_("fetch from multiple remotes")),
2316 OPT_SET_INT('t', "tags", &tags,
2317 N_("fetch all tags and associated objects"), TAGS_SET),
2318 OPT_SET_INT('n', NULL, &tags,
2319 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
2320 OPT_INTEGER('j', "jobs", &max_jobs,
2321 N_("number of submodules fetched in parallel")),
2322 OPT_BOOL(0, "prefetch", &prefetch,
2323 N_("modify the refspec to place all refs within refs/prefetch/")),
2324 OPT_BOOL('p', "prune", &prune,
2325 N_("prune remote-tracking branches no longer on remote")),
2326 OPT_BOOL('P', "prune-tags", &prune_tags,
2327 N_("prune local tags no longer on remote and clobber changed tags")),
2328 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules_cli, N_("on-demand"),
2329 N_("control recursive fetching of submodules"),
2330 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
2331 OPT_BOOL(0, "dry-run", &dry_run,
2332 N_("dry run")),
2333 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
2334 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
2335 N_("write fetched references to the FETCH_HEAD file")),
2336 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
2337 OPT_BOOL('u', "update-head-ok", &update_head_ok,
2338 N_("allow updating of HEAD ref")),
2339 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
2340 OPT_STRING(0, "depth", &depth, N_("depth"),
2341 N_("deepen history of shallow clone")),
2342 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
2343 N_("deepen history of shallow repository based on time")),
2344 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("ref"),
2345 N_("deepen history of shallow clone, excluding ref")),
2346 OPT_INTEGER(0, "deepen", &deepen_relative,
2347 N_("deepen history of shallow clone")),
2348 OPT_SET_INT_F(0, "unshallow", &unshallow,
2349 N_("convert to a complete repository"),
2350 1, PARSE_OPT_NONEG),
2351 OPT_SET_INT_F(0, "refetch", &refetch,
2352 N_("re-fetch without negotiating common commits"),
2353 1, PARSE_OPT_NONEG),
2354 {
2355 .type = OPTION_STRING,
2356 .long_name = "submodule-prefix",
2357 .value = &submodule_prefix,
2358 .argh = N_("dir"),
2359 .help = N_("prepend this to submodule path output"),
2360 .flags = PARSE_OPT_HIDDEN,
2361 },
2362 OPT_CALLBACK_F(0, "recurse-submodules-default",
2363 &recurse_submodules_default, N_("on-demand"),
2364 N_("default for recursive fetching of submodules "
2365 "(lower priority than config files)"),
2366 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
2367 OPT_BOOL(0, "update-shallow", &update_shallow,
2368 N_("accept refs that update .git/shallow")),
2369 OPT_CALLBACK_F(0, "refmap", &refmap, N_("refmap"),
2370 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
2371 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
2372 OPT_IPVERSION(&family),
2373 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
2374 N_("report that we have only objects reachable from this object")),
2375 OPT_BOOL(0, "negotiate-only", &negotiate_only,
2376 N_("do not fetch a packfile; instead, print ancestors of negotiation tips")),
2377 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
2378 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
2379 N_("run 'maintenance --auto' after fetching")),
2380 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
2381 N_("run 'maintenance --auto' after fetching")),
2382 OPT_BOOL(0, "show-forced-updates", &config.show_forced_updates,
2383 N_("check for forced-updates on all updated branches")),
2384 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
2385 N_("write the commit-graph after fetching")),
2386 OPT_BOOL(0, "stdin", &stdin_refspecs,
2387 N_("accept refspecs from stdin")),
2388 OPT_END()
2389 };
2390
2391 packet_trace_identity("fetch");
2392
2393 /* Record the command line for the reflog */
2394 strbuf_addstr(&default_rla, "fetch");
2395 for (i = 1; i < argc; i++) {
2396 /* This handles non-URLs gracefully */
2397 char *anon = transport_anonymize_url(argv[i]);
2398
2399 strbuf_addf(&default_rla, " %s", anon);
2400 free(anon);
2401 }
2402
2403 git_config(git_fetch_config, &config);
2404 if (the_repository->gitdir) {
2405 prepare_repo_settings(the_repository);
2406 the_repository->settings.command_requires_full_index = 0;
2407 }
2408
2409 argc = parse_options(argc, argv, prefix,
2410 builtin_fetch_options, builtin_fetch_usage, 0);
2411
2412 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2413 config.recurse_submodules = recurse_submodules_cli;
2414
2415 if (negotiate_only) {
2416 switch (recurse_submodules_cli) {
2417 case RECURSE_SUBMODULES_OFF:
2418 case RECURSE_SUBMODULES_DEFAULT:
2419 /*
2420 * --negotiate-only should never recurse into
2421 * submodules. Skip it by setting recurse_submodules to
2422 * RECURSE_SUBMODULES_OFF.
2423 */
2424 config.recurse_submodules = RECURSE_SUBMODULES_OFF;
2425 break;
2426
2427 default:
2428 die(_("options '%s' and '%s' cannot be used together"),
2429 "--negotiate-only", "--recurse-submodules");
2430 }
2431 }
2432
2433 if (config.recurse_submodules != RECURSE_SUBMODULES_OFF) {
2434 int *sfjc = config.submodule_fetch_jobs == -1
2435 ? &config.submodule_fetch_jobs : NULL;
2436 int *rs = config.recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2437 ? &config.recurse_submodules : NULL;
2438
2439 fetch_config_from_gitmodules(sfjc, rs);
2440 }
2441
2442
2443 if (porcelain) {
2444 switch (recurse_submodules_cli) {
2445 case RECURSE_SUBMODULES_OFF:
2446 case RECURSE_SUBMODULES_DEFAULT:
2447 /*
2448 * Reference updates in submodules would be ambiguous
2449 * in porcelain mode, so we reject this combination.
2450 */
2451 config.recurse_submodules = RECURSE_SUBMODULES_OFF;
2452 break;
2453
2454 default:
2455 die(_("options '%s' and '%s' cannot be used together"),
2456 "--porcelain", "--recurse-submodules");
2457 }
2458
2459 config.display_format = DISPLAY_FORMAT_PORCELAIN;
2460 }
2461
2462 if (negotiate_only && !negotiation_tip.nr)
2463 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2464
2465 if (deepen_relative) {
2466 if (deepen_relative < 0)
2467 die(_("negative depth in --deepen is not supported"));
2468 if (depth)
2469 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2470 depth = xstrfmt("%d", deepen_relative);
2471 }
2472 if (unshallow) {
2473 if (depth)
2474 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2475 else if (!is_repository_shallow(the_repository))
2476 die(_("--unshallow on a complete repository does not make sense"));
2477 else
2478 depth = xstrfmt("%d", INFINITE_DEPTH);
2479 }
2480
2481 /* no need to be strict, transport_set_option() will validate it again */
2482 if (depth && atoi(depth) < 1)
2483 die(_("depth %s is not a positive number"), depth);
2484 if (depth || deepen_since || deepen_not.nr)
2485 deepen = 1;
2486
2487 /* FETCH_HEAD never gets updated in --dry-run mode */
2488 if (dry_run)
2489 write_fetch_head = 0;
2490
2491 if (!max_jobs)
2492 max_jobs = online_cpus();
2493
2494 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2495 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2496 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2497
2498 if (all < 0) {
2499 /*
2500 * no --[no-]all given;
2501 * only use config option if no remote was explicitly specified
2502 */
2503 all = (!argc) ? config.all : 0;
2504 }
2505
2506 if (all) {
2507 if (argc == 1)
2508 die(_("fetch --all does not take a repository argument"));
2509 else if (argc > 1)
2510 die(_("fetch --all does not make sense with refspecs"));
2511
2512 (void) for_each_remote(get_one_remote_for_fetch, &list);
2513
2514 /* do not do fetch_multiple() of one */
2515 if (list.nr == 1)
2516 remote = remote_get(list.items[0].string);
2517 } else if (argc == 0) {
2518 /* No arguments -- use default remote */
2519 remote = remote_get(NULL);
2520 } else if (multiple) {
2521 /* All arguments are assumed to be remotes or groups */
2522 for (i = 0; i < argc; i++)
2523 if (!add_remote_or_group(argv[i], &list))
2524 die(_("no such remote or remote group: %s"),
2525 argv[i]);
2526 } else {
2527 /* Single remote or group */
2528 (void) add_remote_or_group(argv[0], &list);
2529 if (list.nr > 1) {
2530 /* More than one remote */
2531 if (argc > 1)
2532 die(_("fetching a group and specifying refspecs does not make sense"));
2533 } else {
2534 /* Zero or one remotes */
2535 remote = remote_get(argv[0]);
2536 prune_tags_ok = (argc == 1);
2537 argc--;
2538 argv++;
2539 }
2540 }
2541 string_list_remove_duplicates(&list, 0);
2542
2543 if (negotiate_only) {
2544 struct oidset acked_commits = OIDSET_INIT;
2545 struct oidset_iter iter;
2546 const struct object_id *oid;
2547
2548 trace2_region_enter("fetch", "negotiate-only", the_repository);
2549 if (!remote)
2550 die(_("must supply remote when using --negotiate-only"));
2551 gtransport = prepare_transport(remote, 1);
2552 if (gtransport->smart_options) {
2553 gtransport->smart_options->acked_commits = &acked_commits;
2554 } else {
2555 warning(_("protocol does not support --negotiate-only, exiting"));
2556 result = 1;
2557 trace2_region_leave("fetch", "negotiate-only", the_repository);
2558 goto cleanup;
2559 }
2560 if (server_options.nr)
2561 gtransport->server_options = &server_options;
2562 result = transport_fetch_refs(gtransport, NULL);
2563 gtransport->smart_options->acked_commits = NULL;
2564
2565 oidset_iter_init(&acked_commits, &iter);
2566 while ((oid = oidset_iter_next(&iter)))
2567 printf("%s\n", oid_to_hex(oid));
2568 oidset_clear(&acked_commits);
2569 trace2_region_leave("fetch", "negotiate-only", the_repository);
2570 } else if (remote) {
2571 if (filter_options.choice || repo_has_promisor_remote(the_repository)) {
2572 trace2_region_enter("fetch", "setup-partial", the_repository);
2573 fetch_one_setup_partial(remote);
2574 trace2_region_leave("fetch", "setup-partial", the_repository);
2575 }
2576 trace2_region_enter("fetch", "fetch-one", the_repository);
2577 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs,
2578 &config);
2579 trace2_region_leave("fetch", "fetch-one", the_repository);
2580 } else {
2581 int max_children = max_jobs;
2582
2583 if (filter_options.choice)
2584 die(_("--filter can only be used with the remote "
2585 "configured in extensions.partialclone"));
2586
2587 if (atomic_fetch)
2588 die(_("--atomic can only be used when fetching "
2589 "from one remote"));
2590
2591 if (stdin_refspecs)
2592 die(_("--stdin can only be used when fetching "
2593 "from one remote"));
2594
2595 if (max_children < 0)
2596 max_children = config.parallel;
2597
2598 /* TODO should this also die if we have a previous partial-clone? */
2599 trace2_region_enter("fetch", "fetch-multiple", the_repository);
2600 result = fetch_multiple(&list, max_children, &config);
2601 trace2_region_leave("fetch", "fetch-multiple", the_repository);
2602 }
2603
2604 /*
2605 * This is only needed after fetch_one(), which does not fetch
2606 * submodules by itself.
2607 *
2608 * When we fetch from multiple remotes, fetch_multiple() has
2609 * already updated submodules to grab commits necessary for
2610 * the fetched history from each remote, so there is no need
2611 * to fetch submodules from here.
2612 */
2613 if (!result && remote && (config.recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2614 struct strvec options = STRVEC_INIT;
2615 int max_children = max_jobs;
2616
2617 if (max_children < 0)
2618 max_children = config.submodule_fetch_jobs;
2619 if (max_children < 0)
2620 max_children = config.parallel;
2621
2622 add_options_to_argv(&options, &config);
2623 trace2_region_enter_printf("fetch", "recurse-submodule", the_repository, "%s", submodule_prefix);
2624 result = fetch_submodules(the_repository,
2625 &options,
2626 submodule_prefix,
2627 config.recurse_submodules,
2628 recurse_submodules_default,
2629 verbosity < 0,
2630 max_children);
2631 trace2_region_leave_printf("fetch", "recurse-submodule", the_repository, "%s", submodule_prefix);
2632 strvec_clear(&options);
2633 }
2634
2635 /*
2636 * Skip irrelevant tasks because we know objects were not
2637 * fetched.
2638 *
2639 * NEEDSWORK: as a future optimization, we can return early
2640 * whenever objects were not fetched e.g. if we already have all
2641 * of them.
2642 */
2643 if (negotiate_only)
2644 goto cleanup;
2645
2646 prepare_repo_settings(the_repository);
2647 if (fetch_write_commit_graph > 0 ||
2648 (fetch_write_commit_graph < 0 &&
2649 the_repository->settings.fetch_write_commit_graph)) {
2650 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2651
2652 if (progress)
2653 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2654
2655 trace2_region_enter("fetch", "write-commit-graph", the_repository);
2656 write_commit_graph_reachable(the_repository->objects->odb,
2657 commit_graph_flags,
2658 NULL);
2659 trace2_region_leave("fetch", "write-commit-graph", the_repository);
2660 }
2661
2662 if (enable_auto_gc) {
2663 if (refetch) {
2664 /*
2665 * Hint auto-maintenance strongly to encourage repacking,
2666 * but respect config settings disabling it.
2667 */
2668 int opt_val;
2669 if (git_config_get_int("gc.autopacklimit", &opt_val))
2670 opt_val = -1;
2671 if (opt_val != 0)
2672 git_config_push_parameter("gc.autoPackLimit=1");
2673
2674 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2675 opt_val = -1;
2676 if (opt_val != 0)
2677 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2678 }
2679 run_auto_maintenance(verbosity < 0);
2680 }
2681
2682 cleanup:
2683 string_list_clear(&list, 0);
2684 return result;
2685}