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