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