]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/fetch.c
maintenance: replace run_auto_gc()
[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
32 #define FORCED_UPDATES_DELAY_WARNING_IN_MS (10 * 1000)
33
34 static const char * const builtin_fetch_usage[] = {
35 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
36 N_("git fetch [<options>] <group>"),
37 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
38 N_("git fetch --all [<options>]"),
39 NULL
40 };
41
42 enum {
43 TAGS_UNSET = 0,
44 TAGS_DEFAULT = 1,
45 TAGS_SET = 2
46 };
47
48 static int fetch_prune_config = -1; /* unspecified */
49 static int fetch_show_forced_updates = 1;
50 static uint64_t forced_updates_ms = 0;
51 static int prune = -1; /* unspecified */
52 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
53
54 static int fetch_prune_tags_config = -1; /* unspecified */
55 static int prune_tags = -1; /* unspecified */
56 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
57
58 static int all, append, dry_run, force, keep, multiple, update_head_ok;
59 static int write_fetch_head = 1;
60 static int verbosity, deepen_relative, set_upstream;
61 static int progress = -1;
62 static int enable_auto_gc = 1;
63 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
64 static int max_jobs = -1, submodule_fetch_jobs_config = -1;
65 static int fetch_parallel_config = 1;
66 static enum transport_family family;
67 static const char *depth;
68 static const char *deepen_since;
69 static const char *upload_pack;
70 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
71 static struct strbuf default_rla = STRBUF_INIT;
72 static struct transport *gtransport;
73 static struct transport *gsecondary;
74 static const char *submodule_prefix = "";
75 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
76 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
77 static int shown_url = 0;
78 static struct refspec refmap = REFSPEC_INIT_FETCH;
79 static struct list_objects_filter_options filter_options;
80 static struct string_list server_options = STRING_LIST_INIT_DUP;
81 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
82 static int fetch_write_commit_graph = -1;
83
84 static int git_fetch_config(const char *k, const char *v, void *cb)
85 {
86 if (!strcmp(k, "fetch.prune")) {
87 fetch_prune_config = git_config_bool(k, v);
88 return 0;
89 }
90
91 if (!strcmp(k, "fetch.prunetags")) {
92 fetch_prune_tags_config = git_config_bool(k, v);
93 return 0;
94 }
95
96 if (!strcmp(k, "fetch.showforcedupdates")) {
97 fetch_show_forced_updates = git_config_bool(k, v);
98 return 0;
99 }
100
101 if (!strcmp(k, "submodule.recurse")) {
102 int r = git_config_bool(k, v) ?
103 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
104 recurse_submodules = r;
105 }
106
107 if (!strcmp(k, "submodule.fetchjobs")) {
108 submodule_fetch_jobs_config = parse_submodule_fetchjobs(k, v);
109 return 0;
110 } else if (!strcmp(k, "fetch.recursesubmodules")) {
111 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
112 return 0;
113 }
114
115 if (!strcmp(k, "fetch.parallel")) {
116 fetch_parallel_config = git_config_int(k, v);
117 if (fetch_parallel_config < 0)
118 die(_("fetch.parallel cannot be negative"));
119 return 0;
120 }
121
122 return git_default_config(k, v, cb);
123 }
124
125 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
126 {
127 BUG_ON_OPT_NEG(unset);
128
129 /*
130 * "git fetch --refmap='' origin foo"
131 * can be used to tell the command not to store anywhere
132 */
133 refspec_append(&refmap, arg);
134
135 return 0;
136 }
137
138 static struct option builtin_fetch_options[] = {
139 OPT__VERBOSITY(&verbosity),
140 OPT_BOOL(0, "all", &all,
141 N_("fetch from all remotes")),
142 OPT_BOOL(0, "set-upstream", &set_upstream,
143 N_("set upstream for git pull/fetch")),
144 OPT_BOOL('a', "append", &append,
145 N_("append to .git/FETCH_HEAD instead of overwriting")),
146 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
147 N_("path to upload pack on remote end")),
148 OPT__FORCE(&force, N_("force overwrite of local reference"), 0),
149 OPT_BOOL('m', "multiple", &multiple,
150 N_("fetch from multiple remotes")),
151 OPT_SET_INT('t', "tags", &tags,
152 N_("fetch all tags and associated objects"), TAGS_SET),
153 OPT_SET_INT('n', NULL, &tags,
154 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
155 OPT_INTEGER('j', "jobs", &max_jobs,
156 N_("number of submodules fetched in parallel")),
157 OPT_BOOL('p', "prune", &prune,
158 N_("prune remote-tracking branches no longer on remote")),
159 OPT_BOOL('P', "prune-tags", &prune_tags,
160 N_("prune local tags no longer on remote and clobber changed tags")),
161 OPT_CALLBACK_F(0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
162 N_("control recursive fetching of submodules"),
163 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules),
164 OPT_BOOL(0, "dry-run", &dry_run,
165 N_("dry run")),
166 OPT_BOOL(0, "write-fetch-head", &write_fetch_head,
167 N_("write fetched references to the FETCH_HEAD file")),
168 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
169 OPT_BOOL('u', "update-head-ok", &update_head_ok,
170 N_("allow updating of HEAD ref")),
171 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
172 OPT_STRING(0, "depth", &depth, N_("depth"),
173 N_("deepen history of shallow clone")),
174 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
175 N_("deepen history of shallow repository based on time")),
176 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
177 N_("deepen history of shallow clone, excluding rev")),
178 OPT_INTEGER(0, "deepen", &deepen_relative,
179 N_("deepen history of shallow clone")),
180 OPT_SET_INT_F(0, "unshallow", &unshallow,
181 N_("convert to a complete repository"),
182 1, PARSE_OPT_NONEG),
183 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
184 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
185 OPT_CALLBACK_F(0, "recurse-submodules-default",
186 &recurse_submodules_default, N_("on-demand"),
187 N_("default for recursive fetching of submodules "
188 "(lower priority than config files)"),
189 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules),
190 OPT_BOOL(0, "update-shallow", &update_shallow,
191 N_("accept refs that update .git/shallow")),
192 OPT_CALLBACK_F(0, "refmap", NULL, N_("refmap"),
193 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg),
194 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
195 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
196 TRANSPORT_FAMILY_IPV4),
197 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
198 TRANSPORT_FAMILY_IPV6),
199 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
200 N_("report that we have only objects reachable from this object")),
201 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
202 OPT_BOOL(0, "auto-maintenance", &enable_auto_gc,
203 N_("run 'maintenance --auto' after fetching")),
204 OPT_BOOL(0, "auto-gc", &enable_auto_gc,
205 N_("run 'maintenance --auto' after fetching")),
206 OPT_BOOL(0, "show-forced-updates", &fetch_show_forced_updates,
207 N_("check for forced-updates on all updated branches")),
208 OPT_BOOL(0, "write-commit-graph", &fetch_write_commit_graph,
209 N_("write the commit-graph after fetching")),
210 OPT_END()
211 };
212
213 static void unlock_pack(void)
214 {
215 if (gtransport)
216 transport_unlock_pack(gtransport);
217 if (gsecondary)
218 transport_unlock_pack(gsecondary);
219 }
220
221 static void unlock_pack_on_signal(int signo)
222 {
223 unlock_pack();
224 sigchain_pop(signo);
225 raise(signo);
226 }
227
228 static void add_merge_config(struct ref **head,
229 const struct ref *remote_refs,
230 struct branch *branch,
231 struct ref ***tail)
232 {
233 int i;
234
235 for (i = 0; i < branch->merge_nr; i++) {
236 struct ref *rm, **old_tail = *tail;
237 struct refspec_item refspec;
238
239 for (rm = *head; rm; rm = rm->next) {
240 if (branch_merge_matches(branch, i, rm->name)) {
241 rm->fetch_head_status = FETCH_HEAD_MERGE;
242 break;
243 }
244 }
245 if (rm)
246 continue;
247
248 /*
249 * Not fetched to a remote-tracking branch? We need to fetch
250 * it anyway to allow this branch's "branch.$name.merge"
251 * to be honored by 'git pull', but we do not have to
252 * fail if branch.$name.merge is misconfigured to point
253 * at a nonexisting branch. If we were indeed called by
254 * 'git pull', it will notice the misconfiguration because
255 * there is no entry in the resulting FETCH_HEAD marked
256 * for merging.
257 */
258 memset(&refspec, 0, sizeof(refspec));
259 refspec.src = branch->merge[i]->src;
260 get_fetch_map(remote_refs, &refspec, tail, 1);
261 for (rm = *old_tail; rm; rm = rm->next)
262 rm->fetch_head_status = FETCH_HEAD_MERGE;
263 }
264 }
265
266 static void create_fetch_oidset(struct ref **head, struct oidset *out)
267 {
268 struct ref *rm = *head;
269 while (rm) {
270 oidset_insert(out, &rm->old_oid);
271 rm = rm->next;
272 }
273 }
274
275 struct refname_hash_entry {
276 struct hashmap_entry ent;
277 struct object_id oid;
278 int ignore;
279 char refname[FLEX_ARRAY];
280 };
281
282 static int refname_hash_entry_cmp(const void *hashmap_cmp_fn_data,
283 const struct hashmap_entry *eptr,
284 const struct hashmap_entry *entry_or_key,
285 const void *keydata)
286 {
287 const struct refname_hash_entry *e1, *e2;
288
289 e1 = container_of(eptr, const struct refname_hash_entry, ent);
290 e2 = container_of(entry_or_key, const struct refname_hash_entry, ent);
291 return strcmp(e1->refname, keydata ? keydata : e2->refname);
292 }
293
294 static struct refname_hash_entry *refname_hash_add(struct hashmap *map,
295 const char *refname,
296 const struct object_id *oid)
297 {
298 struct refname_hash_entry *ent;
299 size_t len = strlen(refname);
300
301 FLEX_ALLOC_MEM(ent, refname, refname, len);
302 hashmap_entry_init(&ent->ent, strhash(refname));
303 oidcpy(&ent->oid, oid);
304 hashmap_add(map, &ent->ent);
305 return ent;
306 }
307
308 static int add_one_refname(const char *refname,
309 const struct object_id *oid,
310 int flag, void *cbdata)
311 {
312 struct hashmap *refname_map = cbdata;
313
314 (void) refname_hash_add(refname_map, refname, oid);
315 return 0;
316 }
317
318 static void refname_hash_init(struct hashmap *map)
319 {
320 hashmap_init(map, refname_hash_entry_cmp, NULL, 0);
321 }
322
323 static int refname_hash_exists(struct hashmap *map, const char *refname)
324 {
325 return !!hashmap_get_from_hash(map, strhash(refname), refname);
326 }
327
328 static void clear_item(struct refname_hash_entry *item)
329 {
330 item->ignore = 1;
331 }
332
333 static void find_non_local_tags(const struct ref *refs,
334 struct ref **head,
335 struct ref ***tail)
336 {
337 struct hashmap existing_refs;
338 struct hashmap remote_refs;
339 struct oidset fetch_oids = OIDSET_INIT;
340 struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
341 struct string_list_item *remote_ref_item;
342 const struct ref *ref;
343 struct refname_hash_entry *item = NULL;
344 const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
345
346 refname_hash_init(&existing_refs);
347 refname_hash_init(&remote_refs);
348 create_fetch_oidset(head, &fetch_oids);
349
350 for_each_ref(add_one_refname, &existing_refs);
351 for (ref = refs; ref; ref = ref->next) {
352 if (!starts_with(ref->name, "refs/tags/"))
353 continue;
354
355 /*
356 * The peeled ref always follows the matching base
357 * ref, so if we see a peeled ref that we don't want
358 * to fetch then we can mark the ref entry in the list
359 * as one to ignore by setting util to NULL.
360 */
361 if (ends_with(ref->name, "^{}")) {
362 if (item &&
363 !has_object_file_with_flags(&ref->old_oid, quick_flags) &&
364 !oidset_contains(&fetch_oids, &ref->old_oid) &&
365 !has_object_file_with_flags(&item->oid, quick_flags) &&
366 !oidset_contains(&fetch_oids, &item->oid))
367 clear_item(item);
368 item = NULL;
369 continue;
370 }
371
372 /*
373 * If item is non-NULL here, then we previously saw a
374 * ref not followed by a peeled reference, so we need
375 * to check if it is a lightweight tag that we want to
376 * fetch.
377 */
378 if (item &&
379 !has_object_file_with_flags(&item->oid, quick_flags) &&
380 !oidset_contains(&fetch_oids, &item->oid))
381 clear_item(item);
382
383 item = NULL;
384
385 /* skip duplicates and refs that we already have */
386 if (refname_hash_exists(&remote_refs, ref->name) ||
387 refname_hash_exists(&existing_refs, ref->name))
388 continue;
389
390 item = refname_hash_add(&remote_refs, ref->name, &ref->old_oid);
391 string_list_insert(&remote_refs_list, ref->name);
392 }
393 hashmap_free_entries(&existing_refs, struct refname_hash_entry, ent);
394
395 /*
396 * We may have a final lightweight tag that needs to be
397 * checked to see if it needs fetching.
398 */
399 if (item &&
400 !has_object_file_with_flags(&item->oid, quick_flags) &&
401 !oidset_contains(&fetch_oids, &item->oid))
402 clear_item(item);
403
404 /*
405 * For all the tags in the remote_refs_list,
406 * add them to the list of refs to be fetched
407 */
408 for_each_string_list_item(remote_ref_item, &remote_refs_list) {
409 const char *refname = remote_ref_item->string;
410 struct ref *rm;
411 unsigned int hash = strhash(refname);
412
413 item = hashmap_get_entry_from_hash(&remote_refs, hash, refname,
414 struct refname_hash_entry, ent);
415 if (!item)
416 BUG("unseen remote ref?");
417
418 /* Unless we have already decided to ignore this item... */
419 if (item->ignore)
420 continue;
421
422 rm = alloc_ref(item->refname);
423 rm->peer_ref = alloc_ref(item->refname);
424 oidcpy(&rm->old_oid, &item->oid);
425 **tail = rm;
426 *tail = &rm->next;
427 }
428 hashmap_free_entries(&remote_refs, struct refname_hash_entry, ent);
429 string_list_clear(&remote_refs_list, 0);
430 oidset_clear(&fetch_oids);
431 }
432
433 static struct ref *get_ref_map(struct remote *remote,
434 const struct ref *remote_refs,
435 struct refspec *rs,
436 int tags, int *autotags)
437 {
438 int i;
439 struct ref *rm;
440 struct ref *ref_map = NULL;
441 struct ref **tail = &ref_map;
442
443 /* opportunistically-updated references: */
444 struct ref *orefs = NULL, **oref_tail = &orefs;
445
446 struct hashmap existing_refs;
447
448 if (rs->nr) {
449 struct refspec *fetch_refspec;
450
451 for (i = 0; i < rs->nr; i++) {
452 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
453 if (rs->items[i].dst && rs->items[i].dst[0])
454 *autotags = 1;
455 }
456 /* Merge everything on the command line (but not --tags) */
457 for (rm = ref_map; rm; rm = rm->next)
458 rm->fetch_head_status = FETCH_HEAD_MERGE;
459
460 /*
461 * For any refs that we happen to be fetching via
462 * command-line arguments, the destination ref might
463 * have been missing or have been different than the
464 * remote-tracking ref that would be derived from the
465 * configured refspec. In these cases, we want to
466 * take the opportunity to update their configured
467 * remote-tracking reference. However, we do not want
468 * to mention these entries in FETCH_HEAD at all, as
469 * they would simply be duplicates of existing
470 * entries, so we set them FETCH_HEAD_IGNORE below.
471 *
472 * We compute these entries now, based only on the
473 * refspecs specified on the command line. But we add
474 * them to the list following the refspecs resulting
475 * from the tags option so that one of the latter,
476 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
477 * by ref_remove_duplicates() in favor of one of these
478 * opportunistic entries with FETCH_HEAD_IGNORE.
479 */
480 if (refmap.nr)
481 fetch_refspec = &refmap;
482 else
483 fetch_refspec = &remote->fetch;
484
485 for (i = 0; i < fetch_refspec->nr; i++)
486 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
487 } else if (refmap.nr) {
488 die("--refmap option is only meaningful with command-line refspec(s).");
489 } else {
490 /* Use the defaults */
491 struct branch *branch = branch_get(NULL);
492 int has_merge = branch_has_merge_config(branch);
493 if (remote &&
494 (remote->fetch.nr ||
495 /* Note: has_merge implies non-NULL branch->remote_name */
496 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
497 for (i = 0; i < remote->fetch.nr; i++) {
498 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
499 if (remote->fetch.items[i].dst &&
500 remote->fetch.items[i].dst[0])
501 *autotags = 1;
502 if (!i && !has_merge && ref_map &&
503 !remote->fetch.items[0].pattern)
504 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
505 }
506 /*
507 * if the remote we're fetching from is the same
508 * as given in branch.<name>.remote, we add the
509 * ref given in branch.<name>.merge, too.
510 *
511 * Note: has_merge implies non-NULL branch->remote_name
512 */
513 if (has_merge &&
514 !strcmp(branch->remote_name, remote->name))
515 add_merge_config(&ref_map, remote_refs, branch, &tail);
516 } else {
517 ref_map = get_remote_ref(remote_refs, "HEAD");
518 if (!ref_map)
519 die(_("Couldn't find remote ref HEAD"));
520 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
521 tail = &ref_map->next;
522 }
523 }
524
525 if (tags == TAGS_SET)
526 /* also fetch all tags */
527 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
528 else if (tags == TAGS_DEFAULT && *autotags)
529 find_non_local_tags(remote_refs, &ref_map, &tail);
530
531 /* Now append any refs to be updated opportunistically: */
532 *tail = orefs;
533 for (rm = orefs; rm; rm = rm->next) {
534 rm->fetch_head_status = FETCH_HEAD_IGNORE;
535 tail = &rm->next;
536 }
537
538 ref_map = ref_remove_duplicates(ref_map);
539
540 refname_hash_init(&existing_refs);
541 for_each_ref(add_one_refname, &existing_refs);
542
543 for (rm = ref_map; rm; rm = rm->next) {
544 if (rm->peer_ref) {
545 const char *refname = rm->peer_ref->name;
546 struct refname_hash_entry *peer_item;
547 unsigned int hash = strhash(refname);
548
549 peer_item = hashmap_get_entry_from_hash(&existing_refs,
550 hash, refname,
551 struct refname_hash_entry, ent);
552 if (peer_item) {
553 struct object_id *old_oid = &peer_item->oid;
554 oidcpy(&rm->peer_ref->old_oid, old_oid);
555 }
556 }
557 }
558 hashmap_free_entries(&existing_refs, struct refname_hash_entry, ent);
559
560 return ref_map;
561 }
562
563 #define STORE_REF_ERROR_OTHER 1
564 #define STORE_REF_ERROR_DF_CONFLICT 2
565
566 static int s_update_ref(const char *action,
567 struct ref *ref,
568 int check_old)
569 {
570 char *msg;
571 char *rla = getenv("GIT_REFLOG_ACTION");
572 struct ref_transaction *transaction;
573 struct strbuf err = STRBUF_INIT;
574 int ret, df_conflict = 0;
575
576 if (dry_run)
577 return 0;
578 if (!rla)
579 rla = default_rla.buf;
580 msg = xstrfmt("%s: %s", rla, action);
581
582 transaction = ref_transaction_begin(&err);
583 if (!transaction ||
584 ref_transaction_update(transaction, ref->name,
585 &ref->new_oid,
586 check_old ? &ref->old_oid : NULL,
587 0, msg, &err))
588 goto fail;
589
590 ret = ref_transaction_commit(transaction, &err);
591 if (ret) {
592 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
593 goto fail;
594 }
595
596 ref_transaction_free(transaction);
597 strbuf_release(&err);
598 free(msg);
599 return 0;
600 fail:
601 ref_transaction_free(transaction);
602 error("%s", err.buf);
603 strbuf_release(&err);
604 free(msg);
605 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
606 : STORE_REF_ERROR_OTHER;
607 }
608
609 static int refcol_width = 10;
610 static int compact_format;
611
612 static void adjust_refcol_width(const struct ref *ref)
613 {
614 int max, rlen, llen, len;
615
616 /* uptodate lines are only shown on high verbosity level */
617 if (!verbosity && oideq(&ref->peer_ref->old_oid, &ref->old_oid))
618 return;
619
620 max = term_columns();
621 rlen = utf8_strwidth(prettify_refname(ref->name));
622
623 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
624
625 /*
626 * rough estimation to see if the output line is too long and
627 * should not be counted (we can't do precise calculation
628 * anyway because we don't know if the error explanation part
629 * will be printed in update_local_ref)
630 */
631 if (compact_format) {
632 llen = 0;
633 max = max * 2 / 3;
634 }
635 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
636 if (len >= max)
637 return;
638
639 /*
640 * Not precise calculation for compact mode because '*' can
641 * appear on the left hand side of '->' and shrink the column
642 * back.
643 */
644 if (refcol_width < rlen)
645 refcol_width = rlen;
646 }
647
648 static void prepare_format_display(struct ref *ref_map)
649 {
650 struct ref *rm;
651 const char *format = "full";
652
653 git_config_get_string_const("fetch.output", &format);
654 if (!strcasecmp(format, "full"))
655 compact_format = 0;
656 else if (!strcasecmp(format, "compact"))
657 compact_format = 1;
658 else
659 die(_("configuration fetch.output contains invalid value %s"),
660 format);
661
662 for (rm = ref_map; rm; rm = rm->next) {
663 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
664 !rm->peer_ref ||
665 !strcmp(rm->name, "HEAD"))
666 continue;
667
668 adjust_refcol_width(rm);
669 }
670 }
671
672 static void print_remote_to_local(struct strbuf *display,
673 const char *remote, const char *local)
674 {
675 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
676 }
677
678 static int find_and_replace(struct strbuf *haystack,
679 const char *needle,
680 const char *placeholder)
681 {
682 const char *p = NULL;
683 int plen, nlen;
684
685 nlen = strlen(needle);
686 if (ends_with(haystack->buf, needle))
687 p = haystack->buf + haystack->len - nlen;
688 else
689 p = strstr(haystack->buf, needle);
690 if (!p)
691 return 0;
692
693 if (p > haystack->buf && p[-1] != '/')
694 return 0;
695
696 plen = strlen(p);
697 if (plen > nlen && p[nlen] != '/')
698 return 0;
699
700 strbuf_splice(haystack, p - haystack->buf, nlen,
701 placeholder, strlen(placeholder));
702 return 1;
703 }
704
705 static void print_compact(struct strbuf *display,
706 const char *remote, const char *local)
707 {
708 struct strbuf r = STRBUF_INIT;
709 struct strbuf l = STRBUF_INIT;
710
711 if (!strcmp(remote, local)) {
712 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
713 return;
714 }
715
716 strbuf_addstr(&r, remote);
717 strbuf_addstr(&l, local);
718
719 if (!find_and_replace(&r, local, "*"))
720 find_and_replace(&l, remote, "*");
721 print_remote_to_local(display, r.buf, l.buf);
722
723 strbuf_release(&r);
724 strbuf_release(&l);
725 }
726
727 static void format_display(struct strbuf *display, char code,
728 const char *summary, const char *error,
729 const char *remote, const char *local,
730 int summary_width)
731 {
732 int width = (summary_width + strlen(summary) - gettext_width(summary));
733
734 strbuf_addf(display, "%c %-*s ", code, width, summary);
735 if (!compact_format)
736 print_remote_to_local(display, remote, local);
737 else
738 print_compact(display, remote, local);
739 if (error)
740 strbuf_addf(display, " (%s)", error);
741 }
742
743 static int update_local_ref(struct ref *ref,
744 const char *remote,
745 const struct ref *remote_ref,
746 struct strbuf *display,
747 int summary_width)
748 {
749 struct commit *current = NULL, *updated;
750 enum object_type type;
751 struct branch *current_branch = branch_get(NULL);
752 const char *pretty_ref = prettify_refname(ref->name);
753 int fast_forward = 0;
754
755 type = oid_object_info(the_repository, &ref->new_oid, NULL);
756 if (type < 0)
757 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
758
759 if (oideq(&ref->old_oid, &ref->new_oid)) {
760 if (verbosity > 0)
761 format_display(display, '=', _("[up to date]"), NULL,
762 remote, pretty_ref, summary_width);
763 return 0;
764 }
765
766 if (current_branch &&
767 !strcmp(ref->name, current_branch->name) &&
768 !(update_head_ok || is_bare_repository()) &&
769 !is_null_oid(&ref->old_oid)) {
770 /*
771 * If this is the head, and it's not okay to update
772 * the head, and the old value of the head isn't empty...
773 */
774 format_display(display, '!', _("[rejected]"),
775 _("can't fetch in current branch"),
776 remote, pretty_ref, summary_width);
777 return 1;
778 }
779
780 if (!is_null_oid(&ref->old_oid) &&
781 starts_with(ref->name, "refs/tags/")) {
782 if (force || ref->force) {
783 int r;
784 r = s_update_ref("updating tag", ref, 0);
785 format_display(display, r ? '!' : 't', _("[tag update]"),
786 r ? _("unable to update local ref") : NULL,
787 remote, pretty_ref, summary_width);
788 return r;
789 } else {
790 format_display(display, '!', _("[rejected]"), _("would clobber existing tag"),
791 remote, pretty_ref, summary_width);
792 return 1;
793 }
794 }
795
796 current = lookup_commit_reference_gently(the_repository,
797 &ref->old_oid, 1);
798 updated = lookup_commit_reference_gently(the_repository,
799 &ref->new_oid, 1);
800 if (!current || !updated) {
801 const char *msg;
802 const char *what;
803 int r;
804 /*
805 * Nicely describe the new ref we're fetching.
806 * Base this on the remote's ref name, as it's
807 * more likely to follow a standard layout.
808 */
809 const char *name = remote_ref ? remote_ref->name : "";
810 if (starts_with(name, "refs/tags/")) {
811 msg = "storing tag";
812 what = _("[new tag]");
813 } else if (starts_with(name, "refs/heads/")) {
814 msg = "storing head";
815 what = _("[new branch]");
816 } else {
817 msg = "storing ref";
818 what = _("[new ref]");
819 }
820
821 r = s_update_ref(msg, ref, 0);
822 format_display(display, r ? '!' : '*', what,
823 r ? _("unable to update local ref") : NULL,
824 remote, pretty_ref, summary_width);
825 return r;
826 }
827
828 if (fetch_show_forced_updates) {
829 uint64_t t_before = getnanotime();
830 fast_forward = in_merge_bases(current, updated);
831 forced_updates_ms += (getnanotime() - t_before) / 1000000;
832 } else {
833 fast_forward = 1;
834 }
835
836 if (fast_forward) {
837 struct strbuf quickref = STRBUF_INIT;
838 int r;
839
840 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
841 strbuf_addstr(&quickref, "..");
842 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
843 r = s_update_ref("fast-forward", ref, 1);
844 format_display(display, r ? '!' : ' ', quickref.buf,
845 r ? _("unable to update local ref") : NULL,
846 remote, pretty_ref, summary_width);
847 strbuf_release(&quickref);
848 return r;
849 } else if (force || ref->force) {
850 struct strbuf quickref = STRBUF_INIT;
851 int r;
852 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
853 strbuf_addstr(&quickref, "...");
854 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
855 r = s_update_ref("forced-update", ref, 1);
856 format_display(display, r ? '!' : '+', quickref.buf,
857 r ? _("unable to update local ref") : _("forced update"),
858 remote, pretty_ref, summary_width);
859 strbuf_release(&quickref);
860 return r;
861 } else {
862 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
863 remote, pretty_ref, summary_width);
864 return 1;
865 }
866 }
867
868 static int iterate_ref_map(void *cb_data, struct object_id *oid)
869 {
870 struct ref **rm = cb_data;
871 struct ref *ref = *rm;
872
873 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
874 ref = ref->next;
875 if (!ref)
876 return -1; /* end of the list */
877 *rm = ref->next;
878 oidcpy(oid, &ref->old_oid);
879 return 0;
880 }
881
882 static const char warn_show_forced_updates[] =
883 N_("Fetch normally indicates which branches had a forced update,\n"
884 "but that check has been disabled. To re-enable, use '--show-forced-updates'\n"
885 "flag or run 'git config fetch.showForcedUpdates true'.");
886 static const char warn_time_show_forced_updates[] =
887 N_("It took %.2f seconds to check forced updates. You can use\n"
888 "'--no-show-forced-updates' or run 'git config fetch.showForcedUpdates false'\n"
889 " to avoid this check.\n");
890
891 static int store_updated_refs(const char *raw_url, const char *remote_name,
892 int connectivity_checked, struct ref *ref_map)
893 {
894 FILE *fp;
895 struct commit *commit;
896 int url_len, i, rc = 0;
897 struct strbuf note = STRBUF_INIT;
898 const char *what, *kind;
899 struct ref *rm;
900 char *url;
901 const char *filename = (!write_fetch_head
902 ? "/dev/null"
903 : git_path_fetch_head(the_repository));
904 int want_status;
905 int summary_width = transport_summary_width(ref_map);
906
907 fp = fopen(filename, "a");
908 if (!fp)
909 return error_errno(_("cannot open %s"), filename);
910
911 if (raw_url)
912 url = transport_anonymize_url(raw_url);
913 else
914 url = xstrdup("foreign");
915
916 if (!connectivity_checked) {
917 struct check_connected_options opt = CHECK_CONNECTED_INIT;
918
919 rm = ref_map;
920 if (check_connected(iterate_ref_map, &rm, &opt)) {
921 rc = error(_("%s did not send all necessary objects\n"), url);
922 goto abort;
923 }
924 }
925
926 prepare_format_display(ref_map);
927
928 /*
929 * We do a pass for each fetch_head_status type in their enum order, so
930 * merged entries are written before not-for-merge. That lets readers
931 * use FETCH_HEAD as a refname to refer to the ref to be merged.
932 */
933 for (want_status = FETCH_HEAD_MERGE;
934 want_status <= FETCH_HEAD_IGNORE;
935 want_status++) {
936 for (rm = ref_map; rm; rm = rm->next) {
937 struct ref *ref = NULL;
938 const char *merge_status_marker = "";
939
940 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
941 if (want_status == FETCH_HEAD_MERGE)
942 warning(_("reject %s because shallow roots are not allowed to be updated"),
943 rm->peer_ref ? rm->peer_ref->name : rm->name);
944 continue;
945 }
946
947 commit = lookup_commit_reference_gently(the_repository,
948 &rm->old_oid,
949 1);
950 if (!commit)
951 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
952
953 if (rm->fetch_head_status != want_status)
954 continue;
955
956 if (rm->peer_ref) {
957 ref = alloc_ref(rm->peer_ref->name);
958 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
959 oidcpy(&ref->new_oid, &rm->old_oid);
960 ref->force = rm->peer_ref->force;
961 }
962
963 if (recurse_submodules != RECURSE_SUBMODULES_OFF)
964 check_for_new_submodule_commits(&rm->old_oid);
965
966 if (!strcmp(rm->name, "HEAD")) {
967 kind = "";
968 what = "";
969 }
970 else if (skip_prefix(rm->name, "refs/heads/", &what))
971 kind = "branch";
972 else if (skip_prefix(rm->name, "refs/tags/", &what))
973 kind = "tag";
974 else if (skip_prefix(rm->name, "refs/remotes/", &what))
975 kind = "remote-tracking branch";
976 else {
977 kind = "";
978 what = rm->name;
979 }
980
981 url_len = strlen(url);
982 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
983 ;
984 url_len = i + 1;
985 if (4 < i && !strncmp(".git", url + i - 3, 4))
986 url_len = i - 3;
987
988 strbuf_reset(&note);
989 if (*what) {
990 if (*kind)
991 strbuf_addf(&note, "%s ", kind);
992 strbuf_addf(&note, "'%s' of ", what);
993 }
994 switch (rm->fetch_head_status) {
995 case FETCH_HEAD_NOT_FOR_MERGE:
996 merge_status_marker = "not-for-merge";
997 /* fall-through */
998 case FETCH_HEAD_MERGE:
999 fprintf(fp, "%s\t%s\t%s",
1000 oid_to_hex(&rm->old_oid),
1001 merge_status_marker,
1002 note.buf);
1003 for (i = 0; i < url_len; ++i)
1004 if ('\n' == url[i])
1005 fputs("\\n", fp);
1006 else
1007 fputc(url[i], fp);
1008 fputc('\n', fp);
1009 break;
1010 default:
1011 /* do not write anything to FETCH_HEAD */
1012 break;
1013 }
1014
1015 strbuf_reset(&note);
1016 if (ref) {
1017 rc |= update_local_ref(ref, what, rm, &note,
1018 summary_width);
1019 free(ref);
1020 } else
1021 format_display(&note, '*',
1022 *kind ? kind : "branch", NULL,
1023 *what ? what : "HEAD",
1024 "FETCH_HEAD", summary_width);
1025 if (note.len) {
1026 if (verbosity >= 0 && !shown_url) {
1027 fprintf(stderr, _("From %.*s\n"),
1028 url_len, url);
1029 shown_url = 1;
1030 }
1031 if (verbosity >= 0)
1032 fprintf(stderr, " %s\n", note.buf);
1033 }
1034 }
1035 }
1036
1037 if (rc & STORE_REF_ERROR_DF_CONFLICT)
1038 error(_("some local refs could not be updated; try running\n"
1039 " 'git remote prune %s' to remove any old, conflicting "
1040 "branches"), remote_name);
1041
1042 if (advice_fetch_show_forced_updates) {
1043 if (!fetch_show_forced_updates) {
1044 warning(_(warn_show_forced_updates));
1045 } else if (forced_updates_ms > FORCED_UPDATES_DELAY_WARNING_IN_MS) {
1046 warning(_(warn_time_show_forced_updates),
1047 forced_updates_ms / 1000.0);
1048 }
1049 }
1050
1051 abort:
1052 strbuf_release(&note);
1053 free(url);
1054 fclose(fp);
1055 return rc;
1056 }
1057
1058 /*
1059 * We would want to bypass the object transfer altogether if
1060 * everything we are going to fetch already exists and is connected
1061 * locally.
1062 */
1063 static int check_exist_and_connected(struct ref *ref_map)
1064 {
1065 struct ref *rm = ref_map;
1066 struct check_connected_options opt = CHECK_CONNECTED_INIT;
1067 struct ref *r;
1068
1069 /*
1070 * If we are deepening a shallow clone we already have these
1071 * objects reachable. Running rev-list here will return with
1072 * a good (0) exit status and we'll bypass the fetch that we
1073 * really need to perform. Claiming failure now will ensure
1074 * we perform the network exchange to deepen our history.
1075 */
1076 if (deepen)
1077 return -1;
1078
1079 /*
1080 * check_connected() allows objects to merely be promised, but
1081 * we need all direct targets to exist.
1082 */
1083 for (r = rm; r; r = r->next) {
1084 if (!has_object_file_with_flags(&r->old_oid,
1085 OBJECT_INFO_SKIP_FETCH_OBJECT))
1086 return -1;
1087 }
1088
1089 opt.quiet = 1;
1090 return check_connected(iterate_ref_map, &rm, &opt);
1091 }
1092
1093 static int fetch_refs(struct transport *transport, struct ref *ref_map)
1094 {
1095 int ret = check_exist_and_connected(ref_map);
1096 if (ret) {
1097 trace2_region_enter("fetch", "fetch_refs", the_repository);
1098 ret = transport_fetch_refs(transport, ref_map);
1099 trace2_region_leave("fetch", "fetch_refs", the_repository);
1100 }
1101 if (!ret)
1102 /*
1103 * Keep the new pack's ".keep" file around to allow the caller
1104 * time to update refs to reference the new objects.
1105 */
1106 return 0;
1107 transport_unlock_pack(transport);
1108 return ret;
1109 }
1110
1111 /* Update local refs based on the ref values fetched from a remote */
1112 static int consume_refs(struct transport *transport, struct ref *ref_map)
1113 {
1114 int connectivity_checked = transport->smart_options
1115 ? transport->smart_options->connectivity_checked : 0;
1116 int ret;
1117 trace2_region_enter("fetch", "consume_refs", the_repository);
1118 ret = store_updated_refs(transport->url,
1119 transport->remote->name,
1120 connectivity_checked,
1121 ref_map);
1122 transport_unlock_pack(transport);
1123 trace2_region_leave("fetch", "consume_refs", the_repository);
1124 return ret;
1125 }
1126
1127 static int prune_refs(struct refspec *rs, struct ref *ref_map,
1128 const char *raw_url)
1129 {
1130 int url_len, i, result = 0;
1131 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
1132 char *url;
1133 int summary_width = transport_summary_width(stale_refs);
1134 const char *dangling_msg = dry_run
1135 ? _(" (%s will become dangling)")
1136 : _(" (%s has become dangling)");
1137
1138 if (raw_url)
1139 url = transport_anonymize_url(raw_url);
1140 else
1141 url = xstrdup("foreign");
1142
1143 url_len = strlen(url);
1144 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
1145 ;
1146
1147 url_len = i + 1;
1148 if (4 < i && !strncmp(".git", url + i - 3, 4))
1149 url_len = i - 3;
1150
1151 if (!dry_run) {
1152 struct string_list refnames = STRING_LIST_INIT_NODUP;
1153
1154 for (ref = stale_refs; ref; ref = ref->next)
1155 string_list_append(&refnames, ref->name);
1156
1157 result = delete_refs("fetch: prune", &refnames, 0);
1158 string_list_clear(&refnames, 0);
1159 }
1160
1161 if (verbosity >= 0) {
1162 for (ref = stale_refs; ref; ref = ref->next) {
1163 struct strbuf sb = STRBUF_INIT;
1164 if (!shown_url) {
1165 fprintf(stderr, _("From %.*s\n"), url_len, url);
1166 shown_url = 1;
1167 }
1168 format_display(&sb, '-', _("[deleted]"), NULL,
1169 _("(none)"), prettify_refname(ref->name),
1170 summary_width);
1171 fprintf(stderr, " %s\n",sb.buf);
1172 strbuf_release(&sb);
1173 warn_dangling_symref(stderr, dangling_msg, ref->name);
1174 }
1175 }
1176
1177 free(url);
1178 free_refs(stale_refs);
1179 return result;
1180 }
1181
1182 static void check_not_current_branch(struct ref *ref_map)
1183 {
1184 struct branch *current_branch = branch_get(NULL);
1185
1186 if (is_bare_repository() || !current_branch)
1187 return;
1188
1189 for (; ref_map; ref_map = ref_map->next)
1190 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1191 ref_map->peer_ref->name))
1192 die(_("Refusing to fetch into current branch %s "
1193 "of non-bare repository"), current_branch->refname);
1194 }
1195
1196 static int truncate_fetch_head(void)
1197 {
1198 const char *filename = git_path_fetch_head(the_repository);
1199 FILE *fp = fopen_for_writing(filename);
1200
1201 if (!fp)
1202 return error_errno(_("cannot open %s"), filename);
1203 fclose(fp);
1204 return 0;
1205 }
1206
1207 static void set_option(struct transport *transport, const char *name, const char *value)
1208 {
1209 int r = transport_set_option(transport, name, value);
1210 if (r < 0)
1211 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1212 name, value, transport->url);
1213 if (r > 0)
1214 warning(_("Option \"%s\" is ignored for %s\n"),
1215 name, transport->url);
1216 }
1217
1218
1219 static int add_oid(const char *refname, const struct object_id *oid, int flags,
1220 void *cb_data)
1221 {
1222 struct oid_array *oids = cb_data;
1223
1224 oid_array_append(oids, oid);
1225 return 0;
1226 }
1227
1228 static void add_negotiation_tips(struct git_transport_options *smart_options)
1229 {
1230 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1231 int i;
1232
1233 for (i = 0; i < negotiation_tip.nr; i++) {
1234 const char *s = negotiation_tip.items[i].string;
1235 int old_nr;
1236 if (!has_glob_specials(s)) {
1237 struct object_id oid;
1238 if (get_oid(s, &oid))
1239 die("%s is not a valid object", s);
1240 oid_array_append(oids, &oid);
1241 continue;
1242 }
1243 old_nr = oids->nr;
1244 for_each_glob_ref(add_oid, s, oids);
1245 if (old_nr == oids->nr)
1246 warning("Ignoring --negotiation-tip=%s because it does not match any refs",
1247 s);
1248 }
1249 smart_options->negotiation_tips = oids;
1250 }
1251
1252 static struct transport *prepare_transport(struct remote *remote, int deepen)
1253 {
1254 struct transport *transport;
1255
1256 transport = transport_get(remote, NULL);
1257 transport_set_verbosity(transport, verbosity, progress);
1258 transport->family = family;
1259 if (upload_pack)
1260 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1261 if (keep)
1262 set_option(transport, TRANS_OPT_KEEP, "yes");
1263 if (depth)
1264 set_option(transport, TRANS_OPT_DEPTH, depth);
1265 if (deepen && deepen_since)
1266 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1267 if (deepen && deepen_not.nr)
1268 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1269 (const char *)&deepen_not);
1270 if (deepen_relative)
1271 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1272 if (update_shallow)
1273 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1274 if (filter_options.choice) {
1275 const char *spec =
1276 expand_list_objects_filter_spec(&filter_options);
1277 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER, spec);
1278 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1279 }
1280 if (negotiation_tip.nr) {
1281 if (transport->smart_options)
1282 add_negotiation_tips(transport->smart_options);
1283 else
1284 warning("Ignoring --negotiation-tip because the protocol does not support it.");
1285 }
1286 return transport;
1287 }
1288
1289 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1290 {
1291 int cannot_reuse;
1292
1293 /*
1294 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1295 * when remote helper is used (setting it to an empty string
1296 * is not unsetting). We could extend the remote helper
1297 * protocol for that, but for now, just force a new connection
1298 * without deepen-since. Similar story for deepen-not.
1299 */
1300 cannot_reuse = transport->cannot_reuse ||
1301 deepen_since || deepen_not.nr;
1302 if (cannot_reuse) {
1303 gsecondary = prepare_transport(transport->remote, 0);
1304 transport = gsecondary;
1305 }
1306
1307 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1308 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1309 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1310 if (!fetch_refs(transport, ref_map))
1311 consume_refs(transport, ref_map);
1312
1313 if (gsecondary) {
1314 transport_disconnect(gsecondary);
1315 gsecondary = NULL;
1316 }
1317 }
1318
1319 static int do_fetch(struct transport *transport,
1320 struct refspec *rs)
1321 {
1322 struct ref *ref_map;
1323 int autotags = (transport->remote->fetch_tags == 1);
1324 int retcode = 0;
1325 const struct ref *remote_refs;
1326 struct strvec ref_prefixes = STRVEC_INIT;
1327 int must_list_refs = 1;
1328
1329 if (tags == TAGS_DEFAULT) {
1330 if (transport->remote->fetch_tags == 2)
1331 tags = TAGS_SET;
1332 if (transport->remote->fetch_tags == -1)
1333 tags = TAGS_UNSET;
1334 }
1335
1336 /* if not appending, truncate FETCH_HEAD */
1337 if (!append && write_fetch_head) {
1338 retcode = truncate_fetch_head();
1339 if (retcode)
1340 goto cleanup;
1341 }
1342
1343 if (rs->nr) {
1344 int i;
1345
1346 refspec_ref_prefixes(rs, &ref_prefixes);
1347
1348 /*
1349 * We can avoid listing refs if all of them are exact
1350 * OIDs
1351 */
1352 must_list_refs = 0;
1353 for (i = 0; i < rs->nr; i++) {
1354 if (!rs->items[i].exact_sha1) {
1355 must_list_refs = 1;
1356 break;
1357 }
1358 }
1359 } else if (transport->remote && transport->remote->fetch.nr)
1360 refspec_ref_prefixes(&transport->remote->fetch, &ref_prefixes);
1361
1362 if (tags == TAGS_SET || tags == TAGS_DEFAULT) {
1363 must_list_refs = 1;
1364 if (ref_prefixes.nr)
1365 strvec_push(&ref_prefixes, "refs/tags/");
1366 }
1367
1368 if (must_list_refs) {
1369 trace2_region_enter("fetch", "remote_refs", the_repository);
1370 remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
1371 trace2_region_leave("fetch", "remote_refs", the_repository);
1372 } else
1373 remote_refs = NULL;
1374
1375 strvec_clear(&ref_prefixes);
1376
1377 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1378 tags, &autotags);
1379 if (!update_head_ok)
1380 check_not_current_branch(ref_map);
1381
1382 if (tags == TAGS_DEFAULT && autotags)
1383 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1384 if (prune) {
1385 /*
1386 * We only prune based on refspecs specified
1387 * explicitly (via command line or configuration); we
1388 * don't care whether --tags was specified.
1389 */
1390 if (rs->nr) {
1391 prune_refs(rs, ref_map, transport->url);
1392 } else {
1393 prune_refs(&transport->remote->fetch,
1394 ref_map,
1395 transport->url);
1396 }
1397 }
1398 if (fetch_refs(transport, ref_map) || consume_refs(transport, ref_map)) {
1399 free_refs(ref_map);
1400 retcode = 1;
1401 goto cleanup;
1402 }
1403
1404 if (set_upstream) {
1405 struct branch *branch = branch_get("HEAD");
1406 struct ref *rm;
1407 struct ref *source_ref = NULL;
1408
1409 /*
1410 * We're setting the upstream configuration for the
1411 * current branch. The relevant upstream is the
1412 * fetched branch that is meant to be merged with the
1413 * current one, i.e. the one fetched to FETCH_HEAD.
1414 *
1415 * When there are several such branches, consider the
1416 * request ambiguous and err on the safe side by doing
1417 * nothing and just emit a warning.
1418 */
1419 for (rm = ref_map; rm; rm = rm->next) {
1420 if (!rm->peer_ref) {
1421 if (source_ref) {
1422 warning(_("multiple branches detected, incompatible with --set-upstream"));
1423 goto skip;
1424 } else {
1425 source_ref = rm;
1426 }
1427 }
1428 }
1429 if (source_ref) {
1430 if (!strcmp(source_ref->name, "HEAD") ||
1431 starts_with(source_ref->name, "refs/heads/"))
1432 install_branch_config(0,
1433 branch->name,
1434 transport->remote->name,
1435 source_ref->name);
1436 else if (starts_with(source_ref->name, "refs/remotes/"))
1437 warning(_("not setting upstream for a remote remote-tracking branch"));
1438 else if (starts_with(source_ref->name, "refs/tags/"))
1439 warning(_("not setting upstream for a remote tag"));
1440 else
1441 warning(_("unknown branch type"));
1442 } else {
1443 warning(_("no source branch found.\n"
1444 "you need to specify exactly one branch with the --set-upstream option."));
1445 }
1446 }
1447 skip:
1448 free_refs(ref_map);
1449
1450 /* if neither --no-tags nor --tags was specified, do automated tag
1451 * following ... */
1452 if (tags == TAGS_DEFAULT && autotags) {
1453 struct ref **tail = &ref_map;
1454 ref_map = NULL;
1455 find_non_local_tags(remote_refs, &ref_map, &tail);
1456 if (ref_map)
1457 backfill_tags(transport, ref_map);
1458 free_refs(ref_map);
1459 }
1460
1461 cleanup:
1462 return retcode;
1463 }
1464
1465 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1466 {
1467 struct string_list *list = priv;
1468 if (!remote->skip_default_update)
1469 string_list_append(list, remote->name);
1470 return 0;
1471 }
1472
1473 struct remote_group_data {
1474 const char *name;
1475 struct string_list *list;
1476 };
1477
1478 static int get_remote_group(const char *key, const char *value, void *priv)
1479 {
1480 struct remote_group_data *g = priv;
1481
1482 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1483 /* split list by white space */
1484 while (*value) {
1485 size_t wordlen = strcspn(value, " \t\n");
1486
1487 if (wordlen >= 1)
1488 string_list_append_nodup(g->list,
1489 xstrndup(value, wordlen));
1490 value += wordlen + (value[wordlen] != '\0');
1491 }
1492 }
1493
1494 return 0;
1495 }
1496
1497 static int add_remote_or_group(const char *name, struct string_list *list)
1498 {
1499 int prev_nr = list->nr;
1500 struct remote_group_data g;
1501 g.name = name; g.list = list;
1502
1503 git_config(get_remote_group, &g);
1504 if (list->nr == prev_nr) {
1505 struct remote *remote = remote_get(name);
1506 if (!remote_is_configured(remote, 0))
1507 return 0;
1508 string_list_append(list, remote->name);
1509 }
1510 return 1;
1511 }
1512
1513 static void add_options_to_argv(struct strvec *argv)
1514 {
1515 if (dry_run)
1516 strvec_push(argv, "--dry-run");
1517 if (prune != -1)
1518 strvec_push(argv, prune ? "--prune" : "--no-prune");
1519 if (prune_tags != -1)
1520 strvec_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1521 if (update_head_ok)
1522 strvec_push(argv, "--update-head-ok");
1523 if (force)
1524 strvec_push(argv, "--force");
1525 if (keep)
1526 strvec_push(argv, "--keep");
1527 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1528 strvec_push(argv, "--recurse-submodules");
1529 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1530 strvec_push(argv, "--recurse-submodules=on-demand");
1531 if (tags == TAGS_SET)
1532 strvec_push(argv, "--tags");
1533 else if (tags == TAGS_UNSET)
1534 strvec_push(argv, "--no-tags");
1535 if (verbosity >= 2)
1536 strvec_push(argv, "-v");
1537 if (verbosity >= 1)
1538 strvec_push(argv, "-v");
1539 else if (verbosity < 0)
1540 strvec_push(argv, "-q");
1541
1542 }
1543
1544 /* Fetch multiple remotes in parallel */
1545
1546 struct parallel_fetch_state {
1547 const char **argv;
1548 struct string_list *remotes;
1549 int next, result;
1550 };
1551
1552 static int fetch_next_remote(struct child_process *cp, struct strbuf *out,
1553 void *cb, void **task_cb)
1554 {
1555 struct parallel_fetch_state *state = cb;
1556 char *remote;
1557
1558 if (state->next < 0 || state->next >= state->remotes->nr)
1559 return 0;
1560
1561 remote = state->remotes->items[state->next++].string;
1562 *task_cb = remote;
1563
1564 strvec_pushv(&cp->args, state->argv);
1565 strvec_push(&cp->args, remote);
1566 cp->git_cmd = 1;
1567
1568 if (verbosity >= 0)
1569 printf(_("Fetching %s\n"), remote);
1570
1571 return 1;
1572 }
1573
1574 static int fetch_failed_to_start(struct strbuf *out, void *cb, void *task_cb)
1575 {
1576 struct parallel_fetch_state *state = cb;
1577 const char *remote = task_cb;
1578
1579 state->result = error(_("Could not fetch %s"), remote);
1580
1581 return 0;
1582 }
1583
1584 static int fetch_finished(int result, struct strbuf *out,
1585 void *cb, void *task_cb)
1586 {
1587 struct parallel_fetch_state *state = cb;
1588 const char *remote = task_cb;
1589
1590 if (result) {
1591 strbuf_addf(out, _("could not fetch '%s' (exit code: %d)\n"),
1592 remote, result);
1593 state->result = -1;
1594 }
1595
1596 return 0;
1597 }
1598
1599 static int fetch_multiple(struct string_list *list, int max_children)
1600 {
1601 int i, result = 0;
1602 struct strvec argv = STRVEC_INIT;
1603
1604 if (!append && write_fetch_head) {
1605 int errcode = truncate_fetch_head();
1606 if (errcode)
1607 return errcode;
1608 }
1609
1610 strvec_pushl(&argv, "fetch", "--append", "--no-auto-gc",
1611 "--no-write-commit-graph", NULL);
1612 add_options_to_argv(&argv);
1613
1614 if (max_children != 1 && list->nr != 1) {
1615 struct parallel_fetch_state state = { argv.v, list, 0, 0 };
1616
1617 strvec_push(&argv, "--end-of-options");
1618 result = run_processes_parallel_tr2(max_children,
1619 &fetch_next_remote,
1620 &fetch_failed_to_start,
1621 &fetch_finished,
1622 &state,
1623 "fetch", "parallel/fetch");
1624
1625 if (!result)
1626 result = state.result;
1627 } else
1628 for (i = 0; i < list->nr; i++) {
1629 const char *name = list->items[i].string;
1630 strvec_push(&argv, name);
1631 if (verbosity >= 0)
1632 printf(_("Fetching %s\n"), name);
1633 if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
1634 error(_("Could not fetch %s"), name);
1635 result = 1;
1636 }
1637 strvec_pop(&argv);
1638 }
1639
1640 strvec_clear(&argv);
1641 return !!result;
1642 }
1643
1644 /*
1645 * Fetching from the promisor remote should use the given filter-spec
1646 * or inherit the default filter-spec from the config.
1647 */
1648 static inline void fetch_one_setup_partial(struct remote *remote)
1649 {
1650 /*
1651 * Explicit --no-filter argument overrides everything, regardless
1652 * of any prior partial clones and fetches.
1653 */
1654 if (filter_options.no_filter)
1655 return;
1656
1657 /*
1658 * If no prior partial clone/fetch and the current fetch DID NOT
1659 * request a partial-fetch, do a normal fetch.
1660 */
1661 if (!has_promisor_remote() && !filter_options.choice)
1662 return;
1663
1664 /*
1665 * If this is a partial-fetch request, we enable partial on
1666 * this repo if not already enabled and remember the given
1667 * filter-spec as the default for subsequent fetches to this
1668 * remote.
1669 */
1670 if (filter_options.choice) {
1671 partial_clone_register(remote->name, &filter_options);
1672 return;
1673 }
1674
1675 /*
1676 * Do a partial-fetch from the promisor remote using either the
1677 * explicitly given filter-spec or inherit the filter-spec from
1678 * the config.
1679 */
1680 if (!filter_options.choice)
1681 partial_clone_get_default_filter_spec(&filter_options, remote->name);
1682 return;
1683 }
1684
1685 static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
1686 {
1687 struct refspec rs = REFSPEC_INIT_FETCH;
1688 int i;
1689 int exit_code;
1690 int maybe_prune_tags;
1691 int remote_via_config = remote_is_configured(remote, 0);
1692
1693 if (!remote)
1694 die(_("No remote repository specified. Please, specify either a URL or a\n"
1695 "remote name from which new revisions should be fetched."));
1696
1697 gtransport = prepare_transport(remote, 1);
1698
1699 if (prune < 0) {
1700 /* no command line request */
1701 if (0 <= remote->prune)
1702 prune = remote->prune;
1703 else if (0 <= fetch_prune_config)
1704 prune = fetch_prune_config;
1705 else
1706 prune = PRUNE_BY_DEFAULT;
1707 }
1708
1709 if (prune_tags < 0) {
1710 /* no command line request */
1711 if (0 <= remote->prune_tags)
1712 prune_tags = remote->prune_tags;
1713 else if (0 <= fetch_prune_tags_config)
1714 prune_tags = fetch_prune_tags_config;
1715 else
1716 prune_tags = PRUNE_TAGS_BY_DEFAULT;
1717 }
1718
1719 maybe_prune_tags = prune_tags_ok && prune_tags;
1720 if (maybe_prune_tags && remote_via_config)
1721 refspec_append(&remote->fetch, TAG_REFSPEC);
1722
1723 if (maybe_prune_tags && (argc || !remote_via_config))
1724 refspec_append(&rs, TAG_REFSPEC);
1725
1726 for (i = 0; i < argc; i++) {
1727 if (!strcmp(argv[i], "tag")) {
1728 char *tag;
1729 i++;
1730 if (i >= argc)
1731 die(_("You need to specify a tag name."));
1732
1733 tag = xstrfmt("refs/tags/%s:refs/tags/%s",
1734 argv[i], argv[i]);
1735 refspec_append(&rs, tag);
1736 free(tag);
1737 } else {
1738 refspec_append(&rs, argv[i]);
1739 }
1740 }
1741
1742 if (server_options.nr)
1743 gtransport->server_options = &server_options;
1744
1745 sigchain_push_common(unlock_pack_on_signal);
1746 atexit(unlock_pack);
1747 sigchain_push(SIGPIPE, SIG_IGN);
1748 exit_code = do_fetch(gtransport, &rs);
1749 sigchain_pop(SIGPIPE);
1750 refspec_clear(&rs);
1751 transport_disconnect(gtransport);
1752 gtransport = NULL;
1753 return exit_code;
1754 }
1755
1756 int cmd_fetch(int argc, const char **argv, const char *prefix)
1757 {
1758 int i;
1759 struct string_list list = STRING_LIST_INIT_DUP;
1760 struct remote *remote = NULL;
1761 int result = 0;
1762 int prune_tags_ok = 1;
1763
1764 packet_trace_identity("fetch");
1765
1766 /* Record the command line for the reflog */
1767 strbuf_addstr(&default_rla, "fetch");
1768 for (i = 1; i < argc; i++) {
1769 /* This handles non-URLs gracefully */
1770 char *anon = transport_anonymize_url(argv[i]);
1771
1772 strbuf_addf(&default_rla, " %s", anon);
1773 free(anon);
1774 }
1775
1776 fetch_config_from_gitmodules(&submodule_fetch_jobs_config,
1777 &recurse_submodules);
1778 git_config(git_fetch_config, NULL);
1779
1780 argc = parse_options(argc, argv, prefix,
1781 builtin_fetch_options, builtin_fetch_usage, 0);
1782
1783 if (deepen_relative) {
1784 if (deepen_relative < 0)
1785 die(_("Negative depth in --deepen is not supported"));
1786 if (depth)
1787 die(_("--deepen and --depth are mutually exclusive"));
1788 depth = xstrfmt("%d", deepen_relative);
1789 }
1790 if (unshallow) {
1791 if (depth)
1792 die(_("--depth and --unshallow cannot be used together"));
1793 else if (!is_repository_shallow(the_repository))
1794 die(_("--unshallow on a complete repository does not make sense"));
1795 else
1796 depth = xstrfmt("%d", INFINITE_DEPTH);
1797 }
1798
1799 /* no need to be strict, transport_set_option() will validate it again */
1800 if (depth && atoi(depth) < 1)
1801 die(_("depth %s is not a positive number"), depth);
1802 if (depth || deepen_since || deepen_not.nr)
1803 deepen = 1;
1804
1805 /* FETCH_HEAD never gets updated in --dry-run mode */
1806 if (dry_run)
1807 write_fetch_head = 0;
1808
1809 if (all) {
1810 if (argc == 1)
1811 die(_("fetch --all does not take a repository argument"));
1812 else if (argc > 1)
1813 die(_("fetch --all does not make sense with refspecs"));
1814 (void) for_each_remote(get_one_remote_for_fetch, &list);
1815 } else if (argc == 0) {
1816 /* No arguments -- use default remote */
1817 remote = remote_get(NULL);
1818 } else if (multiple) {
1819 /* All arguments are assumed to be remotes or groups */
1820 for (i = 0; i < argc; i++)
1821 if (!add_remote_or_group(argv[i], &list))
1822 die(_("No such remote or remote group: %s"), argv[i]);
1823 } else {
1824 /* Single remote or group */
1825 (void) add_remote_or_group(argv[0], &list);
1826 if (list.nr > 1) {
1827 /* More than one remote */
1828 if (argc > 1)
1829 die(_("Fetching a group and specifying refspecs does not make sense"));
1830 } else {
1831 /* Zero or one remotes */
1832 remote = remote_get(argv[0]);
1833 prune_tags_ok = (argc == 1);
1834 argc--;
1835 argv++;
1836 }
1837 }
1838
1839 if (remote) {
1840 if (filter_options.choice || has_promisor_remote())
1841 fetch_one_setup_partial(remote);
1842 result = fetch_one(remote, argc, argv, prune_tags_ok);
1843 } else {
1844 int max_children = max_jobs;
1845
1846 if (filter_options.choice)
1847 die(_("--filter can only be used with the remote "
1848 "configured in extensions.partialclone"));
1849
1850 if (max_children < 0)
1851 max_children = fetch_parallel_config;
1852
1853 /* TODO should this also die if we have a previous partial-clone? */
1854 result = fetch_multiple(&list, max_children);
1855 }
1856
1857 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1858 struct strvec options = STRVEC_INIT;
1859 int max_children = max_jobs;
1860
1861 if (max_children < 0)
1862 max_children = submodule_fetch_jobs_config;
1863 if (max_children < 0)
1864 max_children = fetch_parallel_config;
1865
1866 add_options_to_argv(&options);
1867 result = fetch_populated_submodules(the_repository,
1868 &options,
1869 submodule_prefix,
1870 recurse_submodules,
1871 recurse_submodules_default,
1872 verbosity < 0,
1873 max_children);
1874 strvec_clear(&options);
1875 }
1876
1877 string_list_clear(&list, 0);
1878
1879 prepare_repo_settings(the_repository);
1880 if (fetch_write_commit_graph > 0 ||
1881 (fetch_write_commit_graph < 0 &&
1882 the_repository->settings.fetch_write_commit_graph)) {
1883 int commit_graph_flags = COMMIT_GRAPH_WRITE_SPLIT;
1884
1885 if (progress)
1886 commit_graph_flags |= COMMIT_GRAPH_WRITE_PROGRESS;
1887
1888 write_commit_graph_reachable(the_repository->objects->odb,
1889 commit_graph_flags,
1890 NULL);
1891 }
1892
1893 close_object_store(the_repository->objects);
1894
1895 if (enable_auto_gc)
1896 run_auto_maintenance(verbosity < 0);
1897
1898 return result;
1899 }