Merge branch 'sb/sha1-file-cleanup' into maint
[git/debian.git] / builtin / fetch.c
blobc87e59f3b1def1f064e0dae54a14e310c06df1fa
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "refs.h"
7 #include "commit.h"
8 #include "builtin.h"
9 #include "string-list.h"
10 #include "remote.h"
11 #include "transport.h"
12 #include "run-command.h"
13 #include "parse-options.h"
14 #include "sigchain.h"
15 #include "submodule-config.h"
16 #include "submodule.h"
17 #include "connected.h"
18 #include "argv-array.h"
19 #include "utf8.h"
21 static const char * const builtin_fetch_usage[] = {
22 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
23 N_("git fetch [<options>] <group>"),
24 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
25 N_("git fetch --all [<options>]"),
26 NULL
29 enum {
30 TAGS_UNSET = 0,
31 TAGS_DEFAULT = 1,
32 TAGS_SET = 2
35 static int fetch_prune_config = -1; /* unspecified */
36 static int prune = -1; /* unspecified */
37 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
39 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
40 static int progress = -1;
41 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
42 static int max_children = -1;
43 static enum transport_family family;
44 static const char *depth;
45 static const char *deepen_since;
46 static const char *upload_pack;
47 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
48 static struct strbuf default_rla = STRBUF_INIT;
49 static struct transport *gtransport;
50 static struct transport *gsecondary;
51 static const char *submodule_prefix = "";
52 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
53 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
54 static int shown_url = 0;
55 static int refmap_alloc, refmap_nr;
56 static const char **refmap_array;
58 static int git_fetch_config(const char *k, const char *v, void *cb)
60 if (!strcmp(k, "fetch.prune")) {
61 fetch_prune_config = git_config_bool(k, v);
62 return 0;
65 if (!strcmp(k, "submodule.recurse")) {
66 int r = git_config_bool(k, v) ?
67 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
68 recurse_submodules = r;
71 return git_default_config(k, v, cb);
74 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
76 ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
79 * "git fetch --refmap='' origin foo"
80 * can be used to tell the command not to store anywhere
82 if (*arg)
83 refmap_array[refmap_nr++] = arg;
84 return 0;
87 static struct option builtin_fetch_options[] = {
88 OPT__VERBOSITY(&verbosity),
89 OPT_BOOL(0, "all", &all,
90 N_("fetch from all remotes")),
91 OPT_BOOL('a', "append", &append,
92 N_("append to .git/FETCH_HEAD instead of overwriting")),
93 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
94 N_("path to upload pack on remote end")),
95 OPT__FORCE(&force, N_("force overwrite of local branch")),
96 OPT_BOOL('m', "multiple", &multiple,
97 N_("fetch from multiple remotes")),
98 OPT_SET_INT('t', "tags", &tags,
99 N_("fetch all tags and associated objects"), TAGS_SET),
100 OPT_SET_INT('n', NULL, &tags,
101 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
102 OPT_INTEGER('j', "jobs", &max_children,
103 N_("number of submodules fetched in parallel")),
104 OPT_BOOL('p', "prune", &prune,
105 N_("prune remote-tracking branches no longer on remote")),
106 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
107 N_("control recursive fetching of submodules"),
108 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
109 OPT_BOOL(0, "dry-run", &dry_run,
110 N_("dry run")),
111 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
112 OPT_BOOL('u', "update-head-ok", &update_head_ok,
113 N_("allow updating of HEAD ref")),
114 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
115 OPT_STRING(0, "depth", &depth, N_("depth"),
116 N_("deepen history of shallow clone")),
117 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
118 N_("deepen history of shallow repository based on time")),
119 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
120 N_("deepen history of shallow clone, excluding rev")),
121 OPT_INTEGER(0, "deepen", &deepen_relative,
122 N_("deepen history of shallow clone")),
123 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
124 N_("convert to a complete repository"),
125 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
126 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
127 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
128 { OPTION_CALLBACK, 0, "recurse-submodules-default",
129 &recurse_submodules_default, N_("on-demand"),
130 N_("default for recursive fetching of submodules "
131 "(lower priority than config files)"),
132 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
133 OPT_BOOL(0, "update-shallow", &update_shallow,
134 N_("accept refs that update .git/shallow")),
135 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
136 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
137 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
138 TRANSPORT_FAMILY_IPV4),
139 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
140 TRANSPORT_FAMILY_IPV6),
141 OPT_END()
144 static void unlock_pack(void)
146 if (gtransport)
147 transport_unlock_pack(gtransport);
148 if (gsecondary)
149 transport_unlock_pack(gsecondary);
152 static void unlock_pack_on_signal(int signo)
154 unlock_pack();
155 sigchain_pop(signo);
156 raise(signo);
159 static void add_merge_config(struct ref **head,
160 const struct ref *remote_refs,
161 struct branch *branch,
162 struct ref ***tail)
164 int i;
166 for (i = 0; i < branch->merge_nr; i++) {
167 struct ref *rm, **old_tail = *tail;
168 struct refspec refspec;
170 for (rm = *head; rm; rm = rm->next) {
171 if (branch_merge_matches(branch, i, rm->name)) {
172 rm->fetch_head_status = FETCH_HEAD_MERGE;
173 break;
176 if (rm)
177 continue;
180 * Not fetched to a remote-tracking branch? We need to fetch
181 * it anyway to allow this branch's "branch.$name.merge"
182 * to be honored by 'git pull', but we do not have to
183 * fail if branch.$name.merge is misconfigured to point
184 * at a nonexisting branch. If we were indeed called by
185 * 'git pull', it will notice the misconfiguration because
186 * there is no entry in the resulting FETCH_HEAD marked
187 * for merging.
189 memset(&refspec, 0, sizeof(refspec));
190 refspec.src = branch->merge[i]->src;
191 get_fetch_map(remote_refs, &refspec, tail, 1);
192 for (rm = *old_tail; rm; rm = rm->next)
193 rm->fetch_head_status = FETCH_HEAD_MERGE;
197 static int add_existing(const char *refname, const struct object_id *oid,
198 int flag, void *cbdata)
200 struct string_list *list = (struct string_list *)cbdata;
201 struct string_list_item *item = string_list_insert(list, refname);
202 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
204 oidcpy(old_oid, oid);
205 item->util = old_oid;
206 return 0;
209 static int will_fetch(struct ref **head, const unsigned char *sha1)
211 struct ref *rm = *head;
212 while (rm) {
213 if (!hashcmp(rm->old_oid.hash, sha1))
214 return 1;
215 rm = rm->next;
217 return 0;
220 static void find_non_local_tags(struct transport *transport,
221 struct ref **head,
222 struct ref ***tail)
224 struct string_list existing_refs = STRING_LIST_INIT_DUP;
225 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
226 const struct ref *ref;
227 struct string_list_item *item = NULL;
229 for_each_ref(add_existing, &existing_refs);
230 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
231 if (!starts_with(ref->name, "refs/tags/"))
232 continue;
235 * The peeled ref always follows the matching base
236 * ref, so if we see a peeled ref that we don't want
237 * to fetch then we can mark the ref entry in the list
238 * as one to ignore by setting util to NULL.
240 if (ends_with(ref->name, "^{}")) {
241 if (item &&
242 !has_object_file_with_flags(&ref->old_oid,
243 OBJECT_INFO_QUICK) &&
244 !will_fetch(head, ref->old_oid.hash) &&
245 !has_sha1_file_with_flags(item->util,
246 OBJECT_INFO_QUICK) &&
247 !will_fetch(head, item->util))
248 item->util = NULL;
249 item = NULL;
250 continue;
254 * If item is non-NULL here, then we previously saw a
255 * ref not followed by a peeled reference, so we need
256 * to check if it is a lightweight tag that we want to
257 * fetch.
259 if (item &&
260 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
261 !will_fetch(head, item->util))
262 item->util = NULL;
264 item = NULL;
266 /* skip duplicates and refs that we already have */
267 if (string_list_has_string(&remote_refs, ref->name) ||
268 string_list_has_string(&existing_refs, ref->name))
269 continue;
271 item = string_list_insert(&remote_refs, ref->name);
272 item->util = (void *)&ref->old_oid;
274 string_list_clear(&existing_refs, 1);
277 * We may have a final lightweight tag that needs to be
278 * checked to see if it needs fetching.
280 if (item &&
281 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
282 !will_fetch(head, item->util))
283 item->util = NULL;
286 * For all the tags in the remote_refs string list,
287 * add them to the list of refs to be fetched
289 for_each_string_list_item(item, &remote_refs) {
290 /* Unless we have already decided to ignore this item... */
291 if (item->util)
293 struct ref *rm = alloc_ref(item->string);
294 rm->peer_ref = alloc_ref(item->string);
295 oidcpy(&rm->old_oid, item->util);
296 **tail = rm;
297 *tail = &rm->next;
301 string_list_clear(&remote_refs, 0);
304 static struct ref *get_ref_map(struct transport *transport,
305 struct refspec *refspecs, int refspec_count,
306 int tags, int *autotags)
308 int i;
309 struct ref *rm;
310 struct ref *ref_map = NULL;
311 struct ref **tail = &ref_map;
313 /* opportunistically-updated references: */
314 struct ref *orefs = NULL, **oref_tail = &orefs;
316 const struct ref *remote_refs = transport_get_remote_refs(transport);
318 if (refspec_count) {
319 struct refspec *fetch_refspec;
320 int fetch_refspec_nr;
322 for (i = 0; i < refspec_count; i++) {
323 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
324 if (refspecs[i].dst && refspecs[i].dst[0])
325 *autotags = 1;
327 /* Merge everything on the command line (but not --tags) */
328 for (rm = ref_map; rm; rm = rm->next)
329 rm->fetch_head_status = FETCH_HEAD_MERGE;
332 * For any refs that we happen to be fetching via
333 * command-line arguments, the destination ref might
334 * have been missing or have been different than the
335 * remote-tracking ref that would be derived from the
336 * configured refspec. In these cases, we want to
337 * take the opportunity to update their configured
338 * remote-tracking reference. However, we do not want
339 * to mention these entries in FETCH_HEAD at all, as
340 * they would simply be duplicates of existing
341 * entries, so we set them FETCH_HEAD_IGNORE below.
343 * We compute these entries now, based only on the
344 * refspecs specified on the command line. But we add
345 * them to the list following the refspecs resulting
346 * from the tags option so that one of the latter,
347 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
348 * by ref_remove_duplicates() in favor of one of these
349 * opportunistic entries with FETCH_HEAD_IGNORE.
351 if (refmap_array) {
352 fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
353 fetch_refspec_nr = refmap_nr;
354 } else {
355 fetch_refspec = transport->remote->fetch;
356 fetch_refspec_nr = transport->remote->fetch_refspec_nr;
359 for (i = 0; i < fetch_refspec_nr; i++)
360 get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
361 } else if (refmap_array) {
362 die("--refmap option is only meaningful with command-line refspec(s).");
363 } else {
364 /* Use the defaults */
365 struct remote *remote = transport->remote;
366 struct branch *branch = branch_get(NULL);
367 int has_merge = branch_has_merge_config(branch);
368 if (remote &&
369 (remote->fetch_refspec_nr ||
370 /* Note: has_merge implies non-NULL branch->remote_name */
371 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
372 for (i = 0; i < remote->fetch_refspec_nr; i++) {
373 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
374 if (remote->fetch[i].dst &&
375 remote->fetch[i].dst[0])
376 *autotags = 1;
377 if (!i && !has_merge && ref_map &&
378 !remote->fetch[0].pattern)
379 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
382 * if the remote we're fetching from is the same
383 * as given in branch.<name>.remote, we add the
384 * ref given in branch.<name>.merge, too.
386 * Note: has_merge implies non-NULL branch->remote_name
388 if (has_merge &&
389 !strcmp(branch->remote_name, remote->name))
390 add_merge_config(&ref_map, remote_refs, branch, &tail);
391 } else {
392 ref_map = get_remote_ref(remote_refs, "HEAD");
393 if (!ref_map)
394 die(_("Couldn't find remote ref HEAD"));
395 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
396 tail = &ref_map->next;
400 if (tags == TAGS_SET)
401 /* also fetch all tags */
402 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
403 else if (tags == TAGS_DEFAULT && *autotags)
404 find_non_local_tags(transport, &ref_map, &tail);
406 /* Now append any refs to be updated opportunistically: */
407 *tail = orefs;
408 for (rm = orefs; rm; rm = rm->next) {
409 rm->fetch_head_status = FETCH_HEAD_IGNORE;
410 tail = &rm->next;
413 return ref_remove_duplicates(ref_map);
416 #define STORE_REF_ERROR_OTHER 1
417 #define STORE_REF_ERROR_DF_CONFLICT 2
419 static int s_update_ref(const char *action,
420 struct ref *ref,
421 int check_old)
423 char *msg;
424 char *rla = getenv("GIT_REFLOG_ACTION");
425 struct ref_transaction *transaction;
426 struct strbuf err = STRBUF_INIT;
427 int ret, df_conflict = 0;
429 if (dry_run)
430 return 0;
431 if (!rla)
432 rla = default_rla.buf;
433 msg = xstrfmt("%s: %s", rla, action);
435 transaction = ref_transaction_begin(&err);
436 if (!transaction ||
437 ref_transaction_update(transaction, ref->name,
438 ref->new_oid.hash,
439 check_old ? ref->old_oid.hash : NULL,
440 0, msg, &err))
441 goto fail;
443 ret = ref_transaction_commit(transaction, &err);
444 if (ret) {
445 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
446 goto fail;
449 ref_transaction_free(transaction);
450 strbuf_release(&err);
451 free(msg);
452 return 0;
453 fail:
454 ref_transaction_free(transaction);
455 error("%s", err.buf);
456 strbuf_release(&err);
457 free(msg);
458 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
459 : STORE_REF_ERROR_OTHER;
462 static int refcol_width = 10;
463 static int compact_format;
465 static void adjust_refcol_width(const struct ref *ref)
467 int max, rlen, llen, len;
469 /* uptodate lines are only shown on high verbosity level */
470 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
471 return;
473 max = term_columns();
474 rlen = utf8_strwidth(prettify_refname(ref->name));
476 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
479 * rough estimation to see if the output line is too long and
480 * should not be counted (we can't do precise calculation
481 * anyway because we don't know if the error explanation part
482 * will be printed in update_local_ref)
484 if (compact_format) {
485 llen = 0;
486 max = max * 2 / 3;
488 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
489 if (len >= max)
490 return;
493 * Not precise calculation for compact mode because '*' can
494 * appear on the left hand side of '->' and shrink the column
495 * back.
497 if (refcol_width < rlen)
498 refcol_width = rlen;
501 static void prepare_format_display(struct ref *ref_map)
503 struct ref *rm;
504 const char *format = "full";
506 git_config_get_string_const("fetch.output", &format);
507 if (!strcasecmp(format, "full"))
508 compact_format = 0;
509 else if (!strcasecmp(format, "compact"))
510 compact_format = 1;
511 else
512 die(_("configuration fetch.output contains invalid value %s"),
513 format);
515 for (rm = ref_map; rm; rm = rm->next) {
516 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
517 !rm->peer_ref ||
518 !strcmp(rm->name, "HEAD"))
519 continue;
521 adjust_refcol_width(rm);
525 static void print_remote_to_local(struct strbuf *display,
526 const char *remote, const char *local)
528 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
531 static int find_and_replace(struct strbuf *haystack,
532 const char *needle,
533 const char *placeholder)
535 const char *p = strstr(haystack->buf, needle);
536 int plen, nlen;
538 if (!p)
539 return 0;
541 if (p > haystack->buf && p[-1] != '/')
542 return 0;
544 plen = strlen(p);
545 nlen = strlen(needle);
546 if (plen > nlen && p[nlen] != '/')
547 return 0;
549 strbuf_splice(haystack, p - haystack->buf, nlen,
550 placeholder, strlen(placeholder));
551 return 1;
554 static void print_compact(struct strbuf *display,
555 const char *remote, const char *local)
557 struct strbuf r = STRBUF_INIT;
558 struct strbuf l = STRBUF_INIT;
560 if (!strcmp(remote, local)) {
561 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
562 return;
565 strbuf_addstr(&r, remote);
566 strbuf_addstr(&l, local);
568 if (!find_and_replace(&r, local, "*"))
569 find_and_replace(&l, remote, "*");
570 print_remote_to_local(display, r.buf, l.buf);
572 strbuf_release(&r);
573 strbuf_release(&l);
576 static void format_display(struct strbuf *display, char code,
577 const char *summary, const char *error,
578 const char *remote, const char *local,
579 int summary_width)
581 int width = (summary_width + strlen(summary) - gettext_width(summary));
583 strbuf_addf(display, "%c %-*s ", code, width, summary);
584 if (!compact_format)
585 print_remote_to_local(display, remote, local);
586 else
587 print_compact(display, remote, local);
588 if (error)
589 strbuf_addf(display, " (%s)", error);
592 static int update_local_ref(struct ref *ref,
593 const char *remote,
594 const struct ref *remote_ref,
595 struct strbuf *display,
596 int summary_width)
598 struct commit *current = NULL, *updated;
599 enum object_type type;
600 struct branch *current_branch = branch_get(NULL);
601 const char *pretty_ref = prettify_refname(ref->name);
603 type = sha1_object_info(ref->new_oid.hash, NULL);
604 if (type < 0)
605 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
607 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
608 if (verbosity > 0)
609 format_display(display, '=', _("[up to date]"), NULL,
610 remote, pretty_ref, summary_width);
611 return 0;
614 if (current_branch &&
615 !strcmp(ref->name, current_branch->name) &&
616 !(update_head_ok || is_bare_repository()) &&
617 !is_null_oid(&ref->old_oid)) {
619 * If this is the head, and it's not okay to update
620 * the head, and the old value of the head isn't empty...
622 format_display(display, '!', _("[rejected]"),
623 _("can't fetch in current branch"),
624 remote, pretty_ref, summary_width);
625 return 1;
628 if (!is_null_oid(&ref->old_oid) &&
629 starts_with(ref->name, "refs/tags/")) {
630 int r;
631 r = s_update_ref("updating tag", ref, 0);
632 format_display(display, r ? '!' : 't', _("[tag update]"),
633 r ? _("unable to update local ref") : NULL,
634 remote, pretty_ref, summary_width);
635 return r;
638 current = lookup_commit_reference_gently(&ref->old_oid, 1);
639 updated = lookup_commit_reference_gently(&ref->new_oid, 1);
640 if (!current || !updated) {
641 const char *msg;
642 const char *what;
643 int r;
645 * Nicely describe the new ref we're fetching.
646 * Base this on the remote's ref name, as it's
647 * more likely to follow a standard layout.
649 const char *name = remote_ref ? remote_ref->name : "";
650 if (starts_with(name, "refs/tags/")) {
651 msg = "storing tag";
652 what = _("[new tag]");
653 } else if (starts_with(name, "refs/heads/")) {
654 msg = "storing head";
655 what = _("[new branch]");
656 } else {
657 msg = "storing ref";
658 what = _("[new ref]");
661 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
662 (recurse_submodules != RECURSE_SUBMODULES_ON))
663 check_for_new_submodule_commits(&ref->new_oid);
664 r = s_update_ref(msg, ref, 0);
665 format_display(display, r ? '!' : '*', what,
666 r ? _("unable to update local ref") : NULL,
667 remote, pretty_ref, summary_width);
668 return r;
671 if (in_merge_bases(current, updated)) {
672 struct strbuf quickref = STRBUF_INIT;
673 int r;
674 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
675 strbuf_addstr(&quickref, "..");
676 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
677 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
678 (recurse_submodules != RECURSE_SUBMODULES_ON))
679 check_for_new_submodule_commits(&ref->new_oid);
680 r = s_update_ref("fast-forward", ref, 1);
681 format_display(display, r ? '!' : ' ', quickref.buf,
682 r ? _("unable to update local ref") : NULL,
683 remote, pretty_ref, summary_width);
684 strbuf_release(&quickref);
685 return r;
686 } else if (force || ref->force) {
687 struct strbuf quickref = STRBUF_INIT;
688 int r;
689 strbuf_add_unique_abbrev(&quickref, current->object.oid.hash, DEFAULT_ABBREV);
690 strbuf_addstr(&quickref, "...");
691 strbuf_add_unique_abbrev(&quickref, ref->new_oid.hash, DEFAULT_ABBREV);
692 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
693 (recurse_submodules != RECURSE_SUBMODULES_ON))
694 check_for_new_submodule_commits(&ref->new_oid);
695 r = s_update_ref("forced-update", ref, 1);
696 format_display(display, r ? '!' : '+', quickref.buf,
697 r ? _("unable to update local ref") : _("forced update"),
698 remote, pretty_ref, summary_width);
699 strbuf_release(&quickref);
700 return r;
701 } else {
702 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
703 remote, pretty_ref, summary_width);
704 return 1;
708 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
710 struct ref **rm = cb_data;
711 struct ref *ref = *rm;
713 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
714 ref = ref->next;
715 if (!ref)
716 return -1; /* end of the list */
717 *rm = ref->next;
718 hashcpy(sha1, ref->old_oid.hash);
719 return 0;
722 static int store_updated_refs(const char *raw_url, const char *remote_name,
723 struct ref *ref_map)
725 FILE *fp;
726 struct commit *commit;
727 int url_len, i, rc = 0;
728 struct strbuf note = STRBUF_INIT;
729 const char *what, *kind;
730 struct ref *rm;
731 char *url;
732 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head();
733 int want_status;
734 int summary_width = transport_summary_width(ref_map);
736 fp = fopen(filename, "a");
737 if (!fp)
738 return error_errno(_("cannot open %s"), filename);
740 if (raw_url)
741 url = transport_anonymize_url(raw_url);
742 else
743 url = xstrdup("foreign");
745 rm = ref_map;
746 if (check_connected(iterate_ref_map, &rm, NULL)) {
747 rc = error(_("%s did not send all necessary objects\n"), url);
748 goto abort;
751 prepare_format_display(ref_map);
754 * We do a pass for each fetch_head_status type in their enum order, so
755 * merged entries are written before not-for-merge. That lets readers
756 * use FETCH_HEAD as a refname to refer to the ref to be merged.
758 for (want_status = FETCH_HEAD_MERGE;
759 want_status <= FETCH_HEAD_IGNORE;
760 want_status++) {
761 for (rm = ref_map; rm; rm = rm->next) {
762 struct ref *ref = NULL;
763 const char *merge_status_marker = "";
765 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
766 if (want_status == FETCH_HEAD_MERGE)
767 warning(_("reject %s because shallow roots are not allowed to be updated"),
768 rm->peer_ref ? rm->peer_ref->name : rm->name);
769 continue;
772 commit = lookup_commit_reference_gently(&rm->old_oid,
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("fetch: prune", &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 set_config_fetch_recurse_submodules(recurse_submodules_default);
1343 gitmodules_config();
1344 git_config(submodule_config, NULL);
1347 if (all) {
1348 if (argc == 1)
1349 die(_("fetch --all does not take a repository argument"));
1350 else if (argc > 1)
1351 die(_("fetch --all does not make sense with refspecs"));
1352 (void) for_each_remote(get_one_remote_for_fetch, &list);
1353 result = fetch_multiple(&list);
1354 } else if (argc == 0) {
1355 /* No arguments -- use default remote */
1356 remote = remote_get(NULL);
1357 result = fetch_one(remote, argc, argv);
1358 } else if (multiple) {
1359 /* All arguments are assumed to be remotes or groups */
1360 for (i = 0; i < argc; i++)
1361 if (!add_remote_or_group(argv[i], &list))
1362 die(_("No such remote or remote group: %s"), argv[i]);
1363 result = fetch_multiple(&list);
1364 } else {
1365 /* Single remote or group */
1366 (void) add_remote_or_group(argv[0], &list);
1367 if (list.nr > 1) {
1368 /* More than one remote */
1369 if (argc > 1)
1370 die(_("Fetching a group and specifying refspecs does not make sense"));
1371 result = fetch_multiple(&list);
1372 } else {
1373 /* Zero or one remotes */
1374 remote = remote_get(argv[0]);
1375 result = fetch_one(remote, argc-1, argv+1);
1379 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1380 struct argv_array options = ARGV_ARRAY_INIT;
1382 add_options_to_argv(&options);
1383 result = fetch_populated_submodules(&options,
1384 submodule_prefix,
1385 recurse_submodules,
1386 verbosity < 0,
1387 max_children);
1388 argv_array_clear(&options);
1391 string_list_clear(&list, 0);
1393 close_all_packs();
1395 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1396 if (verbosity < 0)
1397 argv_array_push(&argv_gc_auto, "--quiet");
1398 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1399 argv_array_clear(&argv_gc_auto);
1401 return result;