]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/fetch.c
cocci: apply the "object-store.h" part of "the_repository.pending"
[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 !repo_has_object_file_with_flags(the_repository, &ref->old_oid, quick_flags) &&
411 !oidset_contains(&fetch_oids, &ref->old_oid) &&
412 !repo_has_object_file_with_flags(the_repository, &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 !repo_has_object_file_with_flags(the_repository, &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 !repo_has_object_file_with_flags(the_repository, &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 = repo_in_merge_bases(the_repository, current,
969 updated);
970 forced_updates_ms += (getnanotime() - t_before) / 1000000;
971 } else {
972 fast_forward = 1;
973 }
974
975 if (fast_forward) {
976 struct strbuf quickref = STRBUF_INIT;
977 int r;
978
979 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
980 strbuf_addstr(&quickref, "..");
981 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
982 r = s_update_ref("fast-forward", ref, transaction, 1);
983 format_display(display, r ? '!' : ' ', quickref.buf,
984 r ? _("unable to update local ref") : NULL,
985 remote, pretty_ref, summary_width);
986 strbuf_release(&quickref);
987 return r;
988 } else if (force || ref->force) {
989 struct strbuf quickref = STRBUF_INIT;
990 int r;
991 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
992 strbuf_addstr(&quickref, "...");
993 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
994 r = s_update_ref("forced-update", ref, transaction, 1);
995 format_display(display, r ? '!' : '+', quickref.buf,
996 r ? _("unable to update local ref") : _("forced update"),
997 remote, pretty_ref, summary_width);
998 strbuf_release(&quickref);
999 return r;
1000 } else {
1001 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
1002 remote, pretty_ref, summary_width);
1003 return 1;
1004 }
1005 }
1006
1007 static const struct object_id *iterate_ref_map(void *cb_data)
1008 {
1009 struct ref **rm = cb_data;
1010 struct ref *ref = *rm;
1011
1012 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
1013 ref = ref->next;
1014 if (!ref)
1015 return NULL;
1016 *rm = ref->next;
1017 return &ref->old_oid;
1018 }
1019
1020 struct fetch_head {
1021 FILE *fp;
1022 struct strbuf buf;
1023 };
1024
1025 static int open_fetch_head(struct fetch_head *fetch_head)
1026 {
1027 const char *filename = git_path_fetch_head(the_repository);
1028
1029 if (write_fetch_head) {
1030 fetch_head->fp = fopen(filename, "a");
1031 if (!fetch_head->fp)
1032 return error_errno(_("cannot open '%s'"), filename);
1033 strbuf_init(&fetch_head->buf, 0);
1034 } else {
1035 fetch_head->fp = NULL;
1036 }
1037
1038 return 0;
1039 }
1040
1041 static void append_fetch_head(struct fetch_head *fetch_head,
1042 const struct object_id *old_oid,
1043 enum fetch_head_status fetch_head_status,
1044 const char *note,
1045 const char *url, size_t url_len)
1046 {
1047 char old_oid_hex[GIT_MAX_HEXSZ + 1];
1048 const char *merge_status_marker;
1049 size_t i;
1050
1051 if (!fetch_head->fp)
1052 return;
1053
1054 switch (fetch_head_status) {
1055 case FETCH_HEAD_NOT_FOR_MERGE:
1056 merge_status_marker = "not-for-merge";
1057 break;
1058 case FETCH_HEAD_MERGE:
1059 merge_status_marker = "";
1060 break;
1061 default:
1062 /* do not write anything to FETCH_HEAD */
1063 return;
1064 }
1065
1066 strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
1067 oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
1068 for (i = 0; i < url_len; ++i)
1069 if ('\n' == url[i])
1070 strbuf_addstr(&fetch_head->buf, "\\n");
1071 else
1072 strbuf_addch(&fetch_head->buf, url[i]);
1073 strbuf_addch(&fetch_head->buf, '\n');
1074
1075 /*
1076 * When using an atomic fetch, we do not want to update FETCH_HEAD if
1077 * any of the reference updates fails. We thus have to write all
1078 * updates to a buffer first and only commit it as soon as all
1079 * references have been successfully updated.
1080 */
1081 if (!atomic_fetch) {
1082 strbuf_write(&fetch_head->buf, fetch_head->fp);
1083 strbuf_reset(&fetch_head->buf);
1084 }
1085 }
1086
1087 static void commit_fetch_head(struct fetch_head *fetch_head)
1088 {
1089 if (!fetch_head->fp || !atomic_fetch)
1090 return;
1091 strbuf_write(&fetch_head->buf, fetch_head->fp);
1092 }
1093
1094 static void close_fetch_head(struct fetch_head *fetch_head)
1095 {
1096 if (!fetch_head->fp)
1097 return;
1098
1099 fclose(fetch_head->fp);
1100 strbuf_release(&fetch_head->buf);
1101 }
1102
1103 static const char warn_show_forced_updates[] =
1104 N_("fetch normally indicates which branches had a forced update,\n"
1105 "but that check has been disabled; to re-enable, use '--show-forced-updates'\n"
1106 "flag or run 'git config fetch.showForcedUpdates true'");
1107 static const char warn_time_show_forced_updates[] =
1108 N_("it took %.2f seconds to check forced updates; you can use\n"
1109 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
1110 "to avoid this check\n");
1111
1112 static int store_updated_refs(const char *raw_url, const char *remote_name,
1113 int connectivity_checked,
1114 struct ref_transaction *transaction, struct ref *ref_map,
1115 struct fetch_head *fetch_head)
1116 {
1117 int url_len, i, rc = 0;
1118 struct strbuf note = STRBUF_INIT;
1119 const char *what, *kind;
1120 struct ref *rm;
1121 char *url;
1122 int want_status;
1123 int summary_width = 0;
1124
1125 if (verbosity >= 0)
1126 summary_width = transport_summary_width(ref_map);
1127
1128 if (raw_url)
1129 url = transport_anonymize_url(raw_url);
1130 else
1131 url = xstrdup("foreign");
1132
1133 if (!connectivity_checked) {
1134 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1135
1136 rm = ref_map;
1137 if (check_connected(iterate_ref_map, &rm, &opt)) {
1138 rc = error(_("%s did not send all necessary objects\n"), url);
1139 goto abort;
1140 }
1141 }
1142
1143 prepare_format_display(ref_map);
1144
1145 /*
1146 * We do a pass for each fetch_head_status type in their enum order, so
1147 * merged entries are written before not-for-merge. That lets readers
1148 * use FETCH_HEAD as a refname to refer to the ref to be merged.
1149 */
1150 for (want_status = FETCH_HEAD_MERGE;
1151 want_status <= FETCH_HEAD_IGNORE;
1152 want_status++) {
1153 for (rm = ref_map; rm; rm = rm->next) {
1154 struct ref *ref = NULL;
1155
1156 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
1157 if (want_status == FETCH_HEAD_MERGE)
1158 warning(_("rejected %s because shallow roots are not allowed to be updated"),
1159 rm->peer_ref ? rm->peer_ref->name : rm->name);
1160 continue;
1161 }
1162
1163 /*
1164 * When writing FETCH_HEAD we need to determine whether
1165 * we already have the commit or not. If not, then the
1166 * reference is not for merge and needs to be written
1167 * to the reflog after other commits which we already
1168 * have. We're not interested in this property though
1169 * in case FETCH_HEAD is not to be updated, so we can
1170 * skip the classification in that case.
1171 */
1172 if (fetch_head->fp) {
1173 struct commit *commit = NULL;
1174
1175 /*
1176 * References in "refs/tags/" are often going to point
1177 * to annotated tags, which are not part of the
1178 * commit-graph. We thus only try to look up refs in
1179 * the graph which are not in that namespace to not
1180 * regress performance in repositories with many
1181 * annotated tags.
1182 */
1183 if (!starts_with(rm->name, "refs/tags/"))
1184 commit = lookup_commit_in_graph(the_repository, &rm->old_oid);
1185 if (!commit) {
1186 commit = lookup_commit_reference_gently(the_repository,
1187 &rm->old_oid,
1188 1);
1189 if (!commit)
1190 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
1191 }
1192 }
1193
1194 if (rm->fetch_head_status != want_status)
1195 continue;
1196
1197 if (rm->peer_ref) {
1198 ref = alloc_ref(rm->peer_ref->name);
1199 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
1200 oidcpy(&ref->new_oid, &rm->old_oid);
1201 ref->force = rm->peer_ref->force;
1202 }
1203
1204 if (recurse_submodules != RECURSE_SUBMODULES_OFF &&
1205 (!rm->peer_ref || !oideq(&ref->old_oid, &ref->new_oid))) {
1206 check_for_new_submodule_commits(&rm->old_oid);
1207 }
1208
1209 if (!strcmp(rm->name, "HEAD")) {
1210 kind = "";
1211 what = "";
1212 }
1213 else if (skip_prefix(rm->name, "refs/heads/", &what))
1214 kind = "branch";
1215 else if (skip_prefix(rm->name, "refs/tags/", &what))
1216 kind = "tag";
1217 else if (skip_prefix(rm->name, "refs/remotes/", &what))
1218 kind = "remote-tracking branch";
1219 else {
1220 kind = "";
1221 what = rm->name;
1222 }
1223
1224 url_len = strlen(url);
1225 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1226 ;
1227 url_len = i + 1;
1228 if (4 < i && !strncmp(".git", url + i - 3, 4))
1229 url_len = i - 3;
1230
1231 strbuf_reset(&note);
1232 if (*what) {
1233 if (*kind)
1234 strbuf_addf(&note, "%s ", kind);
1235 strbuf_addf(&note, "'%s' of ", what);
1236 }
1237
1238 append_fetch_head(fetch_head, &rm->old_oid,
1239 rm->fetch_head_status,
1240 note.buf, url, url_len);
1241
1242 strbuf_reset(&note);
1243 if (ref) {
1244 rc |= update_local_ref(ref, transaction, what,
1245 rm, &note, summary_width);
1246 free(ref);
1247 } else if (write_fetch_head || dry_run) {
1248 /*
1249 * Display fetches written to FETCH_HEAD (or
1250 * would be written to FETCH_HEAD, if --dry-run
1251 * is set).
1252 */
1253 format_display(&note, '*',
1254 *kind ? kind : "branch", NULL,
1255 *what ? what : "HEAD",
1256 "FETCH_HEAD", summary_width);
1257 }
1258 if (note.len) {
1259 if (!shown_url) {
1260 fprintf(stderr, _("From %.*s\n"),
1261 url_len, url);
1262 shown_url = 1;
1263 }
1264 fprintf(stderr, " %s\n", note.buf);
1265 }
1266 }
1267 }
1268
1269 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1270 error(_("some local refs could not be updated; try running\n"
1271 " 'git remote prune %s' to remove any old, conflicting "
1272 "branches"), remote_name);
1273
1274 if (advice_enabled(ADVICE_FETCH_SHOW_FORCED_UPDATES)) {
1275 if (!fetch_show_forced_updates) {
1276 warning(_(warn_show_forced_updates));
1277 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1278 warning(_(warn_time_show_forced_updates),
1279 forced_updates_ms / 1000.0);
1280 }
1281 }
1282
1283 abort:
1284 strbuf_release(&note);
1285 free(url);
1286 return rc;
1287 }
1288
1289 /*
1290 * We would want to bypass the object transfer altogether if
1291 * everything we are going to fetch already exists and is connected
1292 * locally.
1293 */
1294 static int check_exist_and_connected(struct ref *ref_map)
1295 {
1296 struct ref *rm = ref_map;
1297 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1298 struct ref *r;
1299
1300 /*
1301 * If we are deepening a shallow clone we already have these
1302 * objects reachable. Running rev-list here will return with
1303 * a good (0) exit status and we'll bypass the fetch that we
1304 * really need to perform. Claiming failure now will ensure
1305 * we perform the network exchange to deepen our history.
1306 */
1307 if (deepen)
1308 return -1;
1309
1310 /*
1311 * Similarly, if we need to refetch, we always want to perform a full
1312 * fetch ignoring existing objects.
1313 */
1314 if (refetch)
1315 return -1;
1316
1317
1318 /*
1319 * check_connected() allows objects to merely be promised, but
1320 * we need all direct targets to exist.
1321 */
1322 for (r = rm; r; r = r->next) {
1323 if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
1324 OBJECT_INFO_SKIP_FETCH_OBJECT))
1325 return -1;
1326 }
1327
1328 opt.quiet = 1;
1329 return check_connected(iterate_ref_map, &rm, &opt);
1330 }
1331
1332 static int fetch_and_consume_refs(struct transport *transport,
1333 struct ref_transaction *transaction,
1334 struct ref *ref_map,
1335 struct fetch_head *fetch_head)
1336 {
1337 int connectivity_checked = 1;
1338 int ret;
1339
1340 /*
1341 * We don't need to perform a fetch in case we can already satisfy all
1342 * refs.
1343 */
1344 ret = check_exist_and_connected(ref_map);
1345 if (ret) {
1346 trace2_region_enter("fetch", "fetch_refs", the_repository);
1347 ret = transport_fetch_refs(transport, ref_map);
1348 trace2_region_leave("fetch", "fetch_refs", the_repository);
1349 if (ret)
1350 goto out;
1351 connectivity_checked = transport->smart_options ?
1352 transport->smart_options->connectivity_checked : 0;
1353 }
1354
1355 trace2_region_enter("fetch", "consume_refs", the_repository);
1356 ret = store_updated_refs(transport->url, transport->remote->name,
1357 connectivity_checked, transaction, ref_map,
1358 fetch_head);
1359 trace2_region_leave("fetch", "consume_refs", the_repository);
1360
1361 out:
1362 transport_unlock_pack(transport, 0);
1363 return ret;
1364 }
1365
1366 static int prune_refs(struct refspec *rs,
1367 struct ref_transaction *transaction,
1368 struct ref *ref_map,
1369 const char *raw_url)
1370 {
1371 int url_len, i, result = 0;
1372 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1373 struct strbuf err = STRBUF_INIT;
1374 char *url;
1375 const char *dangling_msg = dry_run
1376 ? _(" (%s will become dangling)")
1377 : _(" (%s has become dangling)");
1378
1379 if (raw_url)
1380 url = transport_anonymize_url(raw_url);
1381 else
1382 url = xstrdup("foreign");
1383
1384 url_len = strlen(url);
1385 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1386 ;
1387
1388 url_len = i + 1;
1389 if (4 < i && !strncmp(".git", url + i - 3, 4))
1390 url_len = i - 3;
1391
1392 if (!dry_run) {
1393 if (transaction) {
1394 for (ref = stale_refs; ref; ref = ref->next) {
1395 result = ref_transaction_delete(transaction, ref->name, NULL, 0,
1396 "fetch: prune", &err);
1397 if (result)
1398 goto cleanup;
1399 }
1400 } else {
1401 struct string_list refnames = STRING_LIST_INIT_NODUP;
1402
1403 for (ref = stale_refs; ref; ref = ref->next)
1404 string_list_append(&refnames, ref->name);
1405
1406 result = delete_refs("fetch: prune", &refnames, 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 struct strbuf sb = STRBUF_INIT;
1416 if (!shown_url) {
1417 fprintf(stderr, _("From %.*s\n"), url_len, url);
1418 shown_url = 1;
1419 }
1420 format_display(&sb, '-', _("[deleted]"), NULL,
1421 _("(none)"), prettify_refname(ref->name),
1422 summary_width);
1423 fprintf(stderr, " %s\n",sb.buf);
1424 strbuf_release(&sb);
1425 warn_dangling_symref(stderr, dangling_msg, ref->name);
1426 }
1427 }
1428
1429 cleanup:
1430 strbuf_release(&err);
1431 free(url);
1432 free_refs(stale_refs);
1433 return result;
1434 }
1435
1436 static void check_not_current_branch(struct ref *ref_map)
1437 {
1438 const char *path;
1439 for (; ref_map; ref_map = ref_map->next)
1440 if (ref_map->peer_ref &&
1441 starts_with(ref_map->peer_ref->name, "refs/heads/") &&
1442 (path = branch_checked_out(ref_map->peer_ref->name)))
1443 die(_("refusing to fetch into branch '%s' "
1444 "checked out at '%s'"),
1445 ref_map->peer_ref->name, path);
1446 }
1447
1448 static int truncate_fetch_head(void)
1449 {
1450 const char *filename = git_path_fetch_head(the_repository);
1451 FILE *fp = fopen_for_writing(filename);
1452
1453 if (!fp)
1454 return error_errno(_("cannot open '%s'"), filename);
1455 fclose(fp);
1456 return 0;
1457 }
1458
1459 static void set_option(struct transport *transport, const char *name, const char *value)
1460 {
1461 int r = transport_set_option(transport, name, value);
1462 if (r < 0)
1463 die(_("option \"%s\" value \"%s\" is not valid for %s"),
1464 name, value, transport->url);
1465 if (r > 0)
1466 warning(_("option \"%s\" is ignored for %s\n"),
1467 name, transport->url);
1468 }
1469
1470
1471 static int add_oid(const char *refname UNUSED,
1472 const struct object_id *oid,
1473 int flags UNUSED, void *cb_data)
1474 {
1475 struct oid_array *oids = cb_data;
1476
1477 oid_array_append(oids, oid);
1478 return 0;
1479 }
1480
1481 static void add_negotiation_tips(struct git_transport_options *smart_options)
1482 {
1483 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1484 int i;
1485
1486 for (i = 0; i < negotiation_tip.nr; i++) {
1487 const char *s = negotiation_tip.items[i].string;
1488 int old_nr;
1489 if (!has_glob_specials(s)) {
1490 struct object_id oid;
1491 if (repo_get_oid(the_repository, s, &oid))
1492 die(_("%s is not a valid object"), s);
1493 if (!has_object(the_repository, &oid, 0))
1494 die(_("the object %s does not exist"), s);
1495 oid_array_append(oids, &oid);
1496 continue;
1497 }
1498 old_nr = oids->nr;
1499 for_each_glob_ref(add_oid, s, oids);
1500 if (old_nr == oids->nr)
1501 warning("ignoring --negotiation-tip=%s because it does not match any refs",
1502 s);
1503 }
1504 smart_options->negotiation_tips = oids;
1505 }
1506
1507 static struct transport *prepare_transport(struct remote *remote, int deepen)
1508 {
1509 struct transport *transport;
1510
1511 transport = transport_get(remote, NULL);
1512 transport_set_verbosity(transport, verbosity, progress);
1513 transport->family = family;
1514 if (upload_pack)
1515 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1516 if (keep)
1517 set_option(transport, TRANS_OPT_KEEP, "yes");
1518 if (depth)
1519 set_option(transport, TRANS_OPT_DEPTH, depth);
1520 if (deepen && deepen_since)
1521 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1522 if (deepen && deepen_not.nr)
1523 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1524 (const char *)&deepen_not);
1525 if (deepen_relative)
1526 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1527 if (update_shallow)
1528 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1529 if (refetch)
1530 set_option(transport, TRANS_OPT_REFETCH, "yes");
1531 if (filter_options.choice) {
1532 const char *spec =
1533 expand_list_objects_filter_spec(&filter_options);
1534 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1535 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1536 }
1537 if (negotiation_tip.nr) {
1538 if (transport->smart_options)
1539 add_negotiation_tips(transport->smart_options);
1540 else
1541 warning("ignoring --negotiation-tip because the protocol does not support it");
1542 }
1543 return transport;
1544 }
1545
1546 static int backfill_tags(struct transport *transport,
1547 struct ref_transaction *transaction,
1548 struct ref *ref_map,
1549 struct fetch_head *fetch_head)
1550 {
1551 int retcode, cannot_reuse;
1552
1553 /*
1554 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1555 * when remote helper is used (setting it to an empty string
1556 * is not unsetting). We could extend the remote helper
1557 * protocol for that, but for now, just force a new connection
1558 * without deepen-since. Similar story for deepen-not.
1559 */
1560 cannot_reuse = transport->cannot_reuse ||
1561 deepen_since || deepen_not.nr;
1562 if (cannot_reuse) {
1563 gsecondary = prepare_transport(transport->remote, 0);
1564 transport = gsecondary;
1565 }
1566
1567 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1568 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1569 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1570 retcode = fetch_and_consume_refs(transport, transaction, ref_map, fetch_head);
1571
1572 if (gsecondary) {
1573 transport_disconnect(gsecondary);
1574 gsecondary = NULL;
1575 }
1576
1577 return retcode;
1578 }
1579
1580 static int do_fetch(struct transport *transport,
1581 struct refspec *rs)
1582 {
1583 struct ref_transaction *transaction = NULL;
1584 struct ref *ref_map = NULL;
1585 int autotags = (transport->remote->fetch_tags == 1);
1586 int retcode = 0;
1587 const struct ref *remote_refs;
1588 struct transport_ls_refs_options transport_ls_refs_options =
1589 TRANSPORT_LS_REFS_OPTIONS_INIT;
1590 int must_list_refs = 1;
1591 struct fetch_head fetch_head = { 0 };
1592 struct strbuf err = STRBUF_INIT;
1593
1594 if (tags == TAGS_DEFAULT) {
1595 if (transport->remote->fetch_tags == 2)
1596 tags = TAGS_SET;
1597 if (transport->remote->fetch_tags == -1)
1598 tags = TAGS_UNSET;
1599 }
1600
1601 /* if not appending, truncate FETCH_HEAD */
1602 if (!append && write_fetch_head) {
1603 retcode = truncate_fetch_head();
1604 if (retcode)
1605 goto cleanup;
1606 }
1607
1608 if (rs->nr) {
1609 int i;
1610
1611 refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
1612
1613 /*
1614 * We can avoid listing refs if all of them are exact
1615 * OIDs
1616 */
1617 must_list_refs = 0;
1618 for (i = 0; i < rs->nr; i++) {
1619 if (!rs->items[i].exact_sha1) {
1620 must_list_refs = 1;
1621 break;
1622 }
1623 }
1624 } else {
1625 struct branch *branch = branch_get(NULL);
1626
1627 if (transport->remote->fetch.nr)
1628 refspec_ref_prefixes(&transport->remote->fetch,
1629 &transport_ls_refs_options.ref_prefixes);
1630 if (branch_has_merge_config(branch) &&
1631 !strcmp(branch->remote_name, transport->remote->name)) {
1632 int i;
1633 for (i = 0; i < branch->merge_nr; i++) {
1634 strvec_push(&transport_ls_refs_options.ref_prefixes,
1635 branch->merge[i]->src);
1636 }
1637 }
1638 }
1639
1640 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1641 must_list_refs = 1;
1642 if (transport_ls_refs_options.ref_prefixes.nr)
1643 strvec_push(&transport_ls_refs_options.ref_prefixes,
1644 "refs/tags/");
1645 }
1646
1647 if (must_list_refs) {
1648 trace2_region_enter("fetch", "remote_refs", the_repository);
1649 remote_refs = transport_get_remote_refs(transport,
1650 &transport_ls_refs_options);
1651 trace2_region_leave("fetch", "remote_refs", the_repository);
1652 } else
1653 remote_refs = NULL;
1654
1655 transport_ls_refs_options_release(&transport_ls_refs_options);
1656
1657 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1658 tags, &autotags);
1659 if (!update_head_ok)
1660 check_not_current_branch(ref_map);
1661
1662 retcode = open_fetch_head(&fetch_head);
1663 if (retcode)
1664 goto cleanup;
1665
1666 if (atomic_fetch) {
1667 transaction = ref_transaction_begin(&err);
1668 if (!transaction) {
1669 retcode = error("%s", err.buf);
1670 goto cleanup;
1671 }
1672 }
1673
1674 if (tags == TAGS_DEFAULT && autotags)
1675 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1676 if (prune) {
1677 /*
1678 * We only prune based on refspecs specified
1679 * explicitly (via command line or configuration); we
1680 * don't care whether --tags was specified.
1681 */
1682 if (rs->nr) {
1683 retcode = prune_refs(rs, transaction, ref_map, transport->url);
1684 } else {
1685 retcode = prune_refs(&transport->remote->fetch,
1686 transaction, ref_map,
1687 transport->url);
1688 }
1689 if (retcode != 0)
1690 retcode = 1;
1691 }
1692
1693 if (fetch_and_consume_refs(transport, transaction, ref_map, &fetch_head)) {
1694 retcode = 1;
1695 goto cleanup;
1696 }
1697
1698 /*
1699 * If neither --no-tags nor --tags was specified, do automated tag
1700 * following.
1701 */
1702 if (tags == TAGS_DEFAULT && autotags) {
1703 struct ref *tags_ref_map = NULL, **tail = &tags_ref_map;
1704
1705 find_non_local_tags(remote_refs, transaction, &tags_ref_map, &tail);
1706 if (tags_ref_map) {
1707 /*
1708 * If backfilling of tags fails then we want to tell
1709 * the user so, but we have to continue regardless to
1710 * populate upstream information of the references we
1711 * have already fetched above. The exception though is
1712 * when `--atomic` is passed: in that case we'll abort
1713 * the transaction and don't commit anything.
1714 */
1715 if (backfill_tags(transport, transaction, tags_ref_map,
1716 &fetch_head))
1717 retcode = 1;
1718 }
1719
1720 free_refs(tags_ref_map);
1721 }
1722
1723 if (transaction) {
1724 if (retcode)
1725 goto cleanup;
1726
1727 retcode = ref_transaction_commit(transaction, &err);
1728 if (retcode) {
1729 error("%s", err.buf);
1730 ref_transaction_free(transaction);
1731 transaction = NULL;
1732 goto cleanup;
1733 }
1734 }
1735
1736 commit_fetch_head(&fetch_head);
1737
1738 if (set_upstream) {
1739 struct branch *branch = branch_get("HEAD");
1740 struct ref *rm;
1741 struct ref *source_ref = NULL;
1742
1743 /*
1744 * We're setting the upstream configuration for the
1745 * current branch. The relevant upstream is the
1746 * fetched branch that is meant to be merged with the
1747 * current one, i.e. the one fetched to FETCH_HEAD.
1748 *
1749 * When there are several such branches, consider the
1750 * request ambiguous and err on the safe side by doing
1751 * nothing and just emit a warning.
1752 */
1753 for (rm = ref_map; rm; rm = rm->next) {
1754 if (!rm->peer_ref) {
1755 if (source_ref) {
1756 warning(_("multiple branches detected, incompatible with --set-upstream"));
1757 goto cleanup;
1758 } else {
1759 source_ref = rm;
1760 }
1761 }
1762 }
1763 if (source_ref) {
1764 if (!branch) {
1765 const char *shortname = source_ref->name;
1766 skip_prefix(shortname, "refs/heads/", &shortname);
1767
1768 warning(_("could not set upstream of HEAD to '%s' from '%s' when "
1769 "it does not point to any branch."),
1770 shortname, transport->remote->name);
1771 goto cleanup;
1772 }
1773
1774 if (!strcmp(source_ref->name, "HEAD") ||
1775 starts_with(source_ref->name, "refs/heads/"))
1776 install_branch_config(0,
1777 branch->name,
1778 transport->remote->name,
1779 source_ref->name);
1780 else if (starts_with(source_ref->name, "refs/remotes/"))
1781 warning(_("not setting upstream for a remote remote-tracking branch"));
1782 else if (starts_with(source_ref->name, "refs/tags/"))
1783 warning(_("not setting upstream for a remote tag"));
1784 else
1785 warning(_("unknown branch type"));
1786 } else {
1787 warning(_("no source branch found;\n"
1788 "you need to specify exactly one branch with the --set-upstream option"));
1789 }
1790 }
1791
1792 cleanup:
1793 if (retcode && transaction) {
1794 ref_transaction_abort(transaction, &err);
1795 error("%s", err.buf);
1796 }
1797
1798 close_fetch_head(&fetch_head);
1799 strbuf_release(&err);
1800 free_refs(ref_map);
1801 return retcode;
1802 }
1803
1804 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1805 {
1806 struct string_list *list = priv;
1807 if (!remote->skip_default_update)
1808 string_list_append(list, remote->name);
1809 return 0;
1810 }
1811
1812 struct remote_group_data {
1813 const char *name;
1814 struct string_list *list;
1815 };
1816
1817 static int get_remote_group(const char *key, const char *value, void *priv)
1818 {
1819 struct remote_group_data *g = priv;
1820
1821 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1822 /* split list by white space */
1823 while (*value) {
1824 size_t wordlen = strcspn(value, " \t\n");
1825
1826 if (wordlen >= 1)
1827 string_list_append_nodup(g->list,
1828 xstrndup(value, wordlen));
1829 value += wordlen + (value[wordlen] != '\0');
1830 }
1831 }
1832
1833 return 0;
1834 }
1835
1836 static int add_remote_or_group(const char *name, struct string_list *list)
1837 {
1838 int prev_nr = list->nr;
1839 struct remote_group_data g;
1840 g.name = name; g.list = list;
1841
1842 git_config(get_remote_group, &g);
1843 if (list->nr == prev_nr) {
1844 struct remote *remote = remote_get(name);
1845 if (!remote_is_configured(remote, 0))
1846 return 0;
1847 string_list_append(list, remote->name);
1848 }
1849 return 1;
1850 }
1851
1852 static void add_options_to_argv(struct strvec *argv)
1853 {
1854 if (dry_run)
1855 strvec_push(argv, "--dry-run");
1856 if (prune != -1)
1857 strvec_push(argv, prune ? "--prune" : "--no-prune");
1858 if (prune_tags != -1)
1859 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1860 if (update_head_ok)
1861 strvec_push(argv, "--update-head-ok");
1862 if (force)
1863 strvec_push(argv, "--force");
1864 if (keep)
1865 strvec_push(argv, "--keep");
1866 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1867 strvec_push(argv, "--recurse-submodules");
1868 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1869 strvec_push(argv, "--recurse-submodules=on-demand");
1870 if (tags == TAGS_SET)
1871 strvec_push(argv, "--tags");
1872 else if (tags == TAGS_UNSET)
1873 strvec_push(argv, "--no-tags");
1874 if (verbosity >= 2)
1875 strvec_push(argv, "-v");
1876 if (verbosity >= 1)
1877 strvec_push(argv, "-v");
1878 else if (verbosity < 0)
1879 strvec_push(argv, "-q");
1880 if (family == TRANSPORT_FAMILY_IPV4)
1881 strvec_push(argv, "--ipv4");
1882 else if (family == TRANSPORT_FAMILY_IPV6)
1883 strvec_push(argv, "--ipv6");
1884 }
1885
1886 /* Fetch multiple remotes in parallel */
1887
1888 struct parallel_fetch_state {
1889 const char **argv;
1890 struct string_list *remotes;
1891 int next, result;
1892 };
1893
1894 static int fetch_next_remote(struct child_process *cp, struct strbuf *out,
1895 void *cb, void **task_cb)
1896 {
1897 struct parallel_fetch_state *state = cb;
1898 char *remote;
1899
1900 if (state->next < 0 || state->next >= state->remotes->nr)
1901 return 0;
1902
1903 remote = state->remotes->items[state->next++].string;
1904 *task_cb = remote;
1905
1906 strvec_pushv(&cp->args, state->argv);
1907 strvec_push(&cp->args, remote);
1908 cp->git_cmd = 1;
1909
1910 if (verbosity >= 0)
1911 printf(_("Fetching %s\n"), remote);
1912
1913 return 1;
1914 }
1915
1916 static int fetch_failed_to_start(struct strbuf *out, void *cb, void *task_cb)
1917 {
1918 struct parallel_fetch_state *state = cb;
1919 const char *remote = task_cb;
1920
1921 state->result = error(_("could not fetch %s"), remote);
1922
1923 return 0;
1924 }
1925
1926 static int fetch_finished(int result, struct strbuf *out,
1927 void *cb, void *task_cb)
1928 {
1929 struct parallel_fetch_state *state = cb;
1930 const char *remote = task_cb;
1931
1932 if (result) {
1933 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1934 remote, result);
1935 state->result = -1;
1936 }
1937
1938 return 0;
1939 }
1940
1941 static int fetch_multiple(struct string_list *list, int max_children)
1942 {
1943 int i, result = 0;
1944 struct strvec argv = STRVEC_INIT;
1945
1946 if (!append && write_fetch_head) {
1947 int errcode = truncate_fetch_head();
1948 if (errcode)
1949 return errcode;
1950 }
1951
1952 strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
1953 "--no-write-commit-graph", NULL);
1954 add_options_to_argv(&argv);
1955
1956 if (max_children != 1 && list->nr != 1) {
1957 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1958 const struct run_process_parallel_opts opts = {
1959 .tr2_category = "fetch",
1960 .tr2_label = "parallel/fetch",
1961
1962 .processes = max_children,
1963
1964 .get_next_task = &fetch_next_remote,
1965 .start_failure = &fetch_failed_to_start,
1966 .task_finished = &fetch_finished,
1967 .data = &state,
1968 };
1969
1970 strvec_push(&argv, "--end-of-options");
1971
1972 run_processes_parallel(&opts);
1973 result = state.result;
1974 } else
1975 for (i = 0; i < list->nr; i++) {
1976 const char *name = list->items[i].string;
1977 struct child_process cmd = CHILD_PROCESS_INIT;
1978
1979 strvec_pushv(&cmd.args, argv.v);
1980 strvec_push(&cmd.args, name);
1981 if (verbosity >= 0)
1982 printf(_("Fetching %s\n"), name);
1983 cmd.git_cmd = 1;
1984 if (run_command(&cmd)) {
1985 error(_("could not fetch %s"), name);
1986 result = 1;
1987 }
1988 }
1989
1990 strvec_clear(&argv);
1991 return !!result;
1992 }
1993
1994 /*
1995 * Fetching from the promisor remote should use the given filter-spec
1996 * or inherit the default filter-spec from the config.
1997 */
1998 static inline void fetch_one_setup_partial(struct remote *remote)
1999 {
2000 /*
2001 * Explicit --no-filter argument overrides everything, regardless
2002 * of any prior partial clones and fetches.
2003 */
2004 if (filter_options.no_filter)
2005 return;
2006
2007 /*
2008 * If no prior partial clone/fetch and the current fetch DID NOT
2009 * request a partial-fetch, do a normal fetch.
2010 */
2011 if (!has_promisor_remote() && !filter_options.choice)
2012 return;
2013
2014 /*
2015 * If this is a partial-fetch request, we enable partial on
2016 * this repo if not already enabled and remember the given
2017 * filter-spec as the default for subsequent fetches to this
2018 * remote if there is currently no default filter-spec.
2019 */
2020 if (filter_options.choice) {
2021 partial_clone_register(remote->name, &filter_options);
2022 return;
2023 }
2024
2025 /*
2026 * Do a partial-fetch from the promisor remote using either the
2027 * explicitly given filter-spec or inherit the filter-spec from
2028 * the config.
2029 */
2030 if (!filter_options.choice)
2031 partial_clone_get_default_filter_spec(&filter_options, remote->name);
2032 return;
2033 }
2034
2035 static int fetch_one(struct remote *remote, int argc, const char **argv,
2036 int prune_tags_ok, int use_stdin_refspecs)
2037 {
2038 struct refspec rs = REFSPEC_INIT_FETCH;
2039 int i;
2040 int exit_code;
2041 int maybe_prune_tags;
2042 int remote_via_config = remote_is_configured(remote, 0);
2043
2044 if (!remote)
2045 die(_("no remote repository specified; please specify either a URL or a\n"
2046 "remote name from which new revisions should be fetched"));
2047
2048 gtransport = prepare_transport(remote, 1);
2049
2050 if (prune < 0) {
2051 /* no command line request */
2052 if (0 <= remote->prune)
2053 prune = remote->prune;
2054 else if (0 <= fetch_prune_config)
2055 prune = fetch_prune_config;
2056 else
2057 prune = PRUNE_BY_DEFAULT;
2058 }
2059
2060 if (prune_tags < 0) {
2061 /* no command line request */
2062 if (0 <= remote->prune_tags)
2063 prune_tags = remote->prune_tags;
2064 else if (0 <= fetch_prune_tags_config)
2065 prune_tags = fetch_prune_tags_config;
2066 else
2067 prune_tags = PRUNE_TAGS_BY_DEFAULT;
2068 }
2069
2070 maybe_prune_tags = prune_tags_ok && prune_tags;
2071 if (maybe_prune_tags && remote_via_config)
2072 refspec_append(&remote->fetch, TAG_REFSPEC);
2073
2074 if (maybe_prune_tags && (argc || !remote_via_config))
2075 refspec_append(&rs, TAG_REFSPEC);
2076
2077 for (i = 0; i < argc; i++) {
2078 if (!strcmp(argv[i], "tag")) {
2079 i++;
2080 if (i >= argc)
2081 die(_("you need to specify a tag name"));
2082
2083 refspec_appendf(&rs, "refs/tags/%s:refs/tags/%s",
2084 argv[i], argv[i]);
2085 } else {
2086 refspec_append(&rs, argv[i]);
2087 }
2088 }
2089
2090 if (use_stdin_refspecs) {
2091 struct strbuf line = STRBUF_INIT;
2092 while (strbuf_getline_lf(&line, stdin) != EOF)
2093 refspec_append(&rs, line.buf);
2094 strbuf_release(&line);
2095 }
2096
2097 if (server_options.nr)
2098 gtransport->server_options = &server_options;
2099
2100 sigchain_push_common(unlock_pack_on_signal);
2101 atexit(unlock_pack_atexit);
2102 sigchain_push(SIGPIPE, SIG_IGN);
2103 exit_code = do_fetch(gtransport, &rs);
2104 sigchain_pop(SIGPIPE);
2105 refspec_clear(&rs);
2106 transport_disconnect(gtransport);
2107 gtransport = NULL;
2108 return exit_code;
2109 }
2110
2111 int cmd_fetch(int argc, const char **argv, const char *prefix)
2112 {
2113 int i;
2114 const char *bundle_uri;
2115 struct string_list list = STRING_LIST_INIT_DUP;
2116 struct remote *remote = NULL;
2117 int result = 0;
2118 int prune_tags_ok = 1;
2119
2120 packet_trace_identity("fetch");
2121
2122 /* Record the command line for the reflog */
2123 strbuf_addstr(&default_rla, "fetch");
2124 for (i = 1; i < argc; i++) {
2125 /* This handles non-URLs gracefully */
2126 char *anon = transport_anonymize_url(argv[i]);
2127
2128 strbuf_addf(&default_rla, " %s", anon);
2129 free(anon);
2130 }
2131
2132 git_config(git_fetch_config, NULL);
2133 if (the_repository->gitdir) {
2134 prepare_repo_settings(the_repository);
2135 the_repository->settings.command_requires_full_index = 0;
2136 }
2137
2138 argc = parse_options(argc, argv, prefix,
2139 builtin_fetch_options, builtin_fetch_usage, 0);
2140
2141 if (recurse_submodules_cli != RECURSE_SUBMODULES_DEFAULT)
2142 recurse_submodules = recurse_submodules_cli;
2143
2144 if (negotiate_only) {
2145 switch (recurse_submodules_cli) {
2146 case RECURSE_SUBMODULES_OFF:
2147 case RECURSE_SUBMODULES_DEFAULT:
2148 /*
2149 * --negotiate-only should never recurse into
2150 * submodules. Skip it by setting recurse_submodules to
2151 * RECURSE_SUBMODULES_OFF.
2152 */
2153 recurse_submodules = RECURSE_SUBMODULES_OFF;
2154 break;
2155
2156 default:
2157 die(_("options '%s' and '%s' cannot be used together"),
2158 "--negotiate-only", "--recurse-submodules");
2159 }
2160 }
2161
2162 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
2163 int *sfjc = submodule_fetch_jobs_config == -1
2164 ? &submodule_fetch_jobs_config : NULL;
2165 int *rs = recurse_submodules == RECURSE_SUBMODULES_DEFAULT
2166 ? &recurse_submodules : NULL;
2167
2168 fetch_config_from_gitmodules(sfjc, rs);
2169 }
2170
2171 if (negotiate_only && !negotiation_tip.nr)
2172 die(_("--negotiate-only needs one or more --negotiation-tip=*"));
2173
2174 if (deepen_relative) {
2175 if (deepen_relative < 0)
2176 die(_("negative depth in --deepen is not supported"));
2177 if (depth)
2178 die(_("options '%s' and '%s' cannot be used together"), "--deepen", "--depth");
2179 depth = xstrfmt("%d", deepen_relative);
2180 }
2181 if (unshallow) {
2182 if (depth)
2183 die(_("options '%s' and '%s' cannot be used together"), "--depth", "--unshallow");
2184 else if (!is_repository_shallow(the_repository))
2185 die(_("--unshallow on a complete repository does not make sense"));
2186 else
2187 depth = xstrfmt("%d", INFINITE_DEPTH);
2188 }
2189
2190 /* no need to be strict, transport_set_option() will validate it again */
2191 if (depth && atoi(depth) < 1)
2192 die(_("depth %s is not a positive number"), depth);
2193 if (depth || deepen_since || deepen_not.nr)
2194 deepen = 1;
2195
2196 /* FETCH_HEAD never gets updated in --dry-run mode */
2197 if (dry_run)
2198 write_fetch_head = 0;
2199
2200 if (!max_jobs)
2201 max_jobs = online_cpus();
2202
2203 if (!git_config_get_string_tmp("fetch.bundleuri", &bundle_uri) &&
2204 fetch_bundle_uri(the_repository, bundle_uri, NULL))
2205 warning(_("failed to fetch bundles from '%s'"), bundle_uri);
2206
2207 if (all) {
2208 if (argc == 1)
2209 die(_("fetch --all does not take a repository argument"));
2210 else if (argc > 1)
2211 die(_("fetch --all does not make sense with refspecs"));
2212 (void) for_each_remote(get_one_remote_for_fetch, &list);
2213
2214 /* do not do fetch_multiple() of one */
2215 if (list.nr == 1)
2216 remote = remote_get(list.items[0].string);
2217 } else if (argc == 0) {
2218 /* No arguments -- use default remote */
2219 remote = remote_get(NULL);
2220 } else if (multiple) {
2221 /* All arguments are assumed to be remotes or groups */
2222 for (i = 0; i < argc; i++)
2223 if (!add_remote_or_group(argv[i], &list))
2224 die(_("no such remote or remote group: %s"),
2225 argv[i]);
2226 } else {
2227 /* Single remote or group */
2228 (void) add_remote_or_group(argv[0], &list);
2229 if (list.nr > 1) {
2230 /* More than one remote */
2231 if (argc > 1)
2232 die(_("fetching a group and specifying refspecs does not make sense"));
2233 } else {
2234 /* Zero or one remotes */
2235 remote = remote_get(argv[0]);
2236 prune_tags_ok = (argc == 1);
2237 argc--;
2238 argv++;
2239 }
2240 }
2241 string_list_remove_duplicates(&list, 0);
2242
2243 if (negotiate_only) {
2244 struct oidset acked_commits = OIDSET_INIT;
2245 struct oidset_iter iter;
2246 const struct object_id *oid;
2247
2248 if (!remote)
2249 die(_("must supply remote when using --negotiate-only"));
2250 gtransport = prepare_transport(remote, 1);
2251 if (gtransport->smart_options) {
2252 gtransport->smart_options->acked_commits = &acked_commits;
2253 } else {
2254 warning(_("protocol does not support --negotiate-only, exiting"));
2255 result = 1;
2256 goto cleanup;
2257 }
2258 if (server_options.nr)
2259 gtransport->server_options = &server_options;
2260 result = transport_fetch_refs(gtransport, NULL);
2261
2262 oidset_iter_init(&acked_commits, &iter);
2263 while ((oid = oidset_iter_next(&iter)))
2264 printf("%s\n", oid_to_hex(oid));
2265 oidset_clear(&acked_commits);
2266 } else if (remote) {
2267 if (filter_options.choice || has_promisor_remote())
2268 fetch_one_setup_partial(remote);
2269 result = fetch_one(remote, argc, argv, prune_tags_ok, stdin_refspecs);
2270 } else {
2271 int max_children = max_jobs;
2272
2273 if (filter_options.choice)
2274 die(_("--filter can only be used with the remote "
2275 "configured in extensions.partialclone"));
2276
2277 if (atomic_fetch)
2278 die(_("--atomic can only be used when fetching "
2279 "from one remote"));
2280
2281 if (stdin_refspecs)
2282 die(_("--stdin can only be used when fetching "
2283 "from one remote"));
2284
2285 if (max_children < 0)
2286 max_children = fetch_parallel_config;
2287
2288 /* TODO should this also die if we have a previous partial-clone? */
2289 result = fetch_multiple(&list, max_children);
2290 }
2291
2292
2293 /*
2294 * This is only needed after fetch_one(), which does not fetch
2295 * submodules by itself.
2296 *
2297 * When we fetch from multiple remotes, fetch_multiple() has
2298 * already updated submodules to grab commits necessary for
2299 * the fetched history from each remote, so there is no need
2300 * to fetch submodules from here.
2301 */
2302 if (!result && remote && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
2303 struct strvec options = STRVEC_INIT;
2304 int max_children = max_jobs;
2305
2306 if (max_children < 0)
2307 max_children = submodule_fetch_jobs_config;
2308 if (max_children < 0)
2309 max_children = fetch_parallel_config;
2310
2311 add_options_to_argv(&options);
2312 result = fetch_submodules(the_repository,
2313 &options,
2314 submodule_prefix,
2315 recurse_submodules,
2316 recurse_submodules_default,
2317 verbosity < 0,
2318 max_children);
2319 strvec_clear(&options);
2320 }
2321
2322 /*
2323 * Skip irrelevant tasks because we know objects were not
2324 * fetched.
2325 *
2326 * NEEDSWORK: as a future optimization, we can return early
2327 * whenever objects were not fetched e.g. if we already have all
2328 * of them.
2329 */
2330 if (negotiate_only)
2331 goto cleanup;
2332
2333 prepare_repo_settings(the_repository);
2334 if (fetch_write_commit_graph > 0 ||
2335 (fetch_write_commit_graph < 0 &&
2336 the_repository->settings.fetch_write_commit_graph)) {
2337 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
2338
2339 if (progress)
2340 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
2341
2342 write_commit_graph_reachable(the_repository->objects->odb,
2343 commit_graph_flags,
2344 NULL);
2345 }
2346
2347 if (enable_auto_gc) {
2348 if (refetch) {
2349 /*
2350 * Hint auto-maintenance strongly to encourage repacking,
2351 * but respect config settings disabling it.
2352 */
2353 int opt_val;
2354 if (git_config_get_int("gc.autopacklimit", &opt_val))
2355 opt_val = -1;
2356 if (opt_val != 0)
2357 git_config_push_parameter("gc.autoPackLimit=1");
2358
2359 if (git_config_get_int("maintenance.incremental-repack.auto", &opt_val))
2360 opt_val = -1;
2361 if (opt_val != 0)
2362 git_config_push_parameter("maintenance.incremental-repack.auto=-1");
2363 }
2364 run_auto_maintenance(verbosity < 0);
2365 }
2366
2367 cleanup:
2368 string_list_clear(&list, 0);
2369 return result;
2370 }