reset --hard: make use of the pretty machinery
[git.git] / builtin / fetch.c
blob5f2c2ab23e4cde17747147f23dcedaebe66c74a3
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, deepen_relative;
39 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
40 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
41 static int max_children = -1;
42 static enum transport_family family;
43 static const char *depth;
44 static const char *deepen_since;
45 static const char *upload_pack;
46 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
47 static struct strbuf default_rla = STRBUF_INIT;
48 static struct transport *gtransport;
49 static struct transport *gsecondary;
50 static const char *submodule_prefix = "";
51 static const char *recurse_submodules_default;
52 static int shown_url = 0;
53 static int refmap_alloc, refmap_nr;
54 static const char **refmap_array;
56 static int option_parse_recurse_submodules(const struct option *opt,
57 const char *arg, int unset)
59 if (unset) {
60 recurse_submodules = RECURSE_SUBMODULES_OFF;
61 } else {
62 if (arg)
63 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
64 else
65 recurse_submodules = RECURSE_SUBMODULES_ON;
67 return 0;
70 static int git_fetch_config(const char *k, const char *v, void *cb)
72 if (!strcmp(k, "fetch.prune")) {
73 fetch_prune_config = git_config_bool(k, v);
74 return 0;
76 return git_default_config(k, v, cb);
79 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
81 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
84 * "git fetch --refmap='' origin foo"
85 * can be used to tell the command not to store anywhere
87 if (*arg)
88 refmap_array[refmap_nr++] = arg;
89 return 0;
92 static struct option builtin_fetch_options[] = {
93 OPT__VERBOSITY(&verbosity),
94 OPT_BOOL(0, "all", &all,
95 N_("fetch from all remotes")),
96 OPT_BOOL('a', "append", &append,
97 N_("append to .git/FETCH_HEAD instead of overwriting")),
98 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
99 N_("path to upload pack on remote end")),
100 OPT__FORCE(&force, N_("force overwrite of local branch")),
101 OPT_BOOL('m', "multiple", &multiple,
102 N_("fetch from multiple remotes")),
103 OPT_SET_INT('t', "tags", &tags,
104 N_("fetch all tags and associated objects"), TAGS_SET),
105 OPT_SET_INT('n', NULL, &tags,
106 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
107 OPT_INTEGER('j', "jobs", &max_children,
108 N_("number of submodules fetched in parallel")),
109 OPT_BOOL('p', "prune", &prune,
110 N_("prune remote-tracking branches no longer on remote")),
111 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
112 N_("control recursive fetching of submodules"),
113 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
114 OPT_BOOL(0, "dry-run", &dry_run,
115 N_("dry run")),
116 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
117 OPT_BOOL('u', "update-head-ok", &update_head_ok,
118 N_("allow updating of HEAD ref")),
119 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
120 OPT_STRING(0, "depth", &depth, N_("depth"),
121 N_("deepen history of shallow clone")),
122 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
123 N_("deepen history of shallow repository based on time")),
124 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
125 N_("deepen history of shallow clone, excluding rev")),
126 OPT_INTEGER(0, "deepen", &deepen_relative,
127 N_("deepen history of shallow clone")),
128 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
129 N_("convert to a complete repository"),
130 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
131 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
132 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
133 { OPTION_STRING, 0, "recurse-submodules-default",
134 &recurse_submodules_default, NULL,
135 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
136 OPT_BOOL(0, "update-shallow", &update_shallow,
137 N_("accept refs that update .git/shallow")),
138 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
139 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
140 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
141 TRANSPORT_FAMILY_IPV4),
142 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
143 TRANSPORT_FAMILY_IPV6),
144 OPT_END()
147 static void unlock_pack(void)
149 if (gtransport)
150 transport_unlock_pack(gtransport);
151 if (gsecondary)
152 transport_unlock_pack(gsecondary);
155 static void unlock_pack_on_signal(int signo)
157 unlock_pack();
158 sigchain_pop(signo);
159 raise(signo);
162 static void add_merge_config(struct ref **head,
163 const struct ref *remote_refs,
164 struct branch *branch,
165 struct ref ***tail)
167 int i;
169 for (i = 0; i < branch->merge_nr; i++) {
170 struct ref *rm, **old_tail = *tail;
171 struct refspec refspec;
173 for (rm = *head; rm; rm = rm->next) {
174 if (branch_merge_matches(branch, i, rm->name)) {
175 rm->fetch_head_status = FETCH_HEAD_MERGE;
176 break;
179 if (rm)
180 continue;
183 * Not fetched to a remote-tracking branch? We need to fetch
184 * it anyway to allow this branch's "branch.$name.merge"
185 * to be honored by 'git pull', but we do not have to
186 * fail if branch.$name.merge is misconfigured to point
187 * at a nonexisting branch. If we were indeed called by
188 * 'git pull', it will notice the misconfiguration because
189 * there is no entry in the resulting FETCH_HEAD marked
190 * for merging.
192 memset(&refspec, 0, sizeof(refspec));
193 refspec.src = branch->merge[i]->src;
194 get_fetch_map(remote_refs, &refspec, tail, 1);
195 for (rm = *old_tail; rm; rm = rm->next)
196 rm->fetch_head_status = FETCH_HEAD_MERGE;
200 static int add_existing(const char *refname, const struct object_id *oid,
201 int flag, void *cbdata)
203 struct string_list *list = (struct string_list *)cbdata;
204 struct string_list_item *item = string_list_insert(list, refname);
205 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
207 oidcpy(old_oid, oid);
208 item->util = old_oid;
209 return 0;
212 static int will_fetch(struct ref **head, const unsigned char *sha1)
214 struct ref *rm = *head;
215 while (rm) {
216 if (!hashcmp(rm->old_oid.hash, sha1))
217 return 1;
218 rm = rm->next;
220 return 0;
223 static void find_non_local_tags(struct transport *transport,
224 struct ref **head,
225 struct ref ***tail)
227 struct string_list existing_refs = STRING_LIST_INIT_DUP;
228 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
229 const struct ref *ref;
230 struct string_list_item *item = NULL;
232 for_each_ref(add_existing, &existing_refs);
233 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
234 if (!starts_with(ref->name, "refs/tags/"))
235 continue;
238 * The peeled ref always follows the matching base
239 * ref, so if we see a peeled ref that we don't want
240 * to fetch then we can mark the ref entry in the list
241 * as one to ignore by setting util to NULL.
243 if (ends_with(ref->name, "^{}")) {
244 if (item &&
245 !has_object_file_with_flags(&ref->old_oid, HAS_SHA1_QUICK) &&
246 !will_fetch(head, ref->old_oid.hash) &&
247 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
248 !will_fetch(head, item->util))
249 item->util = NULL;
250 item = NULL;
251 continue;
255 * If item is non-NULL here, then we previously saw a
256 * ref not followed by a peeled reference, so we need
257 * to check if it is a lightweight tag that we want to
258 * fetch.
260 if (item &&
261 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
262 !will_fetch(head, item->util))
263 item->util = NULL;
265 item = NULL;
267 /* skip duplicates and refs that we already have */
268 if (string_list_has_string(&remote_refs, ref->name) ||
269 string_list_has_string(&existing_refs, ref->name))
270 continue;
272 item = string_list_insert(&remote_refs, ref->name);
273 item->util = (void *)&ref->old_oid;
275 string_list_clear(&existing_refs, 1);
278 * We may have a final lightweight tag that needs to be
279 * checked to see if it needs fetching.
281 if (item &&
282 !has_sha1_file_with_flags(item->util, HAS_SHA1_QUICK) &&
283 !will_fetch(head, item->util))
284 item->util = NULL;
287 * For all the tags in the remote_refs string list,
288 * add them to the list of refs to be fetched
290 for_each_string_list_item(item, &remote_refs) {
291 /* Unless we have already decided to ignore this item... */
292 if (item->util)
294 struct ref *rm = alloc_ref(item->string);
295 rm->peer_ref = alloc_ref(item->string);
296 oidcpy(&rm->old_oid, item->util);
297 **tail = rm;
298 *tail = &rm->next;
302 string_list_clear(&remote_refs, 0);
305 static struct ref *get_ref_map(struct transport *transport,
306 struct refspec *refspecs, int refspec_count,
307 int tags, int *autotags)
309 int i;
310 struct ref *rm;
311 struct ref *ref_map = NULL;
312 struct ref **tail = &ref_map;
314 /* opportunistically-updated references: */
315 struct ref *orefs = NULL, **oref_tail = &orefs;
317 const struct ref *remote_refs = transport_get_remote_refs(transport);
319 if (refspec_count) {
320 struct refspec *fetch_refspec;
321 int fetch_refspec_nr;
323 for (i = 0; i < refspec_count; i++) {
324 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
325 if (refspecs[i].dst && refspecs[i].dst[0])
326 *autotags = 1;
328 /* Merge everything on the command line (but not --tags) */
329 for (rm = ref_map; rm; rm = rm->next)
330 rm->fetch_head_status = FETCH_HEAD_MERGE;
333 * For any refs that we happen to be fetching via
334 * command-line arguments, the destination ref might
335 * have been missing or have been different than the
336 * remote-tracking ref that would be derived from the
337 * configured refspec. In these cases, we want to
338 * take the opportunity to update their configured
339 * remote-tracking reference. However, we do not want
340 * to mention these entries in FETCH_HEAD at all, as
341 * they would simply be duplicates of existing
342 * entries, so we set them FETCH_HEAD_IGNORE below.
344 * We compute these entries now, based only on the
345 * refspecs specified on the command line. But we add
346 * them to the list following the refspecs resulting
347 * from the tags option so that one of the latter,
348 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
349 * by ref_remove_duplicates() in favor of one of these
350 * opportunistic entries with FETCH_HEAD_IGNORE.
352 if (refmap_array) {
353 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
354 fetch_refspec_nr = refmap_nr;
355 } else {
356 fetch_refspec = transport->remote->fetch;
357 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
360 for (i = 0; i < fetch_refspec_nr; i++)
361 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
362 } else if (refmap_array) {
363 die("--refmap option is only meaningful with command-line refspec(s).");
364 } else {
365 /* Use the defaults */
366 struct remote *remote = transport->remote;
367 struct branch *branch = branch_get(NULL);
368 int has_merge = branch_has_merge_config(branch);
369 if (remote &&
370 (remote->fetch_refspec_nr ||
371 /* Note: has_merge implies non-NULL branch->remote_name */
372 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
373 for (i = 0; i < remote->fetch_refspec_nr; i++) {
374 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
375 if (remote->fetch[i].dst &&
376 remote->fetch[i].dst[0])
377 *autotags = 1;
378 if (!i && !has_merge && ref_map &&
379 !remote->fetch[0].pattern)
380 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
383 * if the remote we're fetching from is the same
384 * as given in branch.<name>.remote, we add the
385 * ref given in branch.<name>.merge, too.
387 * Note: has_merge implies non-NULL branch->remote_name
389 if (has_merge &&
390 !strcmp(branch->remote_name, remote->name))
391 add_merge_config(&ref_map, remote_refs, branch, &tail);
392 } else {
393 ref_map = get_remote_ref(remote_refs, "HEAD");
394 if (!ref_map)
395 die(_("Couldn't find remote ref HEAD"));
396 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
397 tail = &ref_map->next;
401 if (tags == TAGS_SET)
402 /* also fetch all tags */
403 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
404 else if (tags == TAGS_DEFAULT && *autotags)
405 find_non_local_tags(transport, &ref_map, &tail);
407 /* Now append any refs to be updated opportunistically: */
408 *tail = orefs;
409 for (rm = orefs; rm; rm = rm->next) {
410 rm->fetch_head_status = FETCH_HEAD_IGNORE;
411 tail = &rm->next;
414 return ref_remove_duplicates(ref_map);
417 #define STORE_REF_ERROR_OTHER 1
418 #define STORE_REF_ERROR_DF_CONFLICT 2
420 static int s_update_ref(const char *action,
421 struct ref *ref,
422 int check_old)
424 char *msg;
425 char *rla = getenv("GIT_REFLOG_ACTION");
426 struct ref_transaction *transaction;
427 struct strbuf err = STRBUF_INIT;
428 int ret, df_conflict = 0;
430 if (dry_run)
431 return 0;
432 if (!rla)
433 rla = default_rla.buf;
434 msg = xstrfmt("%s: %s", rla, action);
436 transaction = ref_transaction_begin(&err);
437 if (!transaction ||
438 ref_transaction_update(transaction, ref->name,
439 ref->new_oid.hash,
440 check_old ? ref->old_oid.hash : NULL,
441 0, msg, &err))
442 goto fail;
444 ret = ref_transaction_commit(transaction, &err);
445 if (ret) {
446 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
447 goto fail;
450 ref_transaction_free(transaction);
451 strbuf_release(&err);
452 free(msg);
453 return 0;
454 fail:
455 ref_transaction_free(transaction);
456 error("%s", err.buf);
457 strbuf_release(&err);
458 free(msg);
459 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
460 : STORE_REF_ERROR_OTHER;
463 static int refcol_width = 10;
464 static int compact_format;
466 static void adjust_refcol_width(const struct ref *ref)
468 int max, rlen, llen, len;
470 /* uptodate lines are only shown on high verbosity level */
471 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
472 return;
474 max = term_columns();
475 rlen = utf8_strwidth(prettify_refname(ref->name));
477 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
480 * rough estimation to see if the output line is too long and
481 * should not be counted (we can't do precise calculation
482 * anyway because we don't know if the error explanation part
483 * will be printed in update_local_ref)
485 if (compact_format) {
486 llen = 0;
487 max = max * 2 / 3;
489 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
490 if (len >= max)
491 return;
494 * Not precise calculation for compact mode because '*' can
495 * appear on the left hand side of '->' and shrink the column
496 * back.
498 if (refcol_width < rlen)
499 refcol_width = rlen;
502 static void prepare_format_display(struct ref *ref_map)
504 struct ref *rm;
505 const char *format = "full";
507 git_config_get_string_const("fetch.output", &format);
508 if (!strcasecmp(format, "full"))
509 compact_format = 0;
510 else if (!strcasecmp(format, "compact"))
511 compact_format = 1;
512 else
513 die(_("configuration fetch.output contains invalid value %s"),
514 format);
516 for (rm = ref_map; rm; rm = rm->next) {
517 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
518 !rm->peer_ref ||
519 !strcmp(rm->name, "HEAD"))
520 continue;
522 adjust_refcol_width(rm);
526 static void print_remote_to_local(struct strbuf *display,
527 const char *remote, const char *local)
529 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
532 static int find_and_replace(struct strbuf *haystack,
533 const char *needle,
534 const char *placeholder)
536 const char *p = strstr(haystack->buf, needle);
537 int plen, nlen;
539 if (!p)
540 return 0;
542 if (p > haystack->buf && p[-1] != '/')
543 return 0;
545 plen = strlen(p);
546 nlen = strlen(needle);
547 if (plen > nlen && p[nlen] != '/')
548 return 0;
550 strbuf_splice(haystack, p - haystack->buf, nlen,
551 placeholder, strlen(placeholder));
552 return 1;
555 static void print_compact(struct strbuf *display,
556 const char *remote, const char *local)
558 struct strbuf r = STRBUF_INIT;
559 struct strbuf l = STRBUF_INIT;
561 if (!strcmp(remote, local)) {
562 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
563 return;
566 strbuf_addstr(&r, remote);
567 strbuf_addstr(&l, local);
569 if (!find_and_replace(&r, local, "*"))
570 find_and_replace(&l, remote, "*");
571 print_remote_to_local(display, r.buf, l.buf);
573 strbuf_release(&r);
574 strbuf_release(&l);
577 static void format_display(struct strbuf *display, char code,
578 const char *summary, const char *error,
579 const char *remote, const char *local,
580 int summary_width)
582 int width = (summary_width + strlen(summary) - gettext_width(summary));
584 strbuf_addf(display, "%c %-*s ", code, width, summary);
585 if (!compact_format)
586 print_remote_to_local(display, remote, local);
587 else
588 print_compact(display, remote, local);
589 if (error)
590 strbuf_addf(display, " (%s)", error);
593 static int update_local_ref(struct ref *ref,
594 const char *remote,
595 const struct ref *remote_ref,
596 struct strbuf *display,
597 int summary_width)
599 struct commit *current = NULL, *updated;
600 enum object_type type;
601 struct branch *current_branch = branch_get(NULL);
602 const char *pretty_ref = prettify_refname(ref->name);
604 type = sha1_object_info(ref->new_oid.hash, NULL);
605 if (type < 0)
606 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
608 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
609 if (verbosity > 0)
610 format_display(display, '=', _("[up to date]"), NULL,
611 remote, pretty_ref, summary_width);
612 return 0;
615 if (current_branch &&
616 !strcmp(ref->name, current_branch->name) &&
617 !(update_head_ok || is_bare_repository()) &&
618 !is_null_oid(&ref->old_oid)) {
620 * If this is the head, and it's not okay to update
621 * the head, and the old value of the head isn't empty...
623 format_display(display, '!', _("[rejected]"),
624 _("can't fetch in current branch"),
625 remote, pretty_ref, summary_width);
626 return 1;
629 if (!is_null_oid(&ref->old_oid) &&
630 starts_with(ref->name, "refs/tags/")) {
631 int r;
632 r = s_update_ref("updating tag", ref, 0);
633 format_display(display, r ? '!' : 't', _("[tag update]"),
634 r ? _("unable to update local ref") : NULL,
635 remote, pretty_ref, summary_width);
636 return r;
639 current = lookup_commit_reference_gently(ref->old_oid.hash, 1);
640 updated = lookup_commit_reference_gently(ref->new_oid.hash, 1);
641 if (!current || !updated) {
642 const char *msg;
643 const char *what;
644 int r;
646 * Nicely describe the new ref we're fetching.
647 * Base this on the remote's ref name, as it's
648 * more likely to follow a standard layout.
650 const char *name = remote_ref ? remote_ref->name : "";
651 if (starts_with(name, "refs/tags/")) {
652 msg = "storing tag";
653 what = _("[new tag]");
654 } else if (starts_with(name, "refs/heads/")) {
655 msg = "storing head";
656 what = _("[new branch]");
657 } else {
658 msg = "storing ref";
659 what = _("[new ref]");
662 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
663 (recurse_submodules != RECURSE_SUBMODULES_ON))
664 check_for_new_submodule_commits(&ref->new_oid);
665 r = s_update_ref(msg, ref, 0);
666 format_display(display, r ? '!' : '*', what,
667 r ? _("unable to update local ref") : NULL,
668 remote, pretty_ref, summary_width);
669 return r;
672 if (in_merge_bases(current, updated)) {
673 struct strbuf quickref = STRBUF_INIT;
674 int r;
675 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
676 strbuf_addstr(&quickref, "..");
677 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
678 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
679 (recurse_submodules != RECURSE_SUBMODULES_ON))
680 check_for_new_submodule_commits(&ref->new_oid);
681 r = s_update_ref("fast-forward", ref, 1);
682 format_display(display, r ? '!' : ' ', quickref.buf,
683 r ? _("unable to update local ref") : NULL,
684 remote, pretty_ref, summary_width);
685 strbuf_release(&quickref);
686 return r;
687 } else if (force || ref->force) {
688 struct strbuf quickref = STRBUF_INIT;
689 int r;
690 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
691 strbuf_addstr(&quickref, "...");
692 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
693 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
694 (recurse_submodules != RECURSE_SUBMODULES_ON))
695 check_for_new_submodule_commits(&ref->new_oid);
696 r = s_update_ref("forced-update", ref, 1);
697 format_display(display, r ? '!' : '+', quickref.buf,
698 r ? _("unable to update local ref") : _("forced update"),
699 remote, pretty_ref, summary_width);
700 strbuf_release(&quickref);
701 return r;
702 } else {
703 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
704 remote, pretty_ref, summary_width);
705 return 1;
709 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
711 struct ref **rm = cb_data;
712 struct ref *ref = *rm;
714 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
715 ref = ref->next;
716 if (!ref)
717 return -1; /* end of the list */
718 *rm = ref->next;
719 hashcpy(sha1, ref->old_oid.hash);
720 return 0;
723 static int store_updated_refs(const char *raw_url, const char *remote_name,
724 struct ref *ref_map)
726 FILE *fp;
727 struct commit *commit;
728 int url_len, i, rc = 0;
729 struct strbuf note = STRBUF_INIT;
730 const char *what, *kind;
731 struct ref *rm;
732 char *url;
733 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
734 int want_status;
735 int summary_width = transport_summary_width(ref_map);
737 fp = fopen(filename, "a");
738 if (!fp)
739 return error_errno(_("cannot open %s"), filename);
741 if (raw_url)
742 url = transport_anonymize_url(raw_url);
743 else
744 url = xstrdup("foreign");
746 rm = ref_map;
747 if (check_connected(iterate_ref_map, &rm, NULL)) {
748 rc = error(_("%s did not send all necessary objects\n"), url);
749 goto abort;
752 prepare_format_display(ref_map);
755 * We do a pass for each fetch_head_status type in their enum order, so
756 * merged entries are written before not-for-merge. That lets readers
757 * use FETCH_HEAD as a refname to refer to the ref to be merged.
759 for (want_status = FETCH_HEAD_MERGE;
760 want_status <= FETCH_HEAD_IGNORE;
761 want_status++) {
762 for (rm = ref_map; rm; rm = rm->next) {
763 struct ref *ref = NULL;
764 const char *merge_status_marker = "";
766 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
767 if (want_status == FETCH_HEAD_MERGE)
768 warning(_("reject %s because shallow roots are not allowed to be updated"),
769 rm->peer_ref ? rm->peer_ref->name : rm->name);
770 continue;
773 commit = lookup_commit_reference_gently(rm->old_oid.hash, 1);
774 if (!commit)
775 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
777 if (rm->fetch_head_status != want_status)
778 continue;
780 if (rm->peer_ref) {
781 ref = alloc_ref(rm->peer_ref->name);
782 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
783 oidcpy(&ref->new_oid, &rm->old_oid);
784 ref->force = rm->peer_ref->force;
788 if (!strcmp(rm->name, "HEAD")) {
789 kind = "";
790 what = "";
792 else if (starts_with(rm->name, "refs/heads/")) {
793 kind = "branch";
794 what = rm->name + 11;
796 else if (starts_with(rm->name, "refs/tags/")) {
797 kind = "tag";
798 what = rm->name + 10;
800 else if (starts_with(rm->name, "refs/remotes/")) {
801 kind = "remote-tracking branch";
802 what = rm->name + 13;
804 else {
805 kind = "";
806 what = rm->name;
809 url_len = strlen(url);
810 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
812 url_len = i + 1;
813 if (4 < i && !strncmp(".git", url + i - 3, 4))
814 url_len = i - 3;
816 strbuf_reset(&note);
817 if (*what) {
818 if (*kind)
819 strbuf_addf(&note, "%s ", kind);
820 strbuf_addf(&note, "'%s' of ", what);
822 switch (rm->fetch_head_status) {
823 case FETCH_HEAD_NOT_FOR_MERGE:
824 merge_status_marker = "not-for-merge";
825 /* fall-through */
826 case FETCH_HEAD_MERGE:
827 fprintf(fp, "%s\t%s\t%s",
828 oid_to_hex(&rm->old_oid),
829 merge_status_marker,
830 note.buf);
831 for (i = 0; i < url_len; ++i)
832 if ('\n' == url[i])
833 fputs("\\n", fp);
834 else
835 fputc(url[i], fp);
836 fputc('\n', fp);
837 break;
838 default:
839 /* do not write anything to FETCH_HEAD */
840 break;
843 strbuf_reset(&note);
844 if (ref) {
845 rc |= update_local_ref(ref, what, rm, &note,
846 summary_width);
847 free(ref);
848 } else
849 format_display(&note, '*',
850 *kind ? kind : "branch", NULL,
851 *what ? what : "HEAD",
852 "FETCH_HEAD", summary_width);
853 if (note.len) {
854 if (verbosity >= 0 && !shown_url) {
855 fprintf(stderr, _("From %.*s\n"),
856 url_len, url);
857 shown_url = 1;
859 if (verbosity >= 0)
860 fprintf(stderr, " %s\n", note.buf);
865 if (rc & STORE_REF_ERROR_DF_CONFLICT)
866 error(_("some local refs could not be updated; try running\n"
867 " 'git remote prune %s' to remove any old, conflicting "
868 "branches"), remote_name);
870 abort:
871 strbuf_release(&note);
872 free(url);
873 fclose(fp);
874 return rc;
878 * We would want to bypass the object transfer altogether if
879 * everything we are going to fetch already exists and is connected
880 * locally.
882 static int quickfetch(struct ref *ref_map)
884 struct ref *rm = ref_map;
885 struct check_connected_options opt = CHECK_CONNECTED_INIT;
888 * If we are deepening a shallow clone we already have these
889 * objects reachable. Running rev-list here will return with
890 * a good (0) exit status and we'll bypass the fetch that we
891 * really need to perform. Claiming failure now will ensure
892 * we perform the network exchange to deepen our history.
894 if (deepen)
895 return -1;
896 opt.quiet = 1;
897 return check_connected(iterate_ref_map, &rm, &opt);
900 static int fetch_refs(struct transport *transport, struct ref *ref_map)
902 int ret = quickfetch(ref_map);
903 if (ret)
904 ret = transport_fetch_refs(transport, ref_map);
905 if (!ret)
906 ret |= store_updated_refs(transport->url,
907 transport->remote->name,
908 ref_map);
909 transport_unlock_pack(transport);
910 return ret;
913 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
914 const char *raw_url)
916 int url_len, i, result = 0;
917 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
918 char *url;
919 int summary_width = transport_summary_width(stale_refs);
920 const char *dangling_msg = dry_run
921 ? _(" (%s will become dangling)")
922 : _(" (%s has become dangling)");
924 if (raw_url)
925 url = transport_anonymize_url(raw_url);
926 else
927 url = xstrdup("foreign");
929 url_len = strlen(url);
930 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
933 url_len = i + 1;
934 if (4 < i && !strncmp(".git", url + i - 3, 4))
935 url_len = i - 3;
937 if (!dry_run) {
938 struct string_list refnames = STRING_LIST_INIT_NODUP;
940 for (ref = stale_refs; ref; ref = ref->next)
941 string_list_append(&refnames, ref->name);
943 result = delete_refs(&refnames, 0);
944 string_list_clear(&refnames, 0);
947 if (verbosity >= 0) {
948 for (ref = stale_refs; ref; ref = ref->next) {
949 struct strbuf sb = STRBUF_INIT;
950 if (!shown_url) {
951 fprintf(stderr, _("From %.*s\n"), url_len, url);
952 shown_url = 1;
954 format_display(&sb, '-', _("[deleted]"), NULL,
955 _("(none)"), prettify_refname(ref->name),
956 summary_width);
957 fprintf(stderr, " %s\n",sb.buf);
958 strbuf_release(&sb);
959 warn_dangling_symref(stderr, dangling_msg, ref->name);
963 free(url);
964 free_refs(stale_refs);
965 return result;
968 static void check_not_current_branch(struct ref *ref_map)
970 struct branch *current_branch = branch_get(NULL);
972 if (is_bare_repository() || !current_branch)
973 return;
975 for (; ref_map; ref_map = ref_map->next)
976 if (ref_map->peer_ref && !strcmp(current_branch->refname,
977 ref_map->peer_ref->name))
978 die(_("Refusing to fetch into current branch %s "
979 "of non-bare repository"), current_branch->refname);
982 static int truncate_fetch_head(void)
984 const char *filename = git_path_fetch_head();
985 FILE *fp = fopen_for_writing(filename);
987 if (!fp)
988 return error_errno(_("cannot open %s"), filename);
989 fclose(fp);
990 return 0;
993 static void set_option(struct transport *transport, const char *name, const char *value)
995 int r = transport_set_option(transport, name, value);
996 if (r < 0)
997 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
998 name, value, transport->url);
999 if (r > 0)
1000 warning(_("Option \"%s\" is ignored for %s\n"),
1001 name, transport->url);
1004 static struct transport *prepare_transport(struct remote *remote, int deepen)
1006 struct transport *transport;
1007 transport = transport_get(remote, NULL);
1008 transport_set_verbosity(transport, verbosity, progress);
1009 transport->family = family;
1010 if (upload_pack)
1011 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1012 if (keep)
1013 set_option(transport, TRANS_OPT_KEEP, "yes");
1014 if (depth)
1015 set_option(transport, TRANS_OPT_DEPTH, depth);
1016 if (deepen && deepen_since)
1017 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1018 if (deepen && deepen_not.nr)
1019 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1020 (const char *)&deepen_not);
1021 if (deepen_relative)
1022 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1023 if (update_shallow)
1024 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1025 return transport;
1028 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1030 int cannot_reuse;
1033 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1034 * when remote helper is used (setting it to an empty string
1035 * is not unsetting). We could extend the remote helper
1036 * protocol for that, but for now, just force a new connection
1037 * without deepen-since. Similar story for deepen-not.
1039 cannot_reuse = transport->cannot_reuse ||
1040 deepen_since || deepen_not.nr;
1041 if (cannot_reuse) {
1042 gsecondary = prepare_transport(transport->remote, 0);
1043 transport = gsecondary;
1046 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1047 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1048 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1049 fetch_refs(transport, ref_map);
1051 if (gsecondary) {
1052 transport_disconnect(gsecondary);
1053 gsecondary = NULL;
1057 static int do_fetch(struct transport *transport,
1058 struct refspec *refs, int ref_count)
1060 struct string_list existing_refs = STRING_LIST_INIT_DUP;
1061 struct ref *ref_map;
1062 struct ref *rm;
1063 int autotags = (transport->remote->fetch_tags == 1);
1064 int retcode = 0;
1066 for_each_ref(add_existing, &existing_refs);
1068 if (tags == TAGS_DEFAULT) {
1069 if (transport->remote->fetch_tags == 2)
1070 tags = TAGS_SET;
1071 if (transport->remote->fetch_tags == -1)
1072 tags = TAGS_UNSET;
1075 if (!transport->get_refs_list || !transport->fetch)
1076 die(_("Don't know how to fetch from %s"), transport->url);
1078 /* if not appending, truncate FETCH_HEAD */
1079 if (!append && !dry_run) {
1080 retcode = truncate_fetch_head();
1081 if (retcode)
1082 goto cleanup;
1085 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
1086 if (!update_head_ok)
1087 check_not_current_branch(ref_map);
1089 for (rm = ref_map; rm; rm = rm->next) {
1090 if (rm->peer_ref) {
1091 struct string_list_item *peer_item =
1092 string_list_lookup(&existing_refs,
1093 rm->peer_ref->name);
1094 if (peer_item) {
1095 struct object_id *old_oid = peer_item->util;
1096 oidcpy(&rm->peer_ref->old_oid, old_oid);
1101 if (tags == TAGS_DEFAULT && autotags)
1102 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1103 if (prune) {
1105 * We only prune based on refspecs specified
1106 * explicitly (via command line or configuration); we
1107 * don't care whether --tags was specified.
1109 if (ref_count) {
1110 prune_refs(refs, ref_count, ref_map, transport->url);
1111 } else {
1112 prune_refs(transport->remote->fetch,
1113 transport->remote->fetch_refspec_nr,
1114 ref_map,
1115 transport->url);
1118 if (fetch_refs(transport, ref_map)) {
1119 free_refs(ref_map);
1120 retcode = 1;
1121 goto cleanup;
1123 free_refs(ref_map);
1125 /* if neither --no-tags nor --tags was specified, do automated tag
1126 * following ... */
1127 if (tags == TAGS_DEFAULT && autotags) {
1128 struct ref **tail = &ref_map;
1129 ref_map = NULL;
1130 find_non_local_tags(transport, &ref_map, &tail);
1131 if (ref_map)
1132 backfill_tags(transport, ref_map);
1133 free_refs(ref_map);
1136 cleanup:
1137 string_list_clear(&existing_refs, 1);
1138 return retcode;
1141 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1143 struct string_list *list = priv;
1144 if (!remote->skip_default_update)
1145 string_list_append(list, remote->name);
1146 return 0;
1149 struct remote_group_data {
1150 const char *name;
1151 struct string_list *list;
1154 static int get_remote_group(const char *key, const char *value, void *priv)
1156 struct remote_group_data *g = priv;
1158 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1159 /* split list by white space */
1160 while (*value) {
1161 size_t wordlen = strcspn(value, " \t\n");
1163 if (wordlen >= 1)
1164 string_list_append_nodup(g->list,
1165 xstrndup(value, wordlen));
1166 value += wordlen + (value[wordlen] != '\0');
1170 return 0;
1173 static int add_remote_or_group(const char *name, struct string_list *list)
1175 int prev_nr = list->nr;
1176 struct remote_group_data g;
1177 g.name = name; g.list = list;
1179 git_config(get_remote_group, &g);
1180 if (list->nr == prev_nr) {
1181 struct remote *remote = remote_get(name);
1182 if (!remote_is_configured(remote, 0))
1183 return 0;
1184 string_list_append(list, remote->name);
1186 return 1;
1189 static void add_options_to_argv(struct argv_array *argv)
1191 if (dry_run)
1192 argv_array_push(argv, "--dry-run");
1193 if (prune != -1)
1194 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1195 if (update_head_ok)
1196 argv_array_push(argv, "--update-head-ok");
1197 if (force)
1198 argv_array_push(argv, "--force");
1199 if (keep)
1200 argv_array_push(argv, "--keep");
1201 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1202 argv_array_push(argv, "--recurse-submodules");
1203 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1204 argv_array_push(argv, "--recurse-submodules=on-demand");
1205 if (tags == TAGS_SET)
1206 argv_array_push(argv, "--tags");
1207 else if (tags == TAGS_UNSET)
1208 argv_array_push(argv, "--no-tags");
1209 if (verbosity >= 2)
1210 argv_array_push(argv, "-v");
1211 if (verbosity >= 1)
1212 argv_array_push(argv, "-v");
1213 else if (verbosity < 0)
1214 argv_array_push(argv, "-q");
1218 static int fetch_multiple(struct string_list *list)
1220 int i, result = 0;
1221 struct argv_array argv = ARGV_ARRAY_INIT;
1223 if (!append && !dry_run) {
1224 int errcode = truncate_fetch_head();
1225 if (errcode)
1226 return errcode;
1229 argv_array_pushl(&argv, "fetch", "--append", NULL);
1230 add_options_to_argv(&argv);
1232 for (i = 0; i < list->nr; i++) {
1233 const char *name = list->items[i].string;
1234 argv_array_push(&argv, name);
1235 if (verbosity >= 0)
1236 printf(_("Fetching %s\n"), name);
1237 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1238 error(_("Could not fetch %s"), name);
1239 result = 1;
1241 argv_array_pop(&argv);
1244 argv_array_clear(&argv);
1245 return result;
1248 static int fetch_one(struct remote *remote, int argc, const char **argv)
1250 static const char **refs = NULL;
1251 struct refspec *refspec;
1252 int ref_nr = 0;
1253 int exit_code;
1255 if (!remote)
1256 die(_("No remote repository specified. Please, specify either a URL or a\n"
1257 "remote name from which new revisions should be fetched."));
1259 gtransport = prepare_transport(remote, 1);
1261 if (prune < 0) {
1262 /* no command line request */
1263 if (0 <= gtransport->remote->prune)
1264 prune = gtransport->remote->prune;
1265 else if (0 <= fetch_prune_config)
1266 prune = fetch_prune_config;
1267 else
1268 prune = PRUNE_BY_DEFAULT;
1271 if (argc > 0) {
1272 int j = 0;
1273 int i;
1274 refs = xcalloc(st_add(argc, 1), sizeof(const char *));
1275 for (i = 0; i < argc; i++) {
1276 if (!strcmp(argv[i], "tag")) {
1277 i++;
1278 if (i >= argc)
1279 die(_("You need to specify a tag name."));
1280 refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
1281 argv[i], argv[i]);
1282 } else
1283 refs[j++] = argv[i];
1285 refs[j] = NULL;
1286 ref_nr = j;
1289 sigchain_push_common(unlock_pack_on_signal);
1290 atexit(unlock_pack);
1291 refspec = parse_fetch_refspec(ref_nr, refs);
1292 exit_code = do_fetch(gtransport, refspec, ref_nr);
1293 free_refspec(ref_nr, refspec);
1294 transport_disconnect(gtransport);
1295 gtransport = NULL;
1296 return exit_code;
1299 int cmd_fetch(int argc, const char **argv, const char *prefix)
1301 int i;
1302 struct string_list list = STRING_LIST_INIT_DUP;
1303 struct remote *remote;
1304 int result = 0;
1305 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1307 packet_trace_identity("fetch");
1309 /* Record the command line for the reflog */
1310 strbuf_addstr(&default_rla, "fetch");
1311 for (i = 1; i < argc; i++)
1312 strbuf_addf(&default_rla, " %s", argv[i]);
1314 git_config(git_fetch_config, NULL);
1316 argc = parse_options(argc, argv, prefix,
1317 builtin_fetch_options, builtin_fetch_usage, 0);
1319 if (deepen_relative) {
1320 if (deepen_relative < 0)
1321 die(_("Negative depth in --deepen is not supported"));
1322 if (depth)
1323 die(_("--deepen and --depth are mutually exclusive"));
1324 depth = xstrfmt("%d", deepen_relative);
1326 if (unshallow) {
1327 if (depth)
1328 die(_("--depth and --unshallow cannot be used together"));
1329 else if (!is_repository_shallow())
1330 die(_("--unshallow on a complete repository does not make sense"));
1331 else
1332 depth = xstrfmt("%d", INFINITE_DEPTH);
1335 /* no need to be strict, transport_set_option() will validate it again */
1336 if (depth && atoi(depth) < 1)
1337 die(_("depth %s is not a positive number"), depth);
1338 if (depth || deepen_since || deepen_not.nr)
1339 deepen = 1;
1341 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1342 if (recurse_submodules_default) {
1343 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1344 set_config_fetch_recurse_submodules(arg);
1346 gitmodules_config();
1347 git_config(submodule_config, NULL);
1350 if (all) {
1351 if (argc == 1)
1352 die(_("fetch --all does not take a repository argument"));
1353 else if (argc > 1)
1354 die(_("fetch --all does not make sense with refspecs"));
1355 (void) for_each_remote(get_one_remote_for_fetch, &list);
1356 result = fetch_multiple(&list);
1357 } else if (argc == 0) {
1358 /* No arguments -- use default remote */
1359 remote = remote_get(NULL);
1360 result = fetch_one(remote, argc, argv);
1361 } else if (multiple) {
1362 /* All arguments are assumed to be remotes or groups */
1363 for (i = 0; i < argc; i++)
1364 if (!add_remote_or_group(argv[i], &list))
1365 die(_("No such remote or remote group: %s"), argv[i]);
1366 result = fetch_multiple(&list);
1367 } else {
1368 /* Single remote or group */
1369 (void) add_remote_or_group(argv[0], &list);
1370 if (list.nr > 1) {
1371 /* More than one remote */
1372 if (argc > 1)
1373 die(_("Fetching a group and specifying refspecs does not make sense"));
1374 result = fetch_multiple(&list);
1375 } else {
1376 /* Zero or one remotes */
1377 remote = remote_get(argv[0]);
1378 result = fetch_one(remote, argc-1, argv+1);
1382 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1383 struct argv_array options = ARGV_ARRAY_INIT;
1385 add_options_to_argv(&options);
1386 result = fetch_populated_submodules(&options,
1387 submodule_prefix,
1388 recurse_submodules,
1389 verbosity < 0,
1390 max_children);
1391 argv_array_clear(&options);
1394 string_list_clear(&list, 0);
1396 close_all_packs();
1398 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1399 if (verbosity < 0)
1400 argv_array_push(&argv_gc_auto, "--quiet");
1401 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1402 argv_array_clear(&argv_gc_auto);
1404 return result;