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