1/*
2 * "git fetch"
3 */
4#include "cache.h"
5#include "refs.h"
6#include "commit.h"
7#include "builtin.h"
8#include "string-list.h"
9#include "remote.h"
10#include "transport.h"
11#include "run-command.h"
12#include "parse-options.h"
13#include "sigchain.h"
14#include "submodule-config.h"
15#include "submodule.h"
16#include "connected.h"
17#include "argv-array.h"
18#include "utf8.h"
19
20#define TRANSPORT_SUMMARY(x) \
21 (int)(TRANSPORT_SUMMARY_WIDTH + strlen(x) - gettext_width(x)), (x)
22
23static const char * const builtin_fetch_usage[] = {
24 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
25 N_("git fetch [<options>] <group>"),
26 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
27 N_("git fetch --all [<options>]"),
28 NULL
29};
30
31enum {
32 TAGS_UNSET = 0,
33 TAGS_DEFAULT = 1,
34 TAGS_SET = 2
35};
36
37static int fetch_prune_config = -1; /* unspecified */
38static int prune = -1; /* unspecified */
39#define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
40
41static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
42static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
43static int tags = TAGS_DEFAULT, unshallow, update_shallow;
44static int max_children = -1;
45static enum transport_family family;
46static const char *depth;
47static const char *upload_pack;
48static struct strbuf default_rla = STRBUF_INIT;
49static struct transport *gtransport;
50static struct transport *gsecondary;
51static const char *submodule_prefix = "";
52static const char *recurse_submodules_default;
53static int shown_url = 0;
54static int refmap_alloc, refmap_nr;
55static const char **refmap_array;
56
57static int option_parse_recurse_submodules(const struct option *opt,
58 const char *arg, int unset)
59{
60 if (unset) {
61 recurse_submodules = RECURSE_SUBMODULES_OFF;
62 } else {
63 if (arg)
64 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
65 else
66 recurse_submodules = RECURSE_SUBMODULES_ON;
67 }
68 return 0;
69}
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 return git_default_config(k, v, cb);
78}
79
80static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
81{
82 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
83
84 /*
85 * "git fetch --refmap='' origin foo"
86 * can be used to tell the command not to store anywhere
87 */
88 if (*arg)
89 refmap_array[refmap_nr++] = arg;
90 return 0;
91}
92
93static struct option builtin_fetch_options[] = {
94 OPT__VERBOSITY(&verbosity),
95 OPT_BOOL(0, "all", &all,
96 N_("fetch from all remotes")),
97 OPT_BOOL('a', "append", &append,
98 N_("append to .git/FETCH_HEAD instead of overwriting")),
99 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
100 N_("path to upload pack on remote end")),
101 OPT__FORCE(&force, N_("force overwrite of local branch")),
102 OPT_BOOL('m', "multiple", &multiple,
103 N_("fetch from multiple remotes")),
104 OPT_SET_INT('t', "tags", &tags,
105 N_("fetch all tags and associated objects"), TAGS_SET),
106 OPT_SET_INT('n', NULL, &tags,
107 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
108 OPT_INTEGER('j', "jobs", &max_children,
109 N_("number of submodules fetched in parallel")),
110 OPT_BOOL('p', "prune", &prune,
111 N_("prune remote-tracking branches no longer on remote")),
112 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
113 N_("control recursive fetching of submodules"),
114 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
115 OPT_BOOL(0, "dry-run", &dry_run,
116 N_("dry run")),
117 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
118 OPT_BOOL('u', "update-head-ok", &update_head_ok,
119 N_("allow updating of HEAD ref")),
120 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
121 OPT_STRING(0, "depth", &depth, N_("depth"),
122 N_("deepen history of shallow clone")),
123 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
124 N_("convert to a complete repository"),
125 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
126 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
127 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
128 { OPTION_STRING, 0, "recurse-submodules-default",
129 &recurse_submodules_default, NULL,
130 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
131 OPT_BOOL(0, "update-shallow", &update_shallow,
132 N_("accept refs that update .git/shallow")),
133 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
134 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
135 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
136 TRANSPORT_FAMILY_IPV4),
137 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
138 TRANSPORT_FAMILY_IPV6),
139 OPT_END()
140};
141
142static void unlock_pack(void)
143{
144 if (gtransport)
145 transport_unlock_pack(gtransport);
146 if (gsecondary)
147 transport_unlock_pack(gsecondary);
148}
149
150static void unlock_pack_on_signal(int signo)
151{
152 unlock_pack();
153 sigchain_pop(signo);
154 raise(signo);
155}
156
157static void add_merge_config(struct ref **head,
158 const struct ref *remote_refs,
159 struct branch *branch,
160 struct ref ***tail)
161{
162 int i;
163
164 for (i = 0; i < branch->merge_nr; i++) {
165 struct ref *rm, **old_tail = *tail;
166 struct refspec refspec;
167
168 for (rm = *head; rm; rm = rm->next) {
169 if (branch_merge_matches(branch, i, rm->name)) {
170 rm->fetch_head_status = FETCH_HEAD_MERGE;
171 break;
172 }
173 }
174 if (rm)
175 continue;
176
177 /*
178 * Not fetched to a remote-tracking branch? We need to fetch
179 * it anyway to allow this branch's "branch.$name.merge"
180 * to be honored by 'git pull', but we do not have to
181 * fail if branch.$name.merge is misconfigured to point
182 * at a nonexisting branch. If we were indeed called by
183 * 'git pull', it will notice the misconfiguration because
184 * there is no entry in the resulting FETCH_HEAD marked
185 * for merging.
186 */
187 memset(&refspec, 0, sizeof(refspec));
188 refspec.src = branch->merge[i]->src;
189 get_fetch_map(remote_refs, &refspec, tail, 1);
190 for (rm = *old_tail; rm; rm = rm->next)
191 rm->fetch_head_status = FETCH_HEAD_MERGE;
192 }
193}
194
195static int add_existing(const char *refname, const struct object_id *oid,
196 int flag, void *cbdata)
197{
198 struct string_list *list = (struct string_list *)cbdata;
199 struct string_list_item *item = string_list_insert(list, refname);
200 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
201
202 oidcpy(old_oid, oid);
203 item->util = old_oid;
204 return 0;
205}
206
207static int will_fetch(struct ref **head, const unsigned char *sha1)
208{
209 struct ref *rm = *head;
210 while (rm) {
211 if (!hashcmp(rm->old_oid.hash, sha1))
212 return 1;
213 rm = rm->next;
214 }
215 return 0;
216}
217
218static void find_non_local_tags(struct transport *transport,
219 struct ref **head,
220 struct ref ***tail)
221{
222 struct string_list existing_refs = STRING_LIST_INIT_DUP;
223 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
224 const struct ref *ref;
225 struct string_list_item *item = NULL;
226
227 for_each_ref(add_existing, &existing_refs);
228 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
229 if (!starts_with(ref->name, "refs/tags/"))
230 continue;
231
232 /*
233 * The peeled ref always follows the matching base
234 * ref, so if we see a peeled ref that we don't want
235 * to fetch then we can mark the ref entry in the list
236 * as one to ignore by setting util to NULL.
237 */
238 if (ends_with(ref->name, "^{}")) {
239 if (item && !has_object_file(&ref->old_oid) &&
240 !will_fetch(head, ref->old_oid.hash) &&
241 !has_sha1_file(item->util) &&
242 !will_fetch(head, item->util))
243 item->util = NULL;
244 item = NULL;
245 continue;
246 }
247
248 /*
249 * If item is non-NULL here, then we previously saw a
250 * ref not followed by a peeled reference, so we need
251 * to check if it is a lightweight tag that we want to
252 * fetch.
253 */
254 if (item && !has_sha1_file(item->util) &&
255 !will_fetch(head, item->util))
256 item->util = NULL;
257
258 item = NULL;
259
260 /* skip duplicates and refs that we already have */
261 if (string_list_has_string(&remote_refs, ref->name) ||
262 string_list_has_string(&existing_refs, ref->name))
263 continue;
264
265 item = string_list_insert(&remote_refs, ref->name);
266 item->util = (void *)&ref->old_oid;
267 }
268 string_list_clear(&existing_refs, 1);
269
270 /*
271 * We may have a final lightweight tag that needs to be
272 * checked to see if it needs fetching.
273 */
274 if (item && !has_sha1_file(item->util) &&
275 !will_fetch(head, item->util))
276 item->util = NULL;
277
278 /*
279 * For all the tags in the remote_refs string list,
280 * add them to the list of refs to be fetched
281 */
282 for_each_string_list_item(item, &remote_refs) {
283 /* Unless we have already decided to ignore this item... */
284 if (item->util)
285 {
286 struct ref *rm = alloc_ref(item->string);
287 rm->peer_ref = alloc_ref(item->string);
288 oidcpy(&rm->old_oid, item->util);
289 **tail = rm;
290 *tail = &rm->next;
291 }
292 }
293
294 string_list_clear(&remote_refs, 0);
295}
296
297static struct ref *get_ref_map(struct transport *transport,
298 struct refspec *refspecs, int refspec_count,
299 int tags, int *autotags)
300{
301 int i;
302 struct ref *rm;
303 struct ref *ref_map = NULL;
304 struct ref **tail = &ref_map;
305
306 /* opportunistically-updated references: */
307 struct ref *orefs = NULL, **oref_tail = &orefs;
308
309 const struct ref *remote_refs = transport_get_remote_refs(transport);
310
311 if (refspec_count) {
312 struct refspec *fetch_refspec;
313 int fetch_refspec_nr;
314
315 for (i = 0; i < refspec_count; i++) {
316 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
317 if (refspecs[i].dst && refspecs[i].dst[0])
318 *autotags = 1;
319 }
320 /* Merge everything on the command line (but not --tags) */
321 for (rm = ref_map; rm; rm = rm->next)
322 rm->fetch_head_status = FETCH_HEAD_MERGE;
323
324 /*
325 * For any refs that we happen to be fetching via
326 * command-line arguments, the destination ref might
327 * have been missing or have been different than the
328 * remote-tracking ref that would be derived from the
329 * configured refspec. In these cases, we want to
330 * take the opportunity to update their configured
331 * remote-tracking reference. However, we do not want
332 * to mention these entries in FETCH_HEAD at all, as
333 * they would simply be duplicates of existing
334 * entries, so we set them FETCH_HEAD_IGNORE below.
335 *
336 * We compute these entries now, based only on the
337 * refspecs specified on the command line. But we add
338 * them to the list following the refspecs resulting
339 * from the tags option so that one of the latter,
340 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
341 * by ref_remove_duplicates() in favor of one of these
342 * opportunistic entries with FETCH_HEAD_IGNORE.
343 */
344 if (refmap_array) {
345 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
346 fetch_refspec_nr = refmap_nr;
347 } else {
348 fetch_refspec = transport->remote->fetch;
349 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
350 }
351
352 for (i = 0; i < fetch_refspec_nr; i++)
353 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
354
355 if (tags == TAGS_SET)
356 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
357 } else if (refmap_array) {
358 die("--refmap option is only meaningful with command-line refspec(s).");
359 } else {
360 /* Use the defaults */
361 struct remote *remote = transport->remote;
362 struct branch *branch = branch_get(NULL);
363 int has_merge = branch_has_merge_config(branch);
364 if (remote &&
365 (remote->fetch_refspec_nr ||
366 /* Note: has_merge implies non-NULL branch->remote_name */
367 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
368 for (i = 0; i < remote->fetch_refspec_nr; i++) {
369 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
370 if (remote->fetch[i].dst &&
371 remote->fetch[i].dst[0])
372 *autotags = 1;
373 if (!i && !has_merge && ref_map &&
374 !remote->fetch[0].pattern)
375 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
376 }
377 /*
378 * if the remote we're fetching from is the same
379 * as given in branch.<name>.remote, we add the
380 * ref given in branch.<name>.merge, too.
381 *
382 * Note: has_merge implies non-NULL branch->remote_name
383 */
384 if (has_merge &&
385 !strcmp(branch->remote_name, remote->name))
386 add_merge_config(&ref_map, remote_refs, branch, &tail);
387 } else {
388 ref_map = get_remote_ref(remote_refs, "HEAD");
389 if (!ref_map)
390 die(_("Couldn't find remote ref HEAD"));
391 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
392 tail = &ref_map->next;
393 }
394 }
395
396 if (tags == TAGS_SET)
397 /* also fetch all tags */
398 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
399 else if (tags == TAGS_DEFAULT && *autotags)
400 find_non_local_tags(transport, &ref_map, &tail);
401
402 /* Now append any refs to be updated opportunistically: */
403 *tail = orefs;
404 for (rm = orefs; rm; rm = rm->next) {
405 rm->fetch_head_status = FETCH_HEAD_IGNORE;
406 tail = &rm->next;
407 }
408
409 return ref_remove_duplicates(ref_map);
410}
411
412#define STORE_REF_ERROR_OTHER 1
413#define STORE_REF_ERROR_DF_CONFLICT 2
414
415static int s_update_ref(const char *action,
416 struct ref *ref,
417 int check_old)
418{
419 char msg[1024];
420 char *rla = getenv("GIT_REFLOG_ACTION");
421 struct ref_transaction *transaction;
422 struct strbuf err = STRBUF_INIT;
423 int ret, df_conflict = 0;
424
425 if (dry_run)
426 return 0;
427 if (!rla)
428 rla = default_rla.buf;
429 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
430
431 transaction = ref_transaction_begin(&err);
432 if (!transaction ||
433 ref_transaction_update(transaction, ref->name,
434 ref->new_oid.hash,
435 check_old ? ref->old_oid.hash : NULL,
436 0, msg, &err))
437 goto fail;
438
439 ret = ref_transaction_commit(transaction, &err);
440 if (ret) {
441 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
442 goto fail;
443 }
444
445 ref_transaction_free(transaction);
446 strbuf_release(&err);
447 return 0;
448fail:
449 ref_transaction_free(transaction);
450 error("%s", err.buf);
451 strbuf_release(&err);
452 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
453 : STORE_REF_ERROR_OTHER;
454}
455
456static int refcol_width = 10;
457static int compact_format;
458
459static void adjust_refcol_width(const struct ref *ref)
460{
461 int max, rlen, llen, len;
462
463 /* uptodate lines are only shown on high verbosity level */
464 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
465 return;
466
467 max = term_columns();
468 rlen = utf8_strwidth(prettify_refname(ref->name));
469
470 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
471
472 /*
473 * rough estimation to see if the output line is too long and
474 * should not be counted (we can't do precise calculation
475 * anyway because we don't know if the error explanation part
476 * will be printed in update_local_ref)
477 */
478 if (compact_format) {
479 llen = 0;
480 max = max * 2 / 3;
481 }
482 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
483 if (len >= max)
484 return;
485
486 /*
487 * Not precise calculation for compact mode because '*' can
488 * appear on the left hand side of '->' and shrink the column
489 * back.
490 */
491 if (refcol_width < rlen)
492 refcol_width = rlen;
493}
494
495static void prepare_format_display(struct ref *ref_map)
496{
497 struct ref *rm;
498 const char *format = "full";
499
500 git_config_get_string_const("fetch.output", &format);
501 if (!strcasecmp(format, "full"))
502 compact_format = 0;
503 else if (!strcasecmp(format, "compact"))
504 compact_format = 1;
505 else
506 die(_("configuration fetch.output contains invalid value %s"),
507 format);
508
509 for (rm = ref_map; rm; rm = rm->next) {
510 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
511 !rm->peer_ref ||
512 !strcmp(rm->name, "HEAD"))
513 continue;
514
515 adjust_refcol_width(rm);
516 }
517}
518
519static void print_remote_to_local(struct strbuf *display,
520 const char *remote, const char *local)
521{
522 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
523}
524
525static int find_and_replace(struct strbuf *haystack,
526 const char *needle,
527 const char *placeholder)
528{
529 const char *p = strstr(haystack->buf, needle);
530 int plen, nlen;
531
532 if (!p)
533 return 0;
534
535 if (p > haystack->buf && p[-1] != '/')
536 return 0;
537
538 plen = strlen(p);
539 nlen = strlen(needle);
540 if (plen > nlen && p[nlen] != '/')
541 return 0;
542
543 strbuf_splice(haystack, p - haystack->buf, nlen,
544 placeholder, strlen(placeholder));
545 return 1;
546}
547
548static void print_compact(struct strbuf *display,
549 const char *remote, const char *local)
550{
551 struct strbuf r = STRBUF_INIT;
552 struct strbuf l = STRBUF_INIT;
553
554 if (!strcmp(remote, local)) {
555 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
556 return;
557 }
558
559 strbuf_addstr(&r, remote);
560 strbuf_addstr(&l, local);
561
562 if (!find_and_replace(&r, local, "*"))
563 find_and_replace(&l, remote, "*");
564 print_remote_to_local(display, r.buf, l.buf);
565
566 strbuf_release(&r);
567 strbuf_release(&l);
568}
569
570static void format_display(struct strbuf *display, char code,
571 const char *summary, const char *error,
572 const char *remote, const char *local)
573{
574 strbuf_addf(display, "%c %-*s ", code, TRANSPORT_SUMMARY(summary));
575 if (!compact_format)
576 print_remote_to_local(display, remote, local);
577 else
578 print_compact(display, remote, local);
579 if (error)
580 strbuf_addf(display, " (%s)", error);
581}
582
583static int update_local_ref(struct ref *ref,
584 const char *remote,
585 const struct ref *remote_ref,
586 struct strbuf *display)
587{
588 struct commit *current = NULL, *updated;
589 enum object_type type;
590 struct branch *current_branch = branch_get(NULL);
591 const char *pretty_ref = prettify_refname(ref->name);
592
593 type = sha1_object_info(ref->new_oid.hash, NULL);
594 if (type < 0)
595 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
596
597 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
598 if (verbosity > 0)
599 format_display(display, '=', _("[up to date]"), NULL,
600 remote, pretty_ref);
601 return 0;
602 }
603
604 if (current_branch &&
605 !strcmp(ref->name, current_branch->name) &&
606 !(update_head_ok || is_bare_repository()) &&
607 !is_null_oid(&ref->old_oid)) {
608 /*
609 * If this is the head, and it's not okay to update
610 * the head, and the old value of the head isn't empty...
611 */
612 format_display(display, '!', _("[rejected]"),
613 _("can't fetch in current branch"),
614 remote, pretty_ref);
615 return 1;
616 }
617
618 if (!is_null_oid(&ref->old_oid) &&
619 starts_with(ref->name, "refs/tags/")) {
620 int r;
621 r = s_update_ref("updating tag", ref, 0);
622 format_display(display, r ? '!' : 't', _("[tag update]"),
623 r ? _("unable to update local ref") : NULL,
624 remote, pretty_ref);
625 return r;
626 }
627
628 current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
629 updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
630 if (!current || !updated) {
631 const char *msg;
632 const char *what;
633 int r;
634 /*
635 * Nicely describe the new ref we're fetching.
636 * Base this on the remote's ref name, as it's
637 * more likely to follow a standard layout.
638 */
639 const char *name = remote_ref ? remote_ref->name : "";
640 if (starts_with(name, "refs/tags/")) {
641 msg = "storing tag";
642 what = _("[new tag]");
643 } else if (starts_with(name, "refs/heads/")) {
644 msg = "storing head";
645 what = _("[new branch]");
646 } else {
647 msg = "storing ref";
648 what = _("[new ref]");
649 }
650
651 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
652 (recurse_submodules != RECURSE_SUBMODULES_ON))
653 check_for_new_submodule_commits(ref->new_oid.hash);
654 r = s_update_ref(msg, ref, 0);
655 format_display(display, r ? '!' : '*', what,
656 r ? _("unable to update local ref") : NULL,
657 remote, pretty_ref);
658 return r;
659 }
660
661 if (in_merge_bases(current, updated)) {
662 struct strbuf quickref = STRBUF_INIT;
663 int r;
664 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
665 strbuf_addstr(&quickref, "..");
666 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
667 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
668 (recurse_submodules != RECURSE_SUBMODULES_ON))
669 check_for_new_submodule_commits(ref->new_oid.hash);
670 r = s_update_ref("fast-forward", ref, 1);
671 format_display(display, r ? '!' : ' ', quickref.buf,
672 r ? _("unable to update local ref") : NULL,
673 remote, pretty_ref);
674 strbuf_release(&quickref);
675 return r;
676 } else if (force || ref->force) {
677 struct strbuf quickref = STRBUF_INIT;
678 int r;
679 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
680 strbuf_addstr(&quickref, "...");
681 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
682 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
683 (recurse_submodules != RECURSE_SUBMODULES_ON))
684 check_for_new_submodule_commits(ref->new_oid.hash);
685 r = s_update_ref("forced-update", ref, 1);
686 format_display(display, r ? '!' : '+', quickref.buf,
687 r ? _("unable to update local ref") : _("forced update"),
688 remote, pretty_ref);
689 strbuf_release(&quickref);
690 return r;
691 } else {
692 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
693 remote, pretty_ref);
694 return 1;
695 }
696}
697
698static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
699{
700 struct ref **rm = cb_data;
701 struct ref *ref = *rm;
702
703 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
704 ref = ref->next;
705 if (!ref)
706 return -1; /* end of the list */
707 *rm = ref->next;
708 hashcpy(sha1, ref->old_oid.hash);
709 return 0;
710}
711
712static int store_updated_refs(const char *raw_url, const char *remote_name,
713 struct ref *ref_map)
714{
715 FILE *fp;
716 struct commit *commit;
717 int url_len, i, rc = 0;
718 struct strbuf note = STRBUF_INIT;
719 const char *what, *kind;
720 struct ref *rm;
721 char *url;
722 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
723 int want_status;
724
725 fp = fopen(filename, "a");
726 if (!fp)
727 return error_errno(_("cannot open %s"), filename);
728
729 if (raw_url)
730 url = transport_anonymize_url(raw_url);
731 else
732 url = xstrdup("foreign");
733
734 rm = ref_map;
735 if (check_connected(iterate_ref_map, &rm, NULL)) {
736 rc = error(_("%s did not send all necessary objects\n"), url);
737 goto abort;
738 }
739
740 prepare_format_display(ref_map);
741
742 /*
743 * We do a pass for each fetch_head_status type in their enum order, so
744 * merged entries are written before not-for-merge. That lets readers
745 * use FETCH_HEAD as a refname to refer to the ref to be merged.
746 */
747 for (want_status = FETCH_HEAD_MERGE;
748 want_status <= FETCH_HEAD_IGNORE;
749 want_status++) {
750 for (rm = ref_map; rm; rm = rm->next) {
751 struct ref *ref = NULL;
752 const char *merge_status_marker = "";
753
754 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
755 if (want_status == FETCH_HEAD_MERGE)
756 warning(_("reject %s because shallow roots are not allowed to be updated"),
757 rm->peer_ref ? rm->peer_ref->name : rm->name);
758 continue;
759 }
760
761 commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
762 if (!commit)
763 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
764
765 if (rm->fetch_head_status != want_status)
766 continue;
767
768 if (rm->peer_ref) {
769 ref = alloc_ref(rm->peer_ref->name);
770 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
771 oidcpy(&ref->new_oid, &rm->old_oid);
772 ref->force = rm->peer_ref->force;
773 }
774
775
776 if (!strcmp(rm->name, "HEAD")) {
777 kind = "";
778 what = "";
779 }
780 else if (starts_with(rm->name, "refs/heads/")) {
781 kind = "branch";
782 what = rm->name + 11;
783 }
784 else if (starts_with(rm->name, "refs/tags/")) {
785 kind = "tag";
786 what = rm->name + 10;
787 }
788 else if (starts_with(rm->name, "refs/remotes/")) {
789 kind = "remote-tracking branch";
790 what = rm->name + 13;
791 }
792 else {
793 kind = "";
794 what = rm->name;
795 }
796
797 url_len = strlen(url);
798 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
799 ;
800 url_len = i + 1;
801 if (4 < i && !strncmp(".git", url + i - 3, 4))
802 url_len = i - 3;
803
804 strbuf_reset(¬e);
805 if (*what) {
806 if (*kind)
807 strbuf_addf(¬e, "%s ", kind);
808 strbuf_addf(¬e, "'%s' of ", what);
809 }
810 switch (rm->fetch_head_status) {
811 case FETCH_HEAD_NOT_FOR_MERGE:
812 merge_status_marker = "not-for-merge";
813 /* fall-through */
814 case FETCH_HEAD_MERGE:
815 fprintf(fp, "%s\t%s\t%s",
816 oid_to_hex(&rm->old_oid),
817 merge_status_marker,
818 note.buf);
819 for (i = 0; i < url_len; ++i)
820 if ('\n' == url[i])
821 fputs("\\n", fp);
822 else
823 fputc(url[i], fp);
824 fputc('\n', fp);
825 break;
826 default:
827 /* do not write anything to FETCH_HEAD */
828 break;
829 }
830
831 strbuf_reset(¬e);
832 if (ref) {
833 rc |= update_local_ref(ref, what, rm, ¬e);
834 free(ref);
835 } else
836 format_display(¬e, '*',
837 *kind ? kind : "branch", NULL,
838 *what ? what : "HEAD",
839 "FETCH_HEAD");
840 if (note.len) {
841 if (verbosity >= 0 && !shown_url) {
842 fprintf(stderr, _("From %.*s\n"),
843 url_len, url);
844 shown_url = 1;
845 }
846 if (verbosity >= 0)
847 fprintf(stderr, " %s\n", note.buf);
848 }
849 }
850 }
851
852 if (rc & STORE_REF_ERROR_DF_CONFLICT)
853 error(_("some local refs could not be updated; try running\n"
854 " 'git remote prune %s' to remove any old, conflicting "
855 "branches"), remote_name);
856
857 abort:
858 strbuf_release(¬e);
859 free(url);
860 fclose(fp);
861 return rc;
862}
863
864/*
865 * We would want to bypass the object transfer altogether if
866 * everything we are going to fetch already exists and is connected
867 * locally.
868 */
869static int quickfetch(struct ref *ref_map)
870{
871 struct ref *rm = ref_map;
872 struct check_connected_options opt = CHECK_CONNECTED_INIT;
873
874 /*
875 * If we are deepening a shallow clone we already have these
876 * objects reachable. Running rev-list here will return with
877 * a good (0) exit status and we'll bypass the fetch that we
878 * really need to perform. Claiming failure now will ensure
879 * we perform the network exchange to deepen our history.
880 */
881 if (depth)
882 return -1;
883 opt.quiet = 1;
884 return check_connected(iterate_ref_map, &rm, &opt);
885}
886
887static int fetch_refs(struct transport *transport, struct ref *ref_map)
888{
889 int ret = quickfetch(ref_map);
890 if (ret)
891 ret = transport_fetch_refs(transport, ref_map);
892 if (!ret)
893 ret |= store_updated_refs(transport->url,
894 transport->remote->name,
895 ref_map);
896 transport_unlock_pack(transport);
897 return ret;
898}
899
900static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
901 const char *raw_url)
902{
903 int url_len, i, result = 0;
904 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
905 char *url;
906 const char *dangling_msg = dry_run
907 ? _(" (%s will become dangling)")
908 : _(" (%s has become dangling)");
909
910 if (raw_url)
911 url = transport_anonymize_url(raw_url);
912 else
913 url = xstrdup("foreign");
914
915 url_len = strlen(url);
916 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
917 ;
918
919 url_len = i + 1;
920 if (4 < i && !strncmp(".git", url + i - 3, 4))
921 url_len = i - 3;
922
923 if (!dry_run) {
924 struct string_list refnames = STRING_LIST_INIT_NODUP;
925
926 for (ref = stale_refs; ref; ref = ref->next)
927 string_list_append(&refnames, ref->name);
928
929 result = delete_refs(&refnames, 0);
930 string_list_clear(&refnames, 0);
931 }
932
933 if (verbosity >= 0) {
934 for (ref = stale_refs; ref; ref = ref->next) {
935 struct strbuf sb = STRBUF_INIT;
936 if (!shown_url) {
937 fprintf(stderr, _("From %.*s\n"), url_len, url);
938 shown_url = 1;
939 }
940 format_display(&sb, '-', _("[deleted]"), NULL,
941 _("(none)"), prettify_refname(ref->name));
942 fprintf(stderr, " %s\n",sb.buf);
943 strbuf_release(&sb);
944 warn_dangling_symref(stderr, dangling_msg, ref->name);
945 }
946 }
947
948 free(url);
949 free_refs(stale_refs);
950 return result;
951}
952
953static void check_not_current_branch(struct ref *ref_map)
954{
955 struct branch *current_branch = branch_get(NULL);
956
957 if (is_bare_repository() || !current_branch)
958 return;
959
960 for (; ref_map; ref_map = ref_map->next)
961 if (ref_map->peer_ref && !strcmp(current_branch->refname,
962 ref_map->peer_ref->name))
963 die(_("Refusing to fetch into current branch %s "
964 "of non-bare repository"), current_branch->refname);
965}
966
967static int truncate_fetch_head(void)
968{
969 const char *filename = git_path_fetch_head();
970 FILE *fp = fopen_for_writing(filename);
971
972 if (!fp)
973 return error_errno(_("cannot open %s"), filename);
974 fclose(fp);
975 return 0;
976}
977
978static void set_option(struct transport *transport, const char *name, const char *value)
979{
980 int r = transport_set_option(transport, name, value);
981 if (r < 0)
982 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
983 name, value, transport->url);
984 if (r > 0)
985 warning(_("Option \"%s\" is ignored for %s\n"),
986 name, transport->url);
987}
988
989static struct transport *prepare_transport(struct remote *remote)
990{
991 struct transport *transport;
992 transport = transport_get(remote, NULL);
993 transport_set_verbosity(transport, verbosity, progress);
994 transport->family = family;
995 if (upload_pack)
996 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
997 if (keep)
998 set_option(transport, TRANS_OPT_KEEP, "yes");
999 if (depth)
1000 set_option(transport, TRANS_OPT_DEPTH, depth);
1001 if (update_shallow)
1002 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1003 return transport;
1004}
1005
1006static void backfill_tags(struct transport *transport, struct ref *ref_map)
1007{
1008 if (transport->cannot_reuse) {
1009 gsecondary = prepare_transport(transport->remote);
1010 transport = gsecondary;
1011 }
1012
1013 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1014 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1015 fetch_refs(transport, ref_map);
1016
1017 if (gsecondary) {
1018 transport_disconnect(gsecondary);
1019 gsecondary = NULL;
1020 }
1021}
1022
1023static int do_fetch(struct transport *transport,
1024 struct refspec *refs, int ref_count)
1025{
1026 struct string_list existing_refs = STRING_LIST_INIT_DUP;
1027 struct ref *ref_map;
1028 struct ref *rm;
1029 int autotags = (transport->remote->fetch_tags == 1);
1030 int retcode = 0;
1031
1032 for_each_ref(add_existing, &existing_refs);
1033
1034 if (tags == TAGS_DEFAULT) {
1035 if (transport->remote->fetch_tags == 2)
1036 tags = TAGS_SET;
1037 if (transport->remote->fetch_tags == -1)
1038 tags = TAGS_UNSET;
1039 }
1040
1041 if (!transport->get_refs_list || !transport->fetch)
1042 die(_("Don't know how to fetch from %s"), transport->url);
1043
1044 /* if not appending, truncate FETCH_HEAD */
1045 if (!append && !dry_run) {
1046 retcode = truncate_fetch_head();
1047 if (retcode)
1048 goto cleanup;
1049 }
1050
1051 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1052 if (!update_head_ok)
1053 check_not_current_branch(ref_map);
1054
1055 for (rm = ref_map; rm; rm = rm->next) {
1056 if (rm->peer_ref) {
1057 struct string_list_item *peer_item =
1058 string_list_lookup(&existing_refs,
1059 rm->peer_ref->name);
1060 if (peer_item) {
1061 struct object_id *old_oid = peer_item->util;
1062 oidcpy(&rm->peer_ref->old_oid, old_oid);
1063 }
1064 }
1065 }
1066
1067 if (tags == TAGS_DEFAULT && autotags)
1068 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1069 if (prune) {
1070 /*
1071 * We only prune based on refspecs specified
1072 * explicitly (via command line or configuration); we
1073 * don't care whether --tags was specified.
1074 */
1075 if (ref_count) {
1076 prune_refs(refs, ref_count, ref_map, transport->url);
1077 } else {
1078 prune_refs(transport->remote->fetch,
1079 transport->remote->fetch_refspec_nr,
1080 ref_map,
1081 transport->url);
1082 }
1083 }
1084 if (fetch_refs(transport, ref_map)) {
1085 free_refs(ref_map);
1086 retcode = 1;
1087 goto cleanup;
1088 }
1089 free_refs(ref_map);
1090
1091 /* if neither --no-tags nor --tags was specified, do automated tag
1092 * following ... */
1093 if (tags == TAGS_DEFAULT && autotags) {
1094 struct ref **tail = &ref_map;
1095 ref_map = NULL;
1096 find_non_local_tags(transport, &ref_map, &tail);
1097 if (ref_map)
1098 backfill_tags(transport, ref_map);
1099 free_refs(ref_map);
1100 }
1101
1102 cleanup:
1103 string_list_clear(&existing_refs, 1);
1104 return retcode;
1105}
1106
1107static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1108{
1109 struct string_list *list = priv;
1110 if (!remote->skip_default_update)
1111 string_list_append(list, remote->name);
1112 return 0;
1113}
1114
1115struct remote_group_data {
1116 const char *name;
1117 struct string_list *list;
1118};
1119
1120static int get_remote_group(const char *key, const char *value, void *priv)
1121{
1122 struct remote_group_data *g = priv;
1123
1124 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1125 /* split list by white space */
1126 while (*value) {
1127 size_t wordlen = strcspn(value, " \t\n");
1128
1129 if (wordlen >= 1)
1130 string_list_append_nodup(g->list,
1131 xstrndup(value, wordlen));
1132 value += wordlen + (value[wordlen] != '\0');
1133 }
1134 }
1135
1136 return 0;
1137}
1138
1139static int add_remote_or_group(const char *name, struct string_list *list)
1140{
1141 int prev_nr = list->nr;
1142 struct remote_group_data g;
1143 g.name = name; g.list = list;
1144
1145 git_config(get_remote_group, &g);
1146 if (list->nr == prev_nr) {
1147 struct remote *remote = remote_get(name);
1148 if (!remote_is_configured(remote))
1149 return 0;
1150 string_list_append(list, remote->name);
1151 }
1152 return 1;
1153}
1154
1155static void add_options_to_argv(struct argv_array *argv)
1156{
1157 if (dry_run)
1158 argv_array_push(argv, "--dry-run");
1159 if (prune != -1)
1160 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1161 if (update_head_ok)
1162 argv_array_push(argv, "--update-head-ok");
1163 if (force)
1164 argv_array_push(argv, "--force");
1165 if (keep)
1166 argv_array_push(argv, "--keep");
1167 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1168 argv_array_push(argv, "--recurse-submodules");
1169 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1170 argv_array_push(argv, "--recurse-submodules=on-demand");
1171 if (tags == TAGS_SET)
1172 argv_array_push(argv, "--tags");
1173 else if (tags == TAGS_UNSET)
1174 argv_array_push(argv, "--no-tags");
1175 if (verbosity >= 2)
1176 argv_array_push(argv, "-v");
1177 if (verbosity >= 1)
1178 argv_array_push(argv, "-v");
1179 else if (verbosity < 0)
1180 argv_array_push(argv, "-q");
1181
1182}
1183
1184static int fetch_multiple(struct string_list *list)
1185{
1186 int i, result = 0;
1187 struct argv_array argv = ARGV_ARRAY_INIT;
1188
1189 if (!append && !dry_run) {
1190 int errcode = truncate_fetch_head();
1191 if (errcode)
1192 return errcode;
1193 }
1194
1195 argv_array_pushl(&argv, "fetch", "--append", NULL);
1196 add_options_to_argv(&argv);
1197
1198 for (i = 0; i < list->nr; i++) {
1199 const char *name = list->items[i].string;
1200 argv_array_push(&argv, name);
1201 if (verbosity >= 0)
1202 printf(_("Fetching %s\n"), name);
1203 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1204 error(_("Could not fetch %s"), name);
1205 result = 1;
1206 }
1207 argv_array_pop(&argv);
1208 }
1209
1210 argv_array_clear(&argv);
1211 return result;
1212}
1213
1214static int fetch_one(struct remote *remote, int argc, const char **argv)
1215{
1216 static const char **refs = NULL;
1217 struct refspec *refspec;
1218 int ref_nr = 0;
1219 int exit_code;
1220
1221 if (!remote)
1222 die(_("No remote repository specified. Please, specify either a URL or a\n"
1223 "remote name from which new revisions should be fetched."));
1224
1225 gtransport = prepare_transport(remote);
1226
1227 if (prune < 0) {
1228 /* no command line request */
1229 if (0 <= gtransport->remote->prune)
1230 prune = gtransport->remote->prune;
1231 else if (0 <= fetch_prune_config)
1232 prune = fetch_prune_config;
1233 else
1234 prune = PRUNE_BY_DEFAULT;
1235 }
1236
1237 if (argc > 0) {
1238 int j = 0;
1239 int i;
1240 refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1241 for (i = 0; i < argc; i++) {
1242 if (!strcmp(argv[i], "tag")) {
1243 i++;
1244 if (i >= argc)
1245 die(_("You need to specify a tag name."));
1246 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1247 argv[i], argv[i]);
1248 } else
1249 refs[j++] = argv[i];
1250 }
1251 refs[j] = NULL;
1252 ref_nr = j;
1253 }
1254
1255 sigchain_push_common(unlock_pack_on_signal);
1256 atexit(unlock_pack);
1257 refspec = parse_fetch_refspec(ref_nr, refs);
1258 exit_code = do_fetch(gtransport, refspec, ref_nr);
1259 free_refspec(ref_nr, refspec);
1260 transport_disconnect(gtransport);
1261 gtransport = NULL;
1262 return exit_code;
1263}
1264
1265int cmd_fetch(int argc, const char **argv, const char *prefix)
1266{
1267 int i;
1268 struct string_list list = STRING_LIST_INIT_DUP;
1269 struct remote *remote;
1270 int result = 0;
1271 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1272
1273 packet_trace_identity("fetch");
1274
1275 /* Record the command line for the reflog */
1276 strbuf_addstr(&default_rla, "fetch");
1277 for (i = 1; i < argc; i++)
1278 strbuf_addf(&default_rla, " %s", argv[i]);
1279
1280 git_config(git_fetch_config, NULL);
1281
1282 argc = parse_options(argc, argv, prefix,
1283 builtin_fetch_options, builtin_fetch_usage, 0);
1284
1285 if (unshallow) {
1286 if (depth)
1287 die(_("--depth and --unshallow cannot be used together"));
1288 else if (!is_repository_shallow())
1289 die(_("--unshallow on a complete repository does not make sense"));
1290 else
1291 depth = xstrfmt("%d", INFINITE_DEPTH);
1292 }
1293
1294 /* no need to be strict, transport_set_option() will validate it again */
1295 if (depth && atoi(depth) < 1)
1296 die(_("depth %s is not a positive number"), depth);
1297
1298 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1299 if (recurse_submodules_default) {
1300 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1301 set_config_fetch_recurse_submodules(arg);
1302 }
1303 gitmodules_config();
1304 git_config(submodule_config, NULL);
1305 }
1306
1307 if (all) {
1308 if (argc == 1)
1309 die(_("fetch --all does not take a repository argument"));
1310 else if (argc > 1)
1311 die(_("fetch --all does not make sense with refspecs"));
1312 (void) for_each_remote(get_one_remote_for_fetch, &list);
1313 result = fetch_multiple(&list);
1314 } else if (argc == 0) {
1315 /* No arguments -- use default remote */
1316 remote = remote_get(NULL);
1317 result = fetch_one(remote, argc, argv);
1318 } else if (multiple) {
1319 /* All arguments are assumed to be remotes or groups */
1320 for (i = 0; i < argc; i++)
1321 if (!add_remote_or_group(argv[i], &list))
1322 die(_("No such remote or remote group: %s"), argv[i]);
1323 result = fetch_multiple(&list);
1324 } else {
1325 /* Single remote or group */
1326 (void) add_remote_or_group(argv[0], &list);
1327 if (list.nr > 1) {
1328 /* More than one remote */
1329 if (argc > 1)
1330 die(_("Fetching a group and specifying refspecs does not make sense"));
1331 result = fetch_multiple(&list);
1332 } else {
1333 /* Zero or one remotes */
1334 remote = remote_get(argv[0]);
1335 result = fetch_one(remote, argc-1, argv+1);
1336 }
1337 }
1338
1339 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1340 struct argv_array options = ARGV_ARRAY_INIT;
1341
1342 add_options_to_argv(&options);
1343 result = fetch_populated_submodules(&options,
1344 submodule_prefix,
1345 recurse_submodules,
1346 verbosity < 0,
1347 max_children);
1348 argv_array_clear(&options);
1349 }
1350
1351 string_list_clear(&list, 0);
1352
1353 close_all_packs();
1354
1355 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1356 if (verbosity < 0)
1357 argv_array_push(&argv_gc_auto, "--quiet");
1358 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1359 argv_array_clear(&argv_gc_auto);
1360
1361 return result;
1362}