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