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