Merge branch 'rs/describe-unique-abbrev' into maint
[git.git] / builtin / fetch.c
blob7bbcd26faf1fe650ccc7dbbd526db5114aac0c8f
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "repository.h"
7 #include "refs.h"
8 #include "commit.h"
9 #include "builtin.h"
10 #include "string-list.h"
11 #include "remote.h"
12 #include "transport.h"
13 #include "run-command.h"
14 #include "parse-options.h"
15 #include "sigchain.h"
16 #include "submodule-config.h"
17 #include "submodule.h"
18 #include "connected.h"
19 #include "argv-array.h"
20 #include "utf8.h"
21 #include "packfile.h"
23 static 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
31 enum {
32 TAGS_UNSET = 0,
33 TAGS_DEFAULT = 1,
34 TAGS_SET = 2
37 static int fetch_prune_config = -1; /* unspecified */
38 static int prune = -1; /* unspecified */
39 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
41 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
42 static int progress = -1;
43 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
44 static int max_children = 1;
45 static enum transport_family family;
46 static const char *depth;
47 static const char *deepen_since;
48 static const char *upload_pack;
49 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
50 static struct strbuf default_rla = STRBUF_INIT;
51 static struct transport *gtransport;
52 static struct transport *gsecondary;
53 static const char *submodule_prefix = "";
54 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
55 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
56 static int shown_url = 0;
57 static int refmap_alloc, refmap_nr;
58 static const char **refmap_array;
60 static int git_fetch_config(const char *k, const char *v, void *cb)
62 if (!strcmp(k, "fetch.prune")) {
63 fetch_prune_config = git_config_bool(k, v);
64 return 0;
67 if (!strcmp(k, "submodule.recurse")) {
68 int r = git_config_bool(k, v) ?
69 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
70 recurse_submodules = r;
73 if (!strcmp(k, "submodule.fetchjobs")) {
74 max_children = parse_submodule_fetchjobs(k, v);
75 return 0;
76 } else if (!strcmp(k, "fetch.recursesubmodules")) {
77 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
78 return 0;
81 return git_default_config(k, v, cb);
84 static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
86 if (!strcmp(var, "submodule.fetchjobs")) {
87 max_children = parse_submodule_fetchjobs(var, value);
88 return 0;
89 } else if (!strcmp(var, "fetch.recursesubmodules")) {
90 recurse_submodules = parse_fetch_recurse_submodules_arg(var, value);
91 return 0;
94 return 0;
97 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
99 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
102 * "git fetch --refmap='' origin foo"
103 * can be used to tell the command not to store anywhere
105 if (*arg)
106 refmap_array[refmap_nr++] = arg;
107 return 0;
110 static 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 branch")),
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 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
130 N_("control recursive fetching of submodules"),
131 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
132 OPT_BOOL(0, "dry-run", &dry_run,
133 N_("dry run")),
134 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
135 OPT_BOOL('u', "update-head-ok", &update_head_ok,
136 N_("allow updating of HEAD ref")),
137 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
138 OPT_STRING(0, "depth", &depth, N_("depth"),
139 N_("deepen history of shallow clone")),
140 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
141 N_("deepen history of shallow repository based on time")),
142 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
143 N_("deepen history of shallow clone, excluding rev")),
144 OPT_INTEGER(0, "deepen", &deepen_relative,
145 N_("deepen history of shallow clone")),
146 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
147 N_("convert to a complete repository"),
148 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
149 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
150 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
151 { OPTION_CALLBACK, 0, "recurse-submodules-default",
152 &recurse_submodules_default, N_("on-demand"),
153 N_("default for recursive fetching of submodules "
154 "(lower priority than config files)"),
155 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
156 OPT_BOOL(0, "update-shallow", &update_shallow,
157 N_("accept refs that update .git/shallow")),
158 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
159 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
160 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
161 TRANSPORT_FAMILY_IPV4),
162 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
163 TRANSPORT_FAMILY_IPV6),
164 OPT_END()
167 static void unlock_pack(void)
169 if (gtransport)
170 transport_unlock_pack(gtransport);
171 if (gsecondary)
172 transport_unlock_pack(gsecondary);
175 static void unlock_pack_on_signal(int signo)
177 unlock_pack();
178 sigchain_pop(signo);
179 raise(signo);
182 static void add_merge_config(struct ref **head,
183 const struct ref *remote_refs,
184 struct branch *branch,
185 struct ref ***tail)
187 int i;
189 for (i = 0; i < branch->merge_nr; i++) {
190 struct ref *rm, **old_tail = *tail;
191 struct refspec refspec;
193 for (rm = *head; rm; rm = rm->next) {
194 if (branch_merge_matches(branch, i, rm->name)) {
195 rm->fetch_head_status = FETCH_HEAD_MERGE;
196 break;
199 if (rm)
200 continue;
203 * Not fetched to a remote-tracking branch? We need to fetch
204 * it anyway to allow this branch's "branch.$name.merge"
205 * to be honored by 'git pull', but we do not have to
206 * fail if branch.$name.merge is misconfigured to point
207 * at a nonexisting branch. If we were indeed called by
208 * 'git pull', it will notice the misconfiguration because
209 * there is no entry in the resulting FETCH_HEAD marked
210 * for merging.
212 memset(&refspec, 0, sizeof(refspec));
213 refspec.src = branch->merge[i]->src;
214 get_fetch_map(remote_refs, &refspec, tail, 1);
215 for (rm = *old_tail; rm; rm = rm->next)
216 rm->fetch_head_status = FETCH_HEAD_MERGE;
220 static int add_existing(const char *refname, const struct object_id *oid,
221 int flag, void *cbdata)
223 struct string_list *list = (struct string_list *)cbdata;
224 struct string_list_item *item = string_list_insert(list, refname);
225 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
227 oidcpy(old_oid, oid);
228 item->util = old_oid;
229 return 0;
232 static int will_fetch(struct ref **head, const unsigned char *sha1)
234 struct ref *rm = *head;
235 while (rm) {
236 if (!hashcmp(rm->old_oid.hash, sha1))
237 return 1;
238 rm = rm->next;
240 return 0;
243 static void find_non_local_tags(struct transport *transport,
244 struct ref **head,
245 struct ref ***tail)
247 struct string_list existing_refs = STRING_LIST_INIT_DUP;
248 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
249 const struct ref *ref;
250 struct string_list_item *item = NULL;
252 for_each_ref(add_existing, &existing_refs);
253 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
254 if (!starts_with(ref->name, "refs/tags/"))
255 continue;
258 * The peeled ref always follows the matching base
259 * ref, so if we see a peeled ref that we don't want
260 * to fetch then we can mark the ref entry in the list
261 * as one to ignore by setting util to NULL.
263 if (ends_with(ref->name, "^{}")) {
264 if (item &&
265 !has_object_file_with_flags(&ref->old_oid,
266 OBJECT_INFO_QUICK) &&
267 !will_fetch(head, ref->old_oid.hash) &&
268 !has_sha1_file_with_flags(item->util,
269 OBJECT_INFO_QUICK) &&
270 !will_fetch(head, item->util))
271 item->util = NULL;
272 item = NULL;
273 continue;
277 * If item is non-NULL here, then we previously saw a
278 * ref not followed by a peeled reference, so we need
279 * to check if it is a lightweight tag that we want to
280 * fetch.
282 if (item &&
283 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
284 !will_fetch(head, item->util))
285 item->util = NULL;
287 item = NULL;
289 /* skip duplicates and refs that we already have */
290 if (string_list_has_string(&remote_refs, ref->name) ||
291 string_list_has_string(&existing_refs, ref->name))
292 continue;
294 item = string_list_insert(&remote_refs, ref->name);
295 item->util = (void *)&ref->old_oid;
297 string_list_clear(&existing_refs, 1);
300 * We may have a final lightweight tag that needs to be
301 * checked to see if it needs fetching.
303 if (item &&
304 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
305 !will_fetch(head, item->util))
306 item->util = NULL;
309 * For all the tags in the remote_refs string list,
310 * add them to the list of refs to be fetched
312 for_each_string_list_item(item, &remote_refs) {
313 /* Unless we have already decided to ignore this item... */
314 if (item->util)
316 struct ref *rm = alloc_ref(item->string);
317 rm->peer_ref = alloc_ref(item->string);
318 oidcpy(&rm->old_oid, item->util);
319 **tail = rm;
320 *tail = &rm->next;
324 string_list_clear(&remote_refs, 0);
327 static struct ref *get_ref_map(struct transport *transport,
328 struct refspec *refspecs, int refspec_count,
329 int tags, int *autotags)
331 int i;
332 struct ref *rm;
333 struct ref *ref_map = NULL;
334 struct ref **tail = &ref_map;
336 /* opportunistically-updated references: */
337 struct ref *orefs = NULL, **oref_tail = &orefs;
339 const struct ref *remote_refs = transport_get_remote_refs(transport);
341 if (refspec_count) {
342 struct refspec *fetch_refspec;
343 int fetch_refspec_nr;
345 for (i = 0; i < refspec_count; i++) {
346 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
347 if (refspecs[i].dst && refspecs[i].dst[0])
348 *autotags = 1;
350 /* Merge everything on the command line (but not --tags) */
351 for (rm = ref_map; rm; rm = rm->next)
352 rm->fetch_head_status = FETCH_HEAD_MERGE;
355 * For any refs that we happen to be fetching via
356 * command-line arguments, the destination ref might
357 * have been missing or have been different than the
358 * remote-tracking ref that would be derived from the
359 * configured refspec. In these cases, we want to
360 * take the opportunity to update their configured
361 * remote-tracking reference. However, we do not want
362 * to mention these entries in FETCH_HEAD at all, as
363 * they would simply be duplicates of existing
364 * entries, so we set them FETCH_HEAD_IGNORE below.
366 * We compute these entries now, based only on the
367 * refspecs specified on the command line. But we add
368 * them to the list following the refspecs resulting
369 * from the tags option so that one of the latter,
370 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
371 * by ref_remove_duplicates() in favor of one of these
372 * opportunistic entries with FETCH_HEAD_IGNORE.
374 if (refmap_array) {
375 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
376 fetch_refspec_nr = refmap_nr;
377 } else {
378 fetch_refspec = transport->remote->fetch;
379 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
382 for (i = 0; i < fetch_refspec_nr; i++)
383 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
384 } else if (refmap_array) {
385 die("--refmap option is only meaningful with command-line refspec(s).");
386 } else {
387 /* Use the defaults */
388 struct remote *remote = transport->remote;
389 struct branch *branch = branch_get(NULL);
390 int has_merge = branch_has_merge_config(branch);
391 if (remote &&
392 (remote->fetch_refspec_nr ||
393 /* Note: has_merge implies non-NULL branch->remote_name */
394 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
395 for (i = 0; i < remote->fetch_refspec_nr; i++) {
396 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
397 if (remote->fetch[i].dst &&
398 remote->fetch[i].dst[0])
399 *autotags = 1;
400 if (!i && !has_merge && ref_map &&
401 !remote->fetch[0].pattern)
402 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
405 * if the remote we're fetching from is the same
406 * as given in branch.<name>.remote, we add the
407 * ref given in branch.<name>.merge, too.
409 * Note: has_merge implies non-NULL branch->remote_name
411 if (has_merge &&
412 !strcmp(branch->remote_name, remote->name))
413 add_merge_config(&ref_map, remote_refs, branch, &tail);
414 } else {
415 ref_map = get_remote_ref(remote_refs, "HEAD");
416 if (!ref_map)
417 die(_("Couldn't find remote ref HEAD"));
418 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
419 tail = &ref_map->next;
423 if (tags == TAGS_SET)
424 /* also fetch all tags */
425 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
426 else if (tags == TAGS_DEFAULT && *autotags)
427 find_non_local_tags(transport, &ref_map, &tail);
429 /* Now append any refs to be updated opportunistically: */
430 *tail = orefs;
431 for (rm = orefs; rm; rm = rm->next) {
432 rm->fetch_head_status = FETCH_HEAD_IGNORE;
433 tail = &rm->next;
436 return ref_remove_duplicates(ref_map);
439 #define STORE_REF_ERROR_OTHER 1
440 #define STORE_REF_ERROR_DF_CONFLICT 2
442 static int s_update_ref(const char *action,
443 struct ref *ref,
444 int check_old)
446 char *msg;
447 char *rla = getenv("GIT_REFLOG_ACTION");
448 struct ref_transaction *transaction;
449 struct strbuf err = STRBUF_INIT;
450 int ret, df_conflict = 0;
452 if (dry_run)
453 return 0;
454 if (!rla)
455 rla = default_rla.buf;
456 msg = xstrfmt("%s: %s", rla, action);
458 transaction = ref_transaction_begin(&err);
459 if (!transaction ||
460 ref_transaction_update(transaction, ref->name,
461 &ref->new_oid,
462 check_old ? &ref->old_oid : NULL,
463 0, msg, &err))
464 goto fail;
466 ret = ref_transaction_commit(transaction, &err);
467 if (ret) {
468 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
469 goto fail;
472 ref_transaction_free(transaction);
473 strbuf_release(&err);
474 free(msg);
475 return 0;
476 fail:
477 ref_transaction_free(transaction);
478 error("%s", err.buf);
479 strbuf_release(&err);
480 free(msg);
481 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
482 : STORE_REF_ERROR_OTHER;
485 static int refcol_width = 10;
486 static int compact_format;
488 static void adjust_refcol_width(const struct ref *ref)
490 int max, rlen, llen, len;
492 /* uptodate lines are only shown on high verbosity level */
493 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
494 return;
496 max = term_columns();
497 rlen = utf8_strwidth(prettify_refname(ref->name));
499 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
502 * rough estimation to see if the output line is too long and
503 * should not be counted (we can't do precise calculation
504 * anyway because we don't know if the error explanation part
505 * will be printed in update_local_ref)
507 if (compact_format) {
508 llen = 0;
509 max = max * 2 / 3;
511 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
512 if (len >= max)
513 return;
516 * Not precise calculation for compact mode because '*' can
517 * appear on the left hand side of '->' and shrink the column
518 * back.
520 if (refcol_width < rlen)
521 refcol_width = rlen;
524 static void prepare_format_display(struct ref *ref_map)
526 struct ref *rm;
527 const char *format = "full";
529 git_config_get_string_const("fetch.output", &format);
530 if (!strcasecmp(format, "full"))
531 compact_format = 0;
532 else if (!strcasecmp(format, "compact"))
533 compact_format = 1;
534 else
535 die(_("configuration fetch.output contains invalid value %s"),
536 format);
538 for (rm = ref_map; rm; rm = rm->next) {
539 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
540 !rm->peer_ref ||
541 !strcmp(rm->name, "HEAD"))
542 continue;
544 adjust_refcol_width(rm);
548 static void print_remote_to_local(struct strbuf *display,
549 const char *remote, const char *local)
551 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
554 static int find_and_replace(struct strbuf *haystack,
555 const char *needle,
556 const char *placeholder)
558 const char *p = strstr(haystack->buf, needle);
559 int plen, nlen;
561 if (!p)
562 return 0;
564 if (p > haystack->buf && p[-1] != '/')
565 return 0;
567 plen = strlen(p);
568 nlen = strlen(needle);
569 if (plen > nlen && p[nlen] != '/')
570 return 0;
572 strbuf_splice(haystack, p - haystack->buf, nlen,
573 placeholder, strlen(placeholder));
574 return 1;
577 static void print_compact(struct strbuf *display,
578 const char *remote, const char *local)
580 struct strbuf r = STRBUF_INIT;
581 struct strbuf l = STRBUF_INIT;
583 if (!strcmp(remote, local)) {
584 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
585 return;
588 strbuf_addstr(&r, remote);
589 strbuf_addstr(&l, local);
591 if (!find_and_replace(&r, local, "*"))
592 find_and_replace(&l, remote, "*");
593 print_remote_to_local(display, r.buf, l.buf);
595 strbuf_release(&r);
596 strbuf_release(&l);
599 static void format_display(struct strbuf *display, char code,
600 const char *summary, const char *error,
601 const char *remote, const char *local,
602 int summary_width)
604 int width = (summary_width + strlen(summary) - gettext_width(summary));
606 strbuf_addf(display, "%c %-*s ", code, width, summary);
607 if (!compact_format)
608 print_remote_to_local(display, remote, local);
609 else
610 print_compact(display, remote, local);
611 if (error)
612 strbuf_addf(display, " (%s)", error);
615 static int update_local_ref(struct ref *ref,
616 const char *remote,
617 const struct ref *remote_ref,
618 struct strbuf *display,
619 int summary_width)
621 struct commit *current = NULL, *updated;
622 enum object_type type;
623 struct branch *current_branch = branch_get(NULL);
624 const char *pretty_ref = prettify_refname(ref->name);
626 type = sha1_object_info(ref->new_oid.hash, NULL);
627 if (type < 0)
628 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
630 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
631 if (verbosity > 0)
632 format_display(display, '=', _("[up to date]"), NULL,
633 remote, pretty_ref, summary_width);
634 return 0;
637 if (current_branch &&
638 !strcmp(ref->name, current_branch->name) &&
639 !(update_head_ok || is_bare_repository()) &&
640 !is_null_oid(&ref->old_oid)) {
642 * If this is the head, and it's not okay to update
643 * the head, and the old value of the head isn't empty...
645 format_display(display, '!', _("[rejected]"),
646 _("can't fetch in current branch"),
647 remote, pretty_ref, summary_width);
648 return 1;
651 if (!is_null_oid(&ref->old_oid) &&
652 starts_with(ref->name, "refs/tags/")) {
653 int r;
654 r = s_update_ref("updating tag", ref, 0);
655 format_display(display, r ? '!' : 't', _("[tag update]"),
656 r ? _("unable to update local ref") : NULL,
657 remote, pretty_ref, summary_width);
658 return r;
661 current = lookup_commit_reference_gently(&ref->old_oid, 1);
662 updated = lookup_commit_reference_gently(&ref->new_oid, 1);
663 if (!current || !updated) {
664 const char *msg;
665 const char *what;
666 int r;
668 * Nicely describe the new ref we're fetching.
669 * Base this on the remote's ref name, as it's
670 * more likely to follow a standard layout.
672 const char *name = remote_ref ? remote_ref->name : "";
673 if (starts_with(name, "refs/tags/")) {
674 msg = "storing tag";
675 what = _("[new tag]");
676 } else if (starts_with(name, "refs/heads/")) {
677 msg = "storing head";
678 what = _("[new branch]");
679 } else {
680 msg = "storing ref";
681 what = _("[new ref]");
684 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
685 (recurse_submodules != RECURSE_SUBMODULES_ON))
686 check_for_new_submodule_commits(&ref->new_oid);
687 r = s_update_ref(msg, ref, 0);
688 format_display(display, r ? '!' : '*', what,
689 r ? _("unable to update local ref") : NULL,
690 remote, pretty_ref, summary_width);
691 return r;
694 if (in_merge_bases(current, updated)) {
695 struct strbuf quickref = STRBUF_INIT;
696 int r;
697 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
698 strbuf_addstr(&quickref, "..");
699 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
700 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
701 (recurse_submodules != RECURSE_SUBMODULES_ON))
702 check_for_new_submodule_commits(&ref->new_oid);
703 r = s_update_ref("fast-forward", ref, 1);
704 format_display(display, r ? '!' : ' ', quickref.buf,
705 r ? _("unable to update local ref") : NULL,
706 remote, pretty_ref, summary_width);
707 strbuf_release(&quickref);
708 return r;
709 } else if (force || ref->force) {
710 struct strbuf quickref = STRBUF_INIT;
711 int r;
712 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
713 strbuf_addstr(&quickref, "...");
714 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
715 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
716 (recurse_submodules != RECURSE_SUBMODULES_ON))
717 check_for_new_submodule_commits(&ref->new_oid);
718 r = s_update_ref("forced-update", ref, 1);
719 format_display(display, r ? '!' : '+', quickref.buf,
720 r ? _("unable to update local ref") : _("forced update"),
721 remote, pretty_ref, summary_width);
722 strbuf_release(&quickref);
723 return r;
724 } else {
725 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
726 remote, pretty_ref, summary_width);
727 return 1;
731 static int iterate_ref_map(void *cb_data, struct object_id *oid)
733 struct ref **rm = cb_data;
734 struct ref *ref = *rm;
736 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
737 ref = ref->next;
738 if (!ref)
739 return -1; /* end of the list */
740 *rm = ref->next;
741 oidcpy(oid, &ref->old_oid);
742 return 0;
745 static int store_updated_refs(const char *raw_url, const char *remote_name,
746 struct ref *ref_map)
748 FILE *fp;
749 struct commit *commit;
750 int url_len, i, rc = 0;
751 struct strbuf note = STRBUF_INIT;
752 const char *what, *kind;
753 struct ref *rm;
754 char *url;
755 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
756 int want_status;
757 int summary_width = transport_summary_width(ref_map);
759 fp = fopen(filename, "a");
760 if (!fp)
761 return error_errno(_("cannot open %s"), filename);
763 if (raw_url)
764 url = transport_anonymize_url(raw_url);
765 else
766 url = xstrdup("foreign");
768 rm = ref_map;
769 if (check_connected(iterate_ref_map, &rm, NULL)) {
770 rc = error(_("%s did not send all necessary objects\n"), url);
771 goto abort;
774 prepare_format_display(ref_map);
777 * We do a pass for each fetch_head_status type in their enum order, so
778 * merged entries are written before not-for-merge. That lets readers
779 * use FETCH_HEAD as a refname to refer to the ref to be merged.
781 for (want_status = FETCH_HEAD_MERGE;
782 want_status <= FETCH_HEAD_IGNORE;
783 want_status++) {
784 for (rm = ref_map; rm; rm = rm->next) {
785 struct ref *ref = NULL;
786 const char *merge_status_marker = "";
788 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
789 if (want_status == FETCH_HEAD_MERGE)
790 warning(_("reject %s because shallow roots are not allowed to be updated"),
791 rm->peer_ref ? rm->peer_ref->name : rm->name);
792 continue;
795 commit = lookup_commit_reference_gently(&rm->old_oid,
797 if (!commit)
798 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
800 if (rm->fetch_head_status != want_status)
801 continue;
803 if (rm->peer_ref) {
804 ref = alloc_ref(rm->peer_ref->name);
805 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
806 oidcpy(&ref->new_oid, &rm->old_oid);
807 ref->force = rm->peer_ref->force;
811 if (!strcmp(rm->name, "HEAD")) {
812 kind = "";
813 what = "";
815 else if (starts_with(rm->name, "refs/heads/")) {
816 kind = "branch";
817 what = rm->name + 11;
819 else if (starts_with(rm->name, "refs/tags/")) {
820 kind = "tag";
821 what = rm->name + 10;
823 else if (starts_with(rm->name, "refs/remotes/")) {
824 kind = "remote-tracking branch";
825 what = rm->name + 13;
827 else {
828 kind = "";
829 what = rm->name;
832 url_len = strlen(url);
833 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
835 url_len = i + 1;
836 if (4 < i && !strncmp(".git", url + i - 3, 4))
837 url_len = i - 3;
839 strbuf_reset(&note);
840 if (*what) {
841 if (*kind)
842 strbuf_addf(&note, "%s ", kind);
843 strbuf_addf(&note, "'%s' of ", what);
845 switch (rm->fetch_head_status) {
846 case FETCH_HEAD_NOT_FOR_MERGE:
847 merge_status_marker = "not-for-merge";
848 /* fall-through */
849 case FETCH_HEAD_MERGE:
850 fprintf(fp, "%s\t%s\t%s",
851 oid_to_hex(&rm->old_oid),
852 merge_status_marker,
853 note.buf);
854 for (i = 0; i < url_len; ++i)
855 if ('\n' == url[i])
856 fputs("\\n", fp);
857 else
858 fputc(url[i], fp);
859 fputc('\n', fp);
860 break;
861 default:
862 /* do not write anything to FETCH_HEAD */
863 break;
866 strbuf_reset(&note);
867 if (ref) {
868 rc |= update_local_ref(ref, what, rm, &note,
869 summary_width);
870 free(ref);
871 } else
872 format_display(&note, '*',
873 *kind ? kind : "branch", NULL,
874 *what ? what : "HEAD",
875 "FETCH_HEAD", summary_width);
876 if (note.len) {
877 if (verbosity >= 0 && !shown_url) {
878 fprintf(stderr, _("From %.*s\n"),
879 url_len, url);
880 shown_url = 1;
882 if (verbosity >= 0)
883 fprintf(stderr, " %s\n", note.buf);
888 if (rc & STORE_REF_ERROR_DF_CONFLICT)
889 error(_("some local refs could not be updated; try running\n"
890 " 'git remote prune %s' to remove any old, conflicting "
891 "branches"), remote_name);
893 abort:
894 strbuf_release(&note);
895 free(url);
896 fclose(fp);
897 return rc;
901 * We would want to bypass the object transfer altogether if
902 * everything we are going to fetch already exists and is connected
903 * locally.
905 static int quickfetch(struct ref *ref_map)
907 struct ref *rm = ref_map;
908 struct check_connected_options opt = CHECK_CONNECTED_INIT;
911 * If we are deepening a shallow clone we already have these
912 * objects reachable. Running rev-list here will return with
913 * a good (0) exit status and we'll bypass the fetch that we
914 * really need to perform. Claiming failure now will ensure
915 * we perform the network exchange to deepen our history.
917 if (deepen)
918 return -1;
919 opt.quiet = 1;
920 return check_connected(iterate_ref_map, &rm, &opt);
923 static int fetch_refs(struct transport *transport, struct ref *ref_map)
925 int ret = quickfetch(ref_map);
926 if (ret)
927 ret = transport_fetch_refs(transport, ref_map);
928 if (!ret)
929 ret |= store_updated_refs(transport->url,
930 transport->remote->name,
931 ref_map);
932 transport_unlock_pack(transport);
933 return ret;
936 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
937 const char *raw_url)
939 int url_len, i, result = 0;
940 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
941 char *url;
942 int summary_width = transport_summary_width(stale_refs);
943 const char *dangling_msg = dry_run
944 ? _(" (%s will become dangling)")
945 : _(" (%s has become dangling)");
947 if (raw_url)
948 url = transport_anonymize_url(raw_url);
949 else
950 url = xstrdup("foreign");
952 url_len = strlen(url);
953 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
956 url_len = i + 1;
957 if (4 < i && !strncmp(".git", url + i - 3, 4))
958 url_len = i - 3;
960 if (!dry_run) {
961 struct string_list refnames = STRING_LIST_INIT_NODUP;
963 for (ref = stale_refs; ref; ref = ref->next)
964 string_list_append(&refnames, ref->name);
966 result = delete_refs("fetch: prune", &refnames, 0);
967 string_list_clear(&refnames, 0);
970 if (verbosity >= 0) {
971 for (ref = stale_refs; ref; ref = ref->next) {
972 struct strbuf sb = STRBUF_INIT;
973 if (!shown_url) {
974 fprintf(stderr, _("From %.*s\n"), url_len, url);
975 shown_url = 1;
977 format_display(&sb, '-', _("[deleted]"), NULL,
978 _("(none)"), prettify_refname(ref->name),
979 summary_width);
980 fprintf(stderr, " %s\n",sb.buf);
981 strbuf_release(&sb);
982 warn_dangling_symref(stderr, dangling_msg, ref->name);
986 free(url);
987 free_refs(stale_refs);
988 return result;
991 static void check_not_current_branch(struct ref *ref_map)
993 struct branch *current_branch = branch_get(NULL);
995 if (is_bare_repository() || !current_branch)
996 return;
998 for (; ref_map; ref_map = ref_map->next)
999 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1000 ref_map->peer_ref->name))
1001 die(_("Refusing to fetch into current branch %s "
1002 "of non-bare repository"), current_branch->refname);
1005 static int truncate_fetch_head(void)
1007 const char *filename = git_path_fetch_head();
1008 FILE *fp = fopen_for_writing(filename);
1010 if (!fp)
1011 return error_errno(_("cannot open %s"), filename);
1012 fclose(fp);
1013 return 0;
1016 static void set_option(struct transport *transport, const char *name, const char *value)
1018 int r = transport_set_option(transport, name, value);
1019 if (r < 0)
1020 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1021 name, value, transport->url);
1022 if (r > 0)
1023 warning(_("Option \"%s\" is ignored for %s\n"),
1024 name, transport->url);
1027 static struct transport *prepare_transport(struct remote *remote, int deepen)
1029 struct transport *transport;
1030 transport = transport_get(remote, NULL);
1031 transport_set_verbosity(transport, verbosity, progress);
1032 transport->family = family;
1033 if (upload_pack)
1034 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1035 if (keep)
1036 set_option(transport, TRANS_OPT_KEEP, "yes");
1037 if (depth)
1038 set_option(transport, TRANS_OPT_DEPTH, depth);
1039 if (deepen && deepen_since)
1040 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1041 if (deepen && deepen_not.nr)
1042 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1043 (const char *)&deepen_not);
1044 if (deepen_relative)
1045 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1046 if (update_shallow)
1047 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1048 return transport;
1051 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1053 int cannot_reuse;
1056 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1057 * when remote helper is used (setting it to an empty string
1058 * is not unsetting). We could extend the remote helper
1059 * protocol for that, but for now, just force a new connection
1060 * without deepen-since. Similar story for deepen-not.
1062 cannot_reuse = transport->cannot_reuse ||
1063 deepen_since || deepen_not.nr;
1064 if (cannot_reuse) {
1065 gsecondary = prepare_transport(transport->remote, 0);
1066 transport = gsecondary;
1069 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1070 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1071 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1072 fetch_refs(transport, ref_map);
1074 if (gsecondary) {
1075 transport_disconnect(gsecondary);
1076 gsecondary = NULL;
1080 static int do_fetch(struct transport *transport,
1081 struct refspec *refs, int ref_count)
1083 struct string_list existing_refs = STRING_LIST_INIT_DUP;
1084 struct ref *ref_map;
1085 struct ref *rm;
1086 int autotags = (transport->remote->fetch_tags == 1);
1087 int retcode = 0;
1089 for_each_ref(add_existing, &existing_refs);
1091 if (tags == TAGS_DEFAULT) {
1092 if (transport->remote->fetch_tags == 2)
1093 tags = TAGS_SET;
1094 if (transport->remote->fetch_tags == -1)
1095 tags = TAGS_UNSET;
1098 /* if not appending, truncate FETCH_HEAD */
1099 if (!append && !dry_run) {
1100 retcode = truncate_fetch_head();
1101 if (retcode)
1102 goto cleanup;
1105 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1106 if (!update_head_ok)
1107 check_not_current_branch(ref_map);
1109 for (rm = ref_map; rm; rm = rm->next) {
1110 if (rm->peer_ref) {
1111 struct string_list_item *peer_item =
1112 string_list_lookup(&existing_refs,
1113 rm->peer_ref->name);
1114 if (peer_item) {
1115 struct object_id *old_oid = peer_item->util;
1116 oidcpy(&rm->peer_ref->old_oid, old_oid);
1121 if (tags == TAGS_DEFAULT && autotags)
1122 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1123 if (prune) {
1125 * We only prune based on refspecs specified
1126 * explicitly (via command line or configuration); we
1127 * don't care whether --tags was specified.
1129 if (ref_count) {
1130 prune_refs(refs, ref_count, ref_map, transport->url);
1131 } else {
1132 prune_refs(transport->remote->fetch,
1133 transport->remote->fetch_refspec_nr,
1134 ref_map,
1135 transport->url);
1138 if (fetch_refs(transport, ref_map)) {
1139 free_refs(ref_map);
1140 retcode = 1;
1141 goto cleanup;
1143 free_refs(ref_map);
1145 /* if neither --no-tags nor --tags was specified, do automated tag
1146 * following ... */
1147 if (tags == TAGS_DEFAULT && autotags) {
1148 struct ref **tail = &ref_map;
1149 ref_map = NULL;
1150 find_non_local_tags(transport, &ref_map, &tail);
1151 if (ref_map)
1152 backfill_tags(transport, ref_map);
1153 free_refs(ref_map);
1156 cleanup:
1157 string_list_clear(&existing_refs, 1);
1158 return retcode;
1161 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1163 struct string_list *list = priv;
1164 if (!remote->skip_default_update)
1165 string_list_append(list, remote->name);
1166 return 0;
1169 struct remote_group_data {
1170 const char *name;
1171 struct string_list *list;
1174 static int get_remote_group(const char *key, const char *value, void *priv)
1176 struct remote_group_data *g = priv;
1178 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1179 /* split list by white space */
1180 while (*value) {
1181 size_t wordlen = strcspn(value, " \t\n");
1183 if (wordlen >= 1)
1184 string_list_append_nodup(g->list,
1185 xstrndup(value, wordlen));
1186 value += wordlen + (value[wordlen] != '\0');
1190 return 0;
1193 static int add_remote_or_group(const char *name, struct string_list *list)
1195 int prev_nr = list->nr;
1196 struct remote_group_data g;
1197 g.name = name; g.list = list;
1199 git_config(get_remote_group, &g);
1200 if (list->nr == prev_nr) {
1201 struct remote *remote = remote_get(name);
1202 if (!remote_is_configured(remote, 0))
1203 return 0;
1204 string_list_append(list, remote->name);
1206 return 1;
1209 static void add_options_to_argv(struct argv_array *argv)
1211 if (dry_run)
1212 argv_array_push(argv, "--dry-run");
1213 if (prune != -1)
1214 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1215 if (update_head_ok)
1216 argv_array_push(argv, "--update-head-ok");
1217 if (force)
1218 argv_array_push(argv, "--force");
1219 if (keep)
1220 argv_array_push(argv, "--keep");
1221 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1222 argv_array_push(argv, "--recurse-submodules");
1223 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1224 argv_array_push(argv, "--recurse-submodules=on-demand");
1225 if (tags == TAGS_SET)
1226 argv_array_push(argv, "--tags");
1227 else if (tags == TAGS_UNSET)
1228 argv_array_push(argv, "--no-tags");
1229 if (verbosity >= 2)
1230 argv_array_push(argv, "-v");
1231 if (verbosity >= 1)
1232 argv_array_push(argv, "-v");
1233 else if (verbosity < 0)
1234 argv_array_push(argv, "-q");
1238 static int fetch_multiple(struct string_list *list)
1240 int i, result = 0;
1241 struct argv_array argv = ARGV_ARRAY_INIT;
1243 if (!append && !dry_run) {
1244 int errcode = truncate_fetch_head();
1245 if (errcode)
1246 return errcode;
1249 argv_array_pushl(&argv, "fetch", "--append", NULL);
1250 add_options_to_argv(&argv);
1252 for (i = 0; i < list->nr; i++) {
1253 const char *name = list->items[i].string;
1254 argv_array_push(&argv, name);
1255 if (verbosity >= 0)
1256 printf(_("Fetching %s\n"), name);
1257 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1258 error(_("Could not fetch %s"), name);
1259 result = 1;
1261 argv_array_pop(&argv);
1264 argv_array_clear(&argv);
1265 return result;
1268 static int fetch_one(struct remote *remote, int argc, const char **argv)
1270 static const char **refs = NULL;
1271 struct refspec *refspec;
1272 int ref_nr = 0;
1273 int exit_code;
1275 if (!remote)
1276 die(_("No remote repository specified. Please, specify either a URL or a\n"
1277 "remote name from which new revisions should be fetched."));
1279 gtransport = prepare_transport(remote, 1);
1281 if (prune < 0) {
1282 /* no command line request */
1283 if (0 <= gtransport->remote->prune)
1284 prune = gtransport->remote->prune;
1285 else if (0 <= fetch_prune_config)
1286 prune = fetch_prune_config;
1287 else
1288 prune = PRUNE_BY_DEFAULT;
1291 if (argc > 0) {
1292 int j = 0;
1293 int i;
1294 refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1295 for (i = 0; i < argc; i++) {
1296 if (!strcmp(argv[i], "tag")) {
1297 i++;
1298 if (i >= argc)
1299 die(_("You need to specify a tag name."));
1300 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1301 argv[i], argv[i]);
1302 } else
1303 refs[j++] = argv[i];
1305 refs[j] = NULL;
1306 ref_nr = j;
1309 sigchain_push_common(unlock_pack_on_signal);
1310 atexit(unlock_pack);
1311 refspec = parse_fetch_refspec(ref_nr, refs);
1312 exit_code = do_fetch(gtransport, refspec, ref_nr);
1313 free_refspec(ref_nr, refspec);
1314 transport_disconnect(gtransport);
1315 gtransport = NULL;
1316 return exit_code;
1319 int cmd_fetch(int argc, const char **argv, const char *prefix)
1321 int i;
1322 struct string_list list = STRING_LIST_INIT_DUP;
1323 struct remote *remote;
1324 int result = 0;
1325 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1327 packet_trace_identity("fetch");
1329 /* Record the command line for the reflog */
1330 strbuf_addstr(&default_rla, "fetch");
1331 for (i = 1; i < argc; i++)
1332 strbuf_addf(&default_rla, " %s", argv[i]);
1334 config_from_gitmodules(gitmodules_fetch_config, NULL);
1335 git_config(git_fetch_config, NULL);
1337 argc = parse_options(argc, argv, prefix,
1338 builtin_fetch_options, builtin_fetch_usage, 0);
1340 if (deepen_relative) {
1341 if (deepen_relative < 0)
1342 die(_("Negative depth in --deepen is not supported"));
1343 if (depth)
1344 die(_("--deepen and --depth are mutually exclusive"));
1345 depth = xstrfmt("%d", deepen_relative);
1347 if (unshallow) {
1348 if (depth)
1349 die(_("--depth and --unshallow cannot be used together"));
1350 else if (!is_repository_shallow())
1351 die(_("--unshallow on a complete repository does not make sense"));
1352 else
1353 depth = xstrfmt("%d", INFINITE_DEPTH);
1356 /* no need to be strict, transport_set_option() will validate it again */
1357 if (depth && atoi(depth) < 1)
1358 die(_("depth %s is not a positive number"), depth);
1359 if (depth || deepen_since || deepen_not.nr)
1360 deepen = 1;
1362 if (all) {
1363 if (argc == 1)
1364 die(_("fetch --all does not take a repository argument"));
1365 else if (argc > 1)
1366 die(_("fetch --all does not make sense with refspecs"));
1367 (void) for_each_remote(get_one_remote_for_fetch, &list);
1368 result = fetch_multiple(&list);
1369 } else if (argc == 0) {
1370 /* No arguments -- use default remote */
1371 remote = remote_get(NULL);
1372 result = fetch_one(remote, argc, argv);
1373 } else if (multiple) {
1374 /* All arguments are assumed to be remotes or groups */
1375 for (i = 0; i < argc; i++)
1376 if (!add_remote_or_group(argv[i], &list))
1377 die(_("No such remote or remote group: %s"), argv[i]);
1378 result = fetch_multiple(&list);
1379 } else {
1380 /* Single remote or group */
1381 (void) add_remote_or_group(argv[0], &list);
1382 if (list.nr > 1) {
1383 /* More than one remote */
1384 if (argc > 1)
1385 die(_("Fetching a group and specifying refspecs does not make sense"));
1386 result = fetch_multiple(&list);
1387 } else {
1388 /* Zero or one remotes */
1389 remote = remote_get(argv[0]);
1390 result = fetch_one(remote, argc-1, argv+1);
1394 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1395 struct argv_array options = ARGV_ARRAY_INIT;
1397 add_options_to_argv(&options);
1398 result = fetch_populated_submodules(the_repository,
1399 &options,
1400 submodule_prefix,
1401 recurse_submodules,
1402 recurse_submodules_default,
1403 verbosity < 0,
1404 max_children);
1405 argv_array_clear(&options);
1408 string_list_clear(&list, 0);
1410 close_all_packs();
1412 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1413 if (verbosity < 0)
1414 argv_array_push(&argv_gc_auto, "--quiet");
1415 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1416 argv_array_clear(&argv_gc_auto);
1418 return result;