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