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