built-in rebase --autostash: leave the current branch alone if possible
[git/debian.git] / builtin / fetch.c
blob34d2bd123b3303a096edb99ab4f82c52a89b35f5
1 /*
2 * "git fetch"
3 */
4 #include "cache.h"
5 #include "config.h"
6 #include "repository.h"
7 #include "refs.h"
8 #include "refspec.h"
9 #include "object-store.h"
10 #include "commit.h"
11 #include "builtin.h"
12 #include "string-list.h"
13 #include "remote.h"
14 #include "transport.h"
15 #include "run-command.h"
16 #include "parse-options.h"
17 #include "sigchain.h"
18 #include "submodule-config.h"
19 #include "submodule.h"
20 #include "connected.h"
21 #include "argv-array.h"
22 #include "utf8.h"
23 #include "packfile.h"
24 #include "list-objects-filter-options.h"
26 static const char * const builtin_fetch_usage[] = {
27 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
28 N_("git fetch [<options>] <group>"),
29 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
30 N_("git fetch --all [<options>]"),
31 NULL
34 enum {
35 TAGS_UNSET = 0,
36 TAGS_DEFAULT = 1,
37 TAGS_SET = 2
40 static int fetch_prune_config = -1; /* unspecified */
41 static int prune = -1; /* unspecified */
42 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
44 static int fetch_prune_tags_config = -1; /* unspecified */
45 static int prune_tags = -1; /* unspecified */
46 #define PRUNE_TAGS_BY_DEFAULT 0 /* do we prune tags by default? */
48 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity, deepen_relative;
49 static int progress = -1;
50 static int tags = TAGS_DEFAULT, unshallow, update_shallow, deepen;
51 static int max_children = 1;
52 static enum transport_family family;
53 static const char *depth;
54 static const char *deepen_since;
55 static const char *upload_pack;
56 static struct string_list deepen_not = STRING_LIST_INIT_NODUP;
57 static struct strbuf default_rla = STRBUF_INIT;
58 static struct transport *gtransport;
59 static struct transport *gsecondary;
60 static const char *submodule_prefix = "";
61 static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
62 static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
63 static int shown_url = 0;
64 static struct refspec refmap = REFSPEC_INIT_FETCH;
65 static struct list_objects_filter_options filter_options;
66 static struct string_list server_options = STRING_LIST_INIT_DUP;
67 static struct string_list negotiation_tip = STRING_LIST_INIT_NODUP;
69 static int git_fetch_config(const char *k, const char *v, void *cb)
71 if (!strcmp(k, "fetch.prune")) {
72 fetch_prune_config = git_config_bool(k, v);
73 return 0;
76 if (!strcmp(k, "fetch.prunetags")) {
77 fetch_prune_tags_config = git_config_bool(k, v);
78 return 0;
81 if (!strcmp(k, "submodule.recurse")) {
82 int r = git_config_bool(k, v) ?
83 RECURSE_SUBMODULES_ON : RECURSE_SUBMODULES_OFF;
84 recurse_submodules = r;
87 if (!strcmp(k, "submodule.fetchjobs")) {
88 max_children = parse_submodule_fetchjobs(k, v);
89 return 0;
90 } else if (!strcmp(k, "fetch.recursesubmodules")) {
91 recurse_submodules = parse_fetch_recurse_submodules_arg(k, v);
92 return 0;
95 return git_default_config(k, v, cb);
98 static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
101 * "git fetch --refmap='' origin foo"
102 * can be used to tell the command not to store anywhere
104 refspec_append(&refmap, arg);
106 return 0;
109 static struct option builtin_fetch_options[] = {
110 OPT__VERBOSITY(&verbosity),
111 OPT_BOOL(0, "all", &all,
112 N_("fetch from all remotes")),
113 OPT_BOOL('a', "append", &append,
114 N_("append to .git/FETCH_HEAD instead of overwriting")),
115 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
116 N_("path to upload pack on remote end")),
117 OPT__FORCE(&force, N_("force overwrite of local branch"), 0),
118 OPT_BOOL('m', "multiple", &multiple,
119 N_("fetch from multiple remotes")),
120 OPT_SET_INT('t', "tags", &tags,
121 N_("fetch all tags and associated objects"), TAGS_SET),
122 OPT_SET_INT('n', NULL, &tags,
123 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
124 OPT_INTEGER('j', "jobs", &max_children,
125 N_("number of submodules fetched in parallel")),
126 OPT_BOOL('p', "prune", &prune,
127 N_("prune remote-tracking branches no longer on remote")),
128 OPT_BOOL('P', "prune-tags", &prune_tags,
129 N_("prune local tags no longer on remote and clobber changed tags")),
130 { OPTION_CALLBACK, 0, "recurse-submodules", &recurse_submodules, N_("on-demand"),
131 N_("control recursive fetching of submodules"),
132 PARSE_OPT_OPTARG, option_fetch_parse_recurse_submodules },
133 OPT_BOOL(0, "dry-run", &dry_run,
134 N_("dry run")),
135 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
136 OPT_BOOL('u', "update-head-ok", &update_head_ok,
137 N_("allow updating of HEAD ref")),
138 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
139 OPT_STRING(0, "depth", &depth, N_("depth"),
140 N_("deepen history of shallow clone")),
141 OPT_STRING(0, "shallow-since", &deepen_since, N_("time"),
142 N_("deepen history of shallow repository based on time")),
143 OPT_STRING_LIST(0, "shallow-exclude", &deepen_not, N_("revision"),
144 N_("deepen history of shallow clone, excluding rev")),
145 OPT_INTEGER(0, "deepen", &deepen_relative,
146 N_("deepen history of shallow clone")),
147 OPT_SET_INT_F(0, "unshallow", &unshallow,
148 N_("convert to a complete repository"),
149 1, PARSE_OPT_NONEG),
150 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
151 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
152 { OPTION_CALLBACK, 0, "recurse-submodules-default",
153 &recurse_submodules_default, N_("on-demand"),
154 N_("default for recursive fetching of submodules "
155 "(lower priority than config files)"),
156 PARSE_OPT_HIDDEN, option_fetch_parse_recurse_submodules },
157 OPT_BOOL(0, "update-shallow", &update_shallow,
158 N_("accept refs that update .git/shallow")),
159 { OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
160 N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
161 OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
162 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
163 TRANSPORT_FAMILY_IPV4),
164 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
165 TRANSPORT_FAMILY_IPV6),
166 OPT_STRING_LIST(0, "negotiation-tip", &negotiation_tip, N_("revision"),
167 N_("report that we have only objects reachable from this object")),
168 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
169 OPT_END()
172 static void unlock_pack(void)
174 if (gtransport)
175 transport_unlock_pack(gtransport);
176 if (gsecondary)
177 transport_unlock_pack(gsecondary);
180 static void unlock_pack_on_signal(int signo)
182 unlock_pack();
183 sigchain_pop(signo);
184 raise(signo);
187 static void add_merge_config(struct ref **head,
188 const struct ref *remote_refs,
189 struct branch *branch,
190 struct ref ***tail)
192 int i;
194 for (i = 0; i < branch->merge_nr; i++) {
195 struct ref *rm, **old_tail = *tail;
196 struct refspec_item refspec;
198 for (rm = *head; rm; rm = rm->next) {
199 if (branch_merge_matches(branch, i, rm->name)) {
200 rm->fetch_head_status = FETCH_HEAD_MERGE;
201 break;
204 if (rm)
205 continue;
208 * Not fetched to a remote-tracking branch? We need to fetch
209 * it anyway to allow this branch's "branch.$name.merge"
210 * to be honored by 'git pull', but we do not have to
211 * fail if branch.$name.merge is misconfigured to point
212 * at a nonexisting branch. If we were indeed called by
213 * 'git pull', it will notice the misconfiguration because
214 * there is no entry in the resulting FETCH_HEAD marked
215 * for merging.
217 memset(&refspec, 0, sizeof(refspec));
218 refspec.src = branch->merge[i]->src;
219 get_fetch_map(remote_refs, &refspec, tail, 1);
220 for (rm = *old_tail; rm; rm = rm->next)
221 rm->fetch_head_status = FETCH_HEAD_MERGE;
225 static int add_existing(const char *refname, const struct object_id *oid,
226 int flag, void *cbdata)
228 struct string_list *list = (struct string_list *)cbdata;
229 struct string_list_item *item = string_list_insert(list, refname);
230 struct object_id *old_oid = xmalloc(sizeof(*old_oid));
232 oidcpy(old_oid, oid);
233 item->util = old_oid;
234 return 0;
237 static int will_fetch(struct ref **head, const unsigned char *sha1)
239 struct ref *rm = *head;
240 while (rm) {
241 if (!hashcmp(rm->old_oid.hash, sha1))
242 return 1;
243 rm = rm->next;
245 return 0;
248 static void find_non_local_tags(const struct ref *refs,
249 struct ref **head,
250 struct ref ***tail)
252 struct string_list existing_refs = STRING_LIST_INIT_DUP;
253 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
254 const struct ref *ref;
255 struct string_list_item *item = NULL;
257 for_each_ref(add_existing, &existing_refs);
258 for (ref = refs; ref; ref = ref->next) {
259 if (!starts_with(ref->name, "refs/tags/"))
260 continue;
263 * The peeled ref always follows the matching base
264 * ref, so if we see a peeled ref that we don't want
265 * to fetch then we can mark the ref entry in the list
266 * as one to ignore by setting util to NULL.
268 if (ends_with(ref->name, "^{}")) {
269 if (item &&
270 !has_object_file_with_flags(&ref->old_oid,
271 OBJECT_INFO_QUICK) &&
272 !will_fetch(head, ref->old_oid.hash) &&
273 !has_sha1_file_with_flags(item->util,
274 OBJECT_INFO_QUICK) &&
275 !will_fetch(head, item->util))
276 item->util = NULL;
277 item = NULL;
278 continue;
282 * If item is non-NULL here, then we previously saw a
283 * ref not followed by a peeled reference, so we need
284 * to check if it is a lightweight tag that we want to
285 * fetch.
287 if (item &&
288 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
289 !will_fetch(head, item->util))
290 item->util = NULL;
292 item = NULL;
294 /* skip duplicates and refs that we already have */
295 if (string_list_has_string(&remote_refs, ref->name) ||
296 string_list_has_string(&existing_refs, ref->name))
297 continue;
299 item = string_list_insert(&remote_refs, ref->name);
300 item->util = (void *)&ref->old_oid;
302 string_list_clear(&existing_refs, 1);
305 * We may have a final lightweight tag that needs to be
306 * checked to see if it needs fetching.
308 if (item &&
309 !has_sha1_file_with_flags(item->util, OBJECT_INFO_QUICK) &&
310 !will_fetch(head, item->util))
311 item->util = NULL;
314 * For all the tags in the remote_refs string list,
315 * add them to the list of refs to be fetched
317 for_each_string_list_item(item, &remote_refs) {
318 /* Unless we have already decided to ignore this item... */
319 if (item->util)
321 struct ref *rm = alloc_ref(item->string);
322 rm->peer_ref = alloc_ref(item->string);
323 oidcpy(&rm->old_oid, item->util);
324 **tail = rm;
325 *tail = &rm->next;
329 string_list_clear(&remote_refs, 0);
332 static struct ref *get_ref_map(struct remote *remote,
333 const struct ref *remote_refs,
334 struct refspec *rs,
335 int tags, int *autotags)
337 int i;
338 struct ref *rm;
339 struct ref *ref_map = NULL;
340 struct ref **tail = &ref_map;
342 /* opportunistically-updated references: */
343 struct ref *orefs = NULL, **oref_tail = &orefs;
345 struct string_list existing_refs = STRING_LIST_INIT_DUP;
347 if (rs->nr) {
348 struct refspec *fetch_refspec;
350 for (i = 0; i < rs->nr; i++) {
351 get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
352 if (rs->items[i].dst && rs->items[i].dst[0])
353 *autotags = 1;
355 /* Merge everything on the command line (but not --tags) */
356 for (rm = ref_map; rm; rm = rm->next)
357 rm->fetch_head_status = FETCH_HEAD_MERGE;
360 * For any refs that we happen to be fetching via
361 * command-line arguments, the destination ref might
362 * have been missing or have been different than the
363 * remote-tracking ref that would be derived from the
364 * configured refspec. In these cases, we want to
365 * take the opportunity to update their configured
366 * remote-tracking reference. However, we do not want
367 * to mention these entries in FETCH_HEAD at all, as
368 * they would simply be duplicates of existing
369 * entries, so we set them FETCH_HEAD_IGNORE below.
371 * We compute these entries now, based only on the
372 * refspecs specified on the command line. But we add
373 * them to the list following the refspecs resulting
374 * from the tags option so that one of the latter,
375 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
376 * by ref_remove_duplicates() in favor of one of these
377 * opportunistic entries with FETCH_HEAD_IGNORE.
379 if (refmap.nr)
380 fetch_refspec = &refmap;
381 else
382 fetch_refspec = &remote->fetch;
384 for (i = 0; i < fetch_refspec->nr; i++)
385 get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
386 } else if (refmap.nr) {
387 die("--refmap option is only meaningful with command-line refspec(s).");
388 } else {
389 /* Use the defaults */
390 struct branch *branch = branch_get(NULL);
391 int has_merge = branch_has_merge_config(branch);
392 if (remote &&
393 (remote->fetch.nr ||
394 /* Note: has_merge implies non-NULL branch->remote_name */
395 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
396 for (i = 0; i < remote->fetch.nr; i++) {
397 get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
398 if (remote->fetch.items[i].dst &&
399 remote->fetch.items[i].dst[0])
400 *autotags = 1;
401 if (!i && !has_merge && ref_map &&
402 !remote->fetch.items[0].pattern)
403 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
406 * if the remote we're fetching from is the same
407 * as given in branch.<name>.remote, we add the
408 * ref given in branch.<name>.merge, too.
410 * Note: has_merge implies non-NULL branch->remote_name
412 if (has_merge &&
413 !strcmp(branch->remote_name, remote->name))
414 add_merge_config(&ref_map, remote_refs, branch, &tail);
415 } else {
416 ref_map = get_remote_ref(remote_refs, "HEAD");
417 if (!ref_map)
418 die(_("Couldn't find remote ref HEAD"));
419 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
420 tail = &ref_map->next;
424 if (tags == TAGS_SET)
425 /* also fetch all tags */
426 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
427 else if (tags == TAGS_DEFAULT && *autotags)
428 find_non_local_tags(remote_refs, &ref_map, &tail);
430 /* Now append any refs to be updated opportunistically: */
431 *tail = orefs;
432 for (rm = orefs; rm; rm = rm->next) {
433 rm->fetch_head_status = FETCH_HEAD_IGNORE;
434 tail = &rm->next;
437 ref_map = ref_remove_duplicates(ref_map);
439 for_each_ref(add_existing, &existing_refs);
440 for (rm = ref_map; rm; rm = rm->next) {
441 if (rm->peer_ref) {
442 struct string_list_item *peer_item =
443 string_list_lookup(&existing_refs,
444 rm->peer_ref->name);
445 if (peer_item) {
446 struct object_id *old_oid = peer_item->util;
447 oidcpy(&rm->peer_ref->old_oid, old_oid);
451 string_list_clear(&existing_refs, 1);
453 return ref_map;
456 #define STORE_REF_ERROR_OTHER 1
457 #define STORE_REF_ERROR_DF_CONFLICT 2
459 static int s_update_ref(const char *action,
460 struct ref *ref,
461 int check_old)
463 char *msg;
464 char *rla = getenv("GIT_REFLOG_ACTION");
465 struct ref_transaction *transaction;
466 struct strbuf err = STRBUF_INIT;
467 int ret, df_conflict = 0;
469 if (dry_run)
470 return 0;
471 if (!rla)
472 rla = default_rla.buf;
473 msg = xstrfmt("%s: %s", rla, action);
475 transaction = ref_transaction_begin(&err);
476 if (!transaction ||
477 ref_transaction_update(transaction, ref->name,
478 &ref->new_oid,
479 check_old ? &ref->old_oid : NULL,
480 0, msg, &err))
481 goto fail;
483 ret = ref_transaction_commit(transaction, &err);
484 if (ret) {
485 df_conflict = (ret == TRANSACTION_NAME_CONFLICT);
486 goto fail;
489 ref_transaction_free(transaction);
490 strbuf_release(&err);
491 free(msg);
492 return 0;
493 fail:
494 ref_transaction_free(transaction);
495 error("%s", err.buf);
496 strbuf_release(&err);
497 free(msg);
498 return df_conflict ? STORE_REF_ERROR_DF_CONFLICT
499 : STORE_REF_ERROR_OTHER;
502 static int refcol_width = 10;
503 static int compact_format;
505 static void adjust_refcol_width(const struct ref *ref)
507 int max, rlen, llen, len;
509 /* uptodate lines are only shown on high verbosity level */
510 if (!verbosity && !oidcmp(&ref->peer_ref->old_oid, &ref->old_oid))
511 return;
513 max = term_columns();
514 rlen = utf8_strwidth(prettify_refname(ref->name));
516 llen = utf8_strwidth(prettify_refname(ref->peer_ref->name));
519 * rough estimation to see if the output line is too long and
520 * should not be counted (we can't do precise calculation
521 * anyway because we don't know if the error explanation part
522 * will be printed in update_local_ref)
524 if (compact_format) {
525 llen = 0;
526 max = max * 2 / 3;
528 len = 21 /* flag and summary */ + rlen + 4 /* -> */ + llen;
529 if (len >= max)
530 return;
533 * Not precise calculation for compact mode because '*' can
534 * appear on the left hand side of '->' and shrink the column
535 * back.
537 if (refcol_width < rlen)
538 refcol_width = rlen;
541 static void prepare_format_display(struct ref *ref_map)
543 struct ref *rm;
544 const char *format = "full";
546 git_config_get_string_const("fetch.output", &format);
547 if (!strcasecmp(format, "full"))
548 compact_format = 0;
549 else if (!strcasecmp(format, "compact"))
550 compact_format = 1;
551 else
552 die(_("configuration fetch.output contains invalid value %s"),
553 format);
555 for (rm = ref_map; rm; rm = rm->next) {
556 if (rm->status == REF_STATUS_REJECT_SHALLOW ||
557 !rm->peer_ref ||
558 !strcmp(rm->name, "HEAD"))
559 continue;
561 adjust_refcol_width(rm);
565 static void print_remote_to_local(struct strbuf *display,
566 const char *remote, const char *local)
568 strbuf_addf(display, "%-*s -> %s", refcol_width, remote, local);
571 static int find_and_replace(struct strbuf *haystack,
572 const char *needle,
573 const char *placeholder)
575 const char *p = strstr(haystack->buf, needle);
576 int plen, nlen;
578 if (!p)
579 return 0;
581 if (p > haystack->buf && p[-1] != '/')
582 return 0;
584 plen = strlen(p);
585 nlen = strlen(needle);
586 if (plen > nlen && p[nlen] != '/')
587 return 0;
589 strbuf_splice(haystack, p - haystack->buf, nlen,
590 placeholder, strlen(placeholder));
591 return 1;
594 static void print_compact(struct strbuf *display,
595 const char *remote, const char *local)
597 struct strbuf r = STRBUF_INIT;
598 struct strbuf l = STRBUF_INIT;
600 if (!strcmp(remote, local)) {
601 strbuf_addf(display, "%-*s -> *", refcol_width, remote);
602 return;
605 strbuf_addstr(&r, remote);
606 strbuf_addstr(&l, local);
608 if (!find_and_replace(&r, local, "*"))
609 find_and_replace(&l, remote, "*");
610 print_remote_to_local(display, r.buf, l.buf);
612 strbuf_release(&r);
613 strbuf_release(&l);
616 static void format_display(struct strbuf *display, char code,
617 const char *summary, const char *error,
618 const char *remote, const char *local,
619 int summary_width)
621 int width = (summary_width + strlen(summary) - gettext_width(summary));
623 strbuf_addf(display, "%c %-*s ", code, width, summary);
624 if (!compact_format)
625 print_remote_to_local(display, remote, local);
626 else
627 print_compact(display, remote, local);
628 if (error)
629 strbuf_addf(display, " (%s)", error);
632 static int update_local_ref(struct ref *ref,
633 const char *remote,
634 const struct ref *remote_ref,
635 struct strbuf *display,
636 int summary_width)
638 struct commit *current = NULL, *updated;
639 enum object_type type;
640 struct branch *current_branch = branch_get(NULL);
641 const char *pretty_ref = prettify_refname(ref->name);
643 type = oid_object_info(the_repository, &ref->new_oid, NULL);
644 if (type < 0)
645 die(_("object %s not found"), oid_to_hex(&ref->new_oid));
647 if (!oidcmp(&ref->old_oid, &ref->new_oid)) {
648 if (verbosity > 0)
649 format_display(display, '=', _("[up to date]"), NULL,
650 remote, pretty_ref, summary_width);
651 return 0;
654 if (current_branch &&
655 !strcmp(ref->name, current_branch->name) &&
656 !(update_head_ok || is_bare_repository()) &&
657 !is_null_oid(&ref->old_oid)) {
659 * If this is the head, and it's not okay to update
660 * the head, and the old value of the head isn't empty...
662 format_display(display, '!', _("[rejected]"),
663 _("can't fetch in current branch"),
664 remote, pretty_ref, summary_width);
665 return 1;
668 if (!is_null_oid(&ref->old_oid) &&
669 starts_with(ref->name, "refs/tags/")) {
670 int r;
671 r = s_update_ref("updating tag", ref, 0);
672 format_display(display, r ? '!' : 't', _("[tag update]"),
673 r ? _("unable to update local ref") : NULL,
674 remote, pretty_ref, summary_width);
675 return r;
678 current = lookup_commit_reference_gently(the_repository,
679 &ref->old_oid, 1);
680 updated = lookup_commit_reference_gently(the_repository,
681 &ref->new_oid, 1);
682 if (!current || !updated) {
683 const char *msg;
684 const char *what;
685 int r;
687 * Nicely describe the new ref we're fetching.
688 * Base this on the remote's ref name, as it's
689 * more likely to follow a standard layout.
691 const char *name = remote_ref ? remote_ref->name : "";
692 if (starts_with(name, "refs/tags/")) {
693 msg = "storing tag";
694 what = _("[new tag]");
695 } else if (starts_with(name, "refs/heads/")) {
696 msg = "storing head";
697 what = _("[new branch]");
698 } else {
699 msg = "storing ref";
700 what = _("[new ref]");
703 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
704 (recurse_submodules != RECURSE_SUBMODULES_ON))
705 check_for_new_submodule_commits(&ref->new_oid);
706 r = s_update_ref(msg, ref, 0);
707 format_display(display, r ? '!' : '*', what,
708 r ? _("unable to update local ref") : NULL,
709 remote, pretty_ref, summary_width);
710 return r;
713 if (in_merge_bases(current, updated)) {
714 struct strbuf quickref = STRBUF_INIT;
715 int r;
716 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
717 strbuf_addstr(&quickref, "..");
718 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
719 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
720 (recurse_submodules != RECURSE_SUBMODULES_ON))
721 check_for_new_submodule_commits(&ref->new_oid);
722 r = s_update_ref("fast-forward", ref, 1);
723 format_display(display, r ? '!' : ' ', quickref.buf,
724 r ? _("unable to update local ref") : NULL,
725 remote, pretty_ref, summary_width);
726 strbuf_release(&quickref);
727 return r;
728 } else if (force || ref->force) {
729 struct strbuf quickref = STRBUF_INIT;
730 int r;
731 strbuf_add_unique_abbrev(&quickref, &current->object.oid, DEFAULT_ABBREV);
732 strbuf_addstr(&quickref, "...");
733 strbuf_add_unique_abbrev(&quickref, &ref->new_oid, DEFAULT_ABBREV);
734 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
735 (recurse_submodules != RECURSE_SUBMODULES_ON))
736 check_for_new_submodule_commits(&ref->new_oid);
737 r = s_update_ref("forced-update", ref, 1);
738 format_display(display, r ? '!' : '+', quickref.buf,
739 r ? _("unable to update local ref") : _("forced update"),
740 remote, pretty_ref, summary_width);
741 strbuf_release(&quickref);
742 return r;
743 } else {
744 format_display(display, '!', _("[rejected]"), _("non-fast-forward"),
745 remote, pretty_ref, summary_width);
746 return 1;
750 static int iterate_ref_map(void *cb_data, struct object_id *oid)
752 struct ref **rm = cb_data;
753 struct ref *ref = *rm;
755 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
756 ref = ref->next;
757 if (!ref)
758 return -1; /* end of the list */
759 *rm = ref->next;
760 oidcpy(oid, &ref->old_oid);
761 return 0;
764 static int store_updated_refs(const char *raw_url, const char *remote_name,
765 int connectivity_checked, struct ref *ref_map)
767 FILE *fp;
768 struct commit *commit;
769 int url_len, i, rc = 0;
770 struct strbuf note = STRBUF_INIT;
771 const char *what, *kind;
772 struct ref *rm;
773 char *url;
774 const char *filename = dry_run ? "/dev/null" : git_path_fetch_head(the_repository);
775 int want_status;
776 int summary_width = transport_summary_width(ref_map);
778 fp = fopen(filename, "a");
779 if (!fp)
780 return error_errno(_("cannot open %s"), filename);
782 if (raw_url)
783 url = transport_anonymize_url(raw_url);
784 else
785 url = xstrdup("foreign");
787 if (!connectivity_checked) {
788 rm = ref_map;
789 if (check_connected(iterate_ref_map, &rm, NULL)) {
790 rc = error(_("%s did not send all necessary objects\n"), url);
791 goto abort;
795 prepare_format_display(ref_map);
798 * We do a pass for each fetch_head_status type in their enum order, so
799 * merged entries are written before not-for-merge. That lets readers
800 * use FETCH_HEAD as a refname to refer to the ref to be merged.
802 for (want_status = FETCH_HEAD_MERGE;
803 want_status <= FETCH_HEAD_IGNORE;
804 want_status++) {
805 for (rm = ref_map; rm; rm = rm->next) {
806 struct ref *ref = NULL;
807 const char *merge_status_marker = "";
809 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
810 if (want_status == FETCH_HEAD_MERGE)
811 warning(_("reject %s because shallow roots are not allowed to be updated"),
812 rm->peer_ref ? rm->peer_ref->name : rm->name);
813 continue;
816 commit = lookup_commit_reference_gently(the_repository,
817 &rm->old_oid,
819 if (!commit)
820 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
822 if (rm->fetch_head_status != want_status)
823 continue;
825 if (rm->peer_ref) {
826 ref = alloc_ref(rm->peer_ref->name);
827 oidcpy(&ref->old_oid, &rm->peer_ref->old_oid);
828 oidcpy(&ref->new_oid, &rm->old_oid);
829 ref->force = rm->peer_ref->force;
833 if (!strcmp(rm->name, "HEAD")) {
834 kind = "";
835 what = "";
837 else if (starts_with(rm->name, "refs/heads/")) {
838 kind = "branch";
839 what = rm->name + 11;
841 else if (starts_with(rm->name, "refs/tags/")) {
842 kind = "tag";
843 what = rm->name + 10;
845 else if (starts_with(rm->name, "refs/remotes/")) {
846 kind = "remote-tracking branch";
847 what = rm->name + 13;
849 else {
850 kind = "";
851 what = rm->name;
854 url_len = strlen(url);
855 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
857 url_len = i + 1;
858 if (4 < i && !strncmp(".git", url + i - 3, 4))
859 url_len = i - 3;
861 strbuf_reset(&note);
862 if (*what) {
863 if (*kind)
864 strbuf_addf(&note, "%s ", kind);
865 strbuf_addf(&note, "'%s' of ", what);
867 switch (rm->fetch_head_status) {
868 case FETCH_HEAD_NOT_FOR_MERGE:
869 merge_status_marker = "not-for-merge";
870 /* fall-through */
871 case FETCH_HEAD_MERGE:
872 fprintf(fp, "%s\t%s\t%s",
873 oid_to_hex(&rm->old_oid),
874 merge_status_marker,
875 note.buf);
876 for (i = 0; i < url_len; ++i)
877 if ('\n' == url[i])
878 fputs("\\n", fp);
879 else
880 fputc(url[i], fp);
881 fputc('\n', fp);
882 break;
883 default:
884 /* do not write anything to FETCH_HEAD */
885 break;
888 strbuf_reset(&note);
889 if (ref) {
890 rc |= update_local_ref(ref, what, rm, &note,
891 summary_width);
892 free(ref);
893 } else
894 format_display(&note, '*',
895 *kind ? kind : "branch", NULL,
896 *what ? what : "HEAD",
897 "FETCH_HEAD", summary_width);
898 if (note.len) {
899 if (verbosity >= 0 && !shown_url) {
900 fprintf(stderr, _("From %.*s\n"),
901 url_len, url);
902 shown_url = 1;
904 if (verbosity >= 0)
905 fprintf(stderr, " %s\n", note.buf);
910 if (rc & STORE_REF_ERROR_DF_CONFLICT)
911 error(_("some local refs could not be updated; try running\n"
912 " 'git remote prune %s' to remove any old, conflicting "
913 "branches"), remote_name);
915 abort:
916 strbuf_release(&note);
917 free(url);
918 fclose(fp);
919 return rc;
923 * We would want to bypass the object transfer altogether if
924 * everything we are going to fetch already exists and is connected
925 * locally.
927 static int quickfetch(struct ref *ref_map)
929 struct ref *rm = ref_map;
930 struct check_connected_options opt = CHECK_CONNECTED_INIT;
933 * If we are deepening a shallow clone we already have these
934 * objects reachable. Running rev-list here will return with
935 * a good (0) exit status and we'll bypass the fetch that we
936 * really need to perform. Claiming failure now will ensure
937 * we perform the network exchange to deepen our history.
939 if (deepen)
940 return -1;
941 opt.quiet = 1;
942 return check_connected(iterate_ref_map, &rm, &opt);
945 static int fetch_refs(struct transport *transport, struct ref *ref_map,
946 struct ref **updated_remote_refs)
948 int ret = quickfetch(ref_map);
949 if (ret)
950 ret = transport_fetch_refs(transport, ref_map,
951 updated_remote_refs);
952 if (!ret)
954 * Keep the new pack's ".keep" file around to allow the caller
955 * time to update refs to reference the new objects.
957 return 0;
958 transport_unlock_pack(transport);
959 return ret;
962 /* Update local refs based on the ref values fetched from a remote */
963 static int consume_refs(struct transport *transport, struct ref *ref_map)
965 int connectivity_checked = transport->smart_options
966 ? transport->smart_options->connectivity_checked : 0;
967 int ret = store_updated_refs(transport->url,
968 transport->remote->name,
969 connectivity_checked,
970 ref_map);
971 transport_unlock_pack(transport);
972 return ret;
975 static int prune_refs(struct refspec *rs, struct ref *ref_map,
976 const char *raw_url)
978 int url_len, i, result = 0;
979 struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
980 char *url;
981 int summary_width = transport_summary_width(stale_refs);
982 const char *dangling_msg = dry_run
983 ? _(" (%s will become dangling)")
984 : _(" (%s has become dangling)");
986 if (raw_url)
987 url = transport_anonymize_url(raw_url);
988 else
989 url = xstrdup("foreign");
991 url_len = strlen(url);
992 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
995 url_len = i + 1;
996 if (4 < i && !strncmp(".git", url + i - 3, 4))
997 url_len = i - 3;
999 if (!dry_run) {
1000 struct string_list refnames = STRING_LIST_INIT_NODUP;
1002 for (ref = stale_refs; ref; ref = ref->next)
1003 string_list_append(&refnames, ref->name);
1005 result = delete_refs("fetch: prune", &refnames, 0);
1006 string_list_clear(&refnames, 0);
1009 if (verbosity >= 0) {
1010 for (ref = stale_refs; ref; ref = ref->next) {
1011 struct strbuf sb = STRBUF_INIT;
1012 if (!shown_url) {
1013 fprintf(stderr, _("From %.*s\n"), url_len, url);
1014 shown_url = 1;
1016 format_display(&sb, '-', _("[deleted]"), NULL,
1017 _("(none)"), prettify_refname(ref->name),
1018 summary_width);
1019 fprintf(stderr, " %s\n",sb.buf);
1020 strbuf_release(&sb);
1021 warn_dangling_symref(stderr, dangling_msg, ref->name);
1025 free(url);
1026 free_refs(stale_refs);
1027 return result;
1030 static void check_not_current_branch(struct ref *ref_map)
1032 struct branch *current_branch = branch_get(NULL);
1034 if (is_bare_repository() || !current_branch)
1035 return;
1037 for (; ref_map; ref_map = ref_map->next)
1038 if (ref_map->peer_ref && !strcmp(current_branch->refname,
1039 ref_map->peer_ref->name))
1040 die(_("Refusing to fetch into current branch %s "
1041 "of non-bare repository"), current_branch->refname);
1044 static int truncate_fetch_head(void)
1046 const char *filename = git_path_fetch_head(the_repository);
1047 FILE *fp = fopen_for_writing(filename);
1049 if (!fp)
1050 return error_errno(_("cannot open %s"), filename);
1051 fclose(fp);
1052 return 0;
1055 static void set_option(struct transport *transport, const char *name, const char *value)
1057 int r = transport_set_option(transport, name, value);
1058 if (r < 0)
1059 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
1060 name, value, transport->url);
1061 if (r > 0)
1062 warning(_("Option \"%s\" is ignored for %s\n"),
1063 name, transport->url);
1067 static int add_oid(const char *refname, const struct object_id *oid, int flags,
1068 void *cb_data)
1070 struct oid_array *oids = cb_data;
1072 oid_array_append(oids, oid);
1073 return 0;
1076 static void add_negotiation_tips(struct git_transport_options *smart_options)
1078 struct oid_array *oids = xcalloc(1, sizeof(*oids));
1079 int i;
1081 for (i = 0; i < negotiation_tip.nr; i++) {
1082 const char *s = negotiation_tip.items[i].string;
1083 int old_nr;
1084 if (!has_glob_specials(s)) {
1085 struct object_id oid;
1086 if (get_oid(s, &oid))
1087 die("%s is not a valid object", s);
1088 oid_array_append(oids, &oid);
1089 continue;
1091 old_nr = oids->nr;
1092 for_each_glob_ref(add_oid, s, oids);
1093 if (old_nr == oids->nr)
1094 warning("Ignoring --negotiation-tip=%s because it does not match any refs",
1097 smart_options->negotiation_tips = oids;
1100 static struct transport *prepare_transport(struct remote *remote, int deepen)
1102 struct transport *transport;
1103 transport = transport_get(remote, NULL);
1104 transport_set_verbosity(transport, verbosity, progress);
1105 transport->family = family;
1106 if (upload_pack)
1107 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
1108 if (keep)
1109 set_option(transport, TRANS_OPT_KEEP, "yes");
1110 if (depth)
1111 set_option(transport, TRANS_OPT_DEPTH, depth);
1112 if (deepen && deepen_since)
1113 set_option(transport, TRANS_OPT_DEEPEN_SINCE, deepen_since);
1114 if (deepen && deepen_not.nr)
1115 set_option(transport, TRANS_OPT_DEEPEN_NOT,
1116 (const char *)&deepen_not);
1117 if (deepen_relative)
1118 set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, "yes");
1119 if (update_shallow)
1120 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
1121 if (filter_options.choice) {
1122 set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1123 filter_options.filter_spec);
1124 set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1126 if (negotiation_tip.nr) {
1127 if (transport->smart_options)
1128 add_negotiation_tips(transport->smart_options);
1129 else
1130 warning("Ignoring --negotiation-tip because the protocol does not support it.");
1132 return transport;
1135 static void backfill_tags(struct transport *transport, struct ref *ref_map)
1137 int cannot_reuse;
1140 * Once we have set TRANS_OPT_DEEPEN_SINCE, we can't unset it
1141 * when remote helper is used (setting it to an empty string
1142 * is not unsetting). We could extend the remote helper
1143 * protocol for that, but for now, just force a new connection
1144 * without deepen-since. Similar story for deepen-not.
1146 cannot_reuse = transport->cannot_reuse ||
1147 deepen_since || deepen_not.nr;
1148 if (cannot_reuse) {
1149 gsecondary = prepare_transport(transport->remote, 0);
1150 transport = gsecondary;
1153 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
1154 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
1155 transport_set_option(transport, TRANS_OPT_DEEPEN_RELATIVE, NULL);
1156 if (!fetch_refs(transport, ref_map, NULL))
1157 consume_refs(transport, ref_map);
1159 if (gsecondary) {
1160 transport_disconnect(gsecondary);
1161 gsecondary = NULL;
1165 static int do_fetch(struct transport *transport,
1166 struct refspec *rs)
1168 struct ref *ref_map;
1169 int autotags = (transport->remote->fetch_tags == 1);
1170 int retcode = 0;
1171 const struct ref *remote_refs;
1172 struct ref *updated_remote_refs = NULL;
1173 struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
1175 if (tags == TAGS_DEFAULT) {
1176 if (transport->remote->fetch_tags == 2)
1177 tags = TAGS_SET;
1178 if (transport->remote->fetch_tags == -1)
1179 tags = TAGS_UNSET;
1182 /* if not appending, truncate FETCH_HEAD */
1183 if (!append && !dry_run) {
1184 retcode = truncate_fetch_head();
1185 if (retcode)
1186 goto cleanup;
1189 if (rs->nr)
1190 refspec_ref_prefixes(rs, &ref_prefixes);
1191 else if (transport->remote && transport->remote->fetch.nr)
1192 refspec_ref_prefixes(&transport->remote->fetch, &ref_prefixes);
1194 if (ref_prefixes.argc &&
1195 (tags == TAGS_SET || (tags == TAGS_DEFAULT && !rs->nr))) {
1196 argv_array_push(&ref_prefixes, "refs/tags/");
1199 remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
1200 argv_array_clear(&ref_prefixes);
1202 ref_map = get_ref_map(transport->remote, remote_refs, rs,
1203 tags, &autotags);
1204 if (!update_head_ok)
1205 check_not_current_branch(ref_map);
1207 if (tags == TAGS_DEFAULT && autotags)
1208 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1209 if (prune) {
1211 * We only prune based on refspecs specified
1212 * explicitly (via command line or configuration); we
1213 * don't care whether --tags was specified.
1215 if (rs->nr) {
1216 prune_refs(rs, ref_map, transport->url);
1217 } else {
1218 prune_refs(&transport->remote->fetch,
1219 ref_map,
1220 transport->url);
1224 if (fetch_refs(transport, ref_map, &updated_remote_refs)) {
1225 free_refs(ref_map);
1226 retcode = 1;
1227 goto cleanup;
1229 if (updated_remote_refs) {
1231 * Regenerate ref_map using the updated remote refs. This is
1232 * to account for additional information which may be provided
1233 * by the transport (e.g. shallow info).
1235 free_refs(ref_map);
1236 ref_map = get_ref_map(transport->remote, updated_remote_refs, rs,
1237 tags, &autotags);
1238 free_refs(updated_remote_refs);
1240 if (consume_refs(transport, ref_map)) {
1241 free_refs(ref_map);
1242 retcode = 1;
1243 goto cleanup;
1245 free_refs(ref_map);
1247 /* if neither --no-tags nor --tags was specified, do automated tag
1248 * following ... */
1249 if (tags == TAGS_DEFAULT && autotags) {
1250 struct ref **tail = &ref_map;
1251 ref_map = NULL;
1252 find_non_local_tags(remote_refs, &ref_map, &tail);
1253 if (ref_map)
1254 backfill_tags(transport, ref_map);
1255 free_refs(ref_map);
1258 cleanup:
1259 return retcode;
1262 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
1264 struct string_list *list = priv;
1265 if (!remote->skip_default_update)
1266 string_list_append(list, remote->name);
1267 return 0;
1270 struct remote_group_data {
1271 const char *name;
1272 struct string_list *list;
1275 static int get_remote_group(const char *key, const char *value, void *priv)
1277 struct remote_group_data *g = priv;
1279 if (skip_prefix(key, "remotes.", &key) && !strcmp(key, g->name)) {
1280 /* split list by white space */
1281 while (*value) {
1282 size_t wordlen = strcspn(value, " \t\n");
1284 if (wordlen >= 1)
1285 string_list_append_nodup(g->list,
1286 xstrndup(value, wordlen));
1287 value += wordlen + (value[wordlen] != '\0');
1291 return 0;
1294 static int add_remote_or_group(const char *name, struct string_list *list)
1296 int prev_nr = list->nr;
1297 struct remote_group_data g;
1298 g.name = name; g.list = list;
1300 git_config(get_remote_group, &g);
1301 if (list->nr == prev_nr) {
1302 struct remote *remote = remote_get(name);
1303 if (!remote_is_configured(remote, 0))
1304 return 0;
1305 string_list_append(list, remote->name);
1307 return 1;
1310 static void add_options_to_argv(struct argv_array *argv)
1312 if (dry_run)
1313 argv_array_push(argv, "--dry-run");
1314 if (prune != -1)
1315 argv_array_push(argv, prune ? "--prune" : "--no-prune");
1316 if (prune_tags != -1)
1317 argv_array_push(argv, prune_tags ? "--prune-tags" : "--no-prune-tags");
1318 if (update_head_ok)
1319 argv_array_push(argv, "--update-head-ok");
1320 if (force)
1321 argv_array_push(argv, "--force");
1322 if (keep)
1323 argv_array_push(argv, "--keep");
1324 if (recurse_submodules == RECURSE_SUBMODULES_ON)
1325 argv_array_push(argv, "--recurse-submodules");
1326 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
1327 argv_array_push(argv, "--recurse-submodules=on-demand");
1328 if (tags == TAGS_SET)
1329 argv_array_push(argv, "--tags");
1330 else if (tags == TAGS_UNSET)
1331 argv_array_push(argv, "--no-tags");
1332 if (verbosity >= 2)
1333 argv_array_push(argv, "-v");
1334 if (verbosity >= 1)
1335 argv_array_push(argv, "-v");
1336 else if (verbosity < 0)
1337 argv_array_push(argv, "-q");
1341 static int fetch_multiple(struct string_list *list)
1343 int i, result = 0;
1344 struct argv_array argv = ARGV_ARRAY_INIT;
1346 if (!append && !dry_run) {
1347 int errcode = truncate_fetch_head();
1348 if (errcode)
1349 return errcode;
1352 argv_array_pushl(&argv, "fetch", "--append", NULL);
1353 add_options_to_argv(&argv);
1355 for (i = 0; i < list->nr; i++) {
1356 const char *name = list->items[i].string;
1357 argv_array_push(&argv, name);
1358 if (verbosity >= 0)
1359 printf(_("Fetching %s\n"), name);
1360 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1361 error(_("Could not fetch %s"), name);
1362 result = 1;
1364 argv_array_pop(&argv);
1367 argv_array_clear(&argv);
1368 return result;
1372 * Fetching from the promisor remote should use the given filter-spec
1373 * or inherit the default filter-spec from the config.
1375 static inline void fetch_one_setup_partial(struct remote *remote)
1378 * Explicit --no-filter argument overrides everything, regardless
1379 * of any prior partial clones and fetches.
1381 if (filter_options.no_filter)
1382 return;
1385 * If no prior partial clone/fetch and the current fetch DID NOT
1386 * request a partial-fetch, do a normal fetch.
1388 if (!repository_format_partial_clone && !filter_options.choice)
1389 return;
1392 * If this is the FIRST partial-fetch request, we enable partial
1393 * on this repo and remember the given filter-spec as the default
1394 * for subsequent fetches to this remote.
1396 if (!repository_format_partial_clone && filter_options.choice) {
1397 partial_clone_register(remote->name, &filter_options);
1398 return;
1402 * We are currently limited to only ONE promisor remote and only
1403 * allow partial-fetches from the promisor remote.
1405 if (strcmp(remote->name, repository_format_partial_clone)) {
1406 if (filter_options.choice)
1407 die(_("--filter can only be used with the remote configured in core.partialClone"));
1408 return;
1412 * Do a partial-fetch from the promisor remote using either the
1413 * explicitly given filter-spec or inherit the filter-spec from
1414 * the config.
1416 if (!filter_options.choice)
1417 partial_clone_get_default_filter_spec(&filter_options);
1418 return;
1421 static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
1423 struct refspec rs = REFSPEC_INIT_FETCH;
1424 int i;
1425 int exit_code;
1426 int maybe_prune_tags;
1427 int remote_via_config = remote_is_configured(remote, 0);
1429 if (!remote)
1430 die(_("No remote repository specified. Please, specify either a URL or a\n"
1431 "remote name from which new revisions should be fetched."));
1433 gtransport = prepare_transport(remote, 1);
1435 if (prune < 0) {
1436 /* no command line request */
1437 if (0 <= remote->prune)
1438 prune = remote->prune;
1439 else if (0 <= fetch_prune_config)
1440 prune = fetch_prune_config;
1441 else
1442 prune = PRUNE_BY_DEFAULT;
1445 if (prune_tags < 0) {
1446 /* no command line request */
1447 if (0 <= remote->prune_tags)
1448 prune_tags = remote->prune_tags;
1449 else if (0 <= fetch_prune_tags_config)
1450 prune_tags = fetch_prune_tags_config;
1451 else
1452 prune_tags = PRUNE_TAGS_BY_DEFAULT;
1455 maybe_prune_tags = prune_tags_ok && prune_tags;
1456 if (maybe_prune_tags && remote_via_config)
1457 refspec_append(&remote->fetch, TAG_REFSPEC);
1459 if (maybe_prune_tags && (argc || !remote_via_config))
1460 refspec_append(&rs, TAG_REFSPEC);
1462 for (i = 0; i < argc; i++) {
1463 if (!strcmp(argv[i], "tag")) {
1464 char *tag;
1465 i++;
1466 if (i >= argc)
1467 die(_("You need to specify a tag name."));
1469 tag = xstrfmt("refs/tags/%s:refs/tags/%s",
1470 argv[i], argv[i]);
1471 refspec_append(&rs, tag);
1472 free(tag);
1473 } else {
1474 refspec_append(&rs, argv[i]);
1478 if (server_options.nr)
1479 gtransport->server_options = &server_options;
1481 sigchain_push_common(unlock_pack_on_signal);
1482 atexit(unlock_pack);
1483 exit_code = do_fetch(gtransport, &rs);
1484 refspec_clear(&rs);
1485 transport_disconnect(gtransport);
1486 gtransport = NULL;
1487 return exit_code;
1490 int cmd_fetch(int argc, const char **argv, const char *prefix)
1492 int i;
1493 struct string_list list = STRING_LIST_INIT_DUP;
1494 struct remote *remote = NULL;
1495 int result = 0;
1496 int prune_tags_ok = 1;
1497 struct argv_array argv_gc_auto = ARGV_ARRAY_INIT;
1499 packet_trace_identity("fetch");
1501 fetch_if_missing = 0;
1503 /* Record the command line for the reflog */
1504 strbuf_addstr(&default_rla, "fetch");
1505 for (i = 1; i < argc; i++)
1506 strbuf_addf(&default_rla, " %s", argv[i]);
1508 fetch_config_from_gitmodules(&max_children, &recurse_submodules);
1509 git_config(git_fetch_config, NULL);
1511 argc = parse_options(argc, argv, prefix,
1512 builtin_fetch_options, builtin_fetch_usage, 0);
1514 if (deepen_relative) {
1515 if (deepen_relative < 0)
1516 die(_("Negative depth in --deepen is not supported"));
1517 if (depth)
1518 die(_("--deepen and --depth are mutually exclusive"));
1519 depth = xstrfmt("%d", deepen_relative);
1521 if (unshallow) {
1522 if (depth)
1523 die(_("--depth and --unshallow cannot be used together"));
1524 else if (!is_repository_shallow(the_repository))
1525 die(_("--unshallow on a complete repository does not make sense"));
1526 else
1527 depth = xstrfmt("%d", INFINITE_DEPTH);
1530 /* no need to be strict, transport_set_option() will validate it again */
1531 if (depth && atoi(depth) < 1)
1532 die(_("depth %s is not a positive number"), depth);
1533 if (depth || deepen_since || deepen_not.nr)
1534 deepen = 1;
1536 if (filter_options.choice && !repository_format_partial_clone)
1537 die("--filter can only be used when extensions.partialClone is set");
1539 if (all) {
1540 if (argc == 1)
1541 die(_("fetch --all does not take a repository argument"));
1542 else if (argc > 1)
1543 die(_("fetch --all does not make sense with refspecs"));
1544 (void) for_each_remote(get_one_remote_for_fetch, &list);
1545 } else if (argc == 0) {
1546 /* No arguments -- use default remote */
1547 remote = remote_get(NULL);
1548 } else if (multiple) {
1549 /* All arguments are assumed to be remotes or groups */
1550 for (i = 0; i < argc; i++)
1551 if (!add_remote_or_group(argv[i], &list))
1552 die(_("No such remote or remote group: %s"), argv[i]);
1553 } else {
1554 /* Single remote or group */
1555 (void) add_remote_or_group(argv[0], &list);
1556 if (list.nr > 1) {
1557 /* More than one remote */
1558 if (argc > 1)
1559 die(_("Fetching a group and specifying refspecs does not make sense"));
1560 } else {
1561 /* Zero or one remotes */
1562 remote = remote_get(argv[0]);
1563 prune_tags_ok = (argc == 1);
1564 argc--;
1565 argv++;
1569 if (remote) {
1570 if (filter_options.choice || repository_format_partial_clone)
1571 fetch_one_setup_partial(remote);
1572 result = fetch_one(remote, argc, argv, prune_tags_ok);
1573 } else {
1574 if (filter_options.choice)
1575 die(_("--filter can only be used with the remote configured in core.partialClone"));
1576 /* TODO should this also die if we have a previous partial-clone? */
1577 result = fetch_multiple(&list);
1580 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1581 struct argv_array options = ARGV_ARRAY_INIT;
1583 add_options_to_argv(&options);
1584 result = fetch_populated_submodules(the_repository,
1585 &options,
1586 submodule_prefix,
1587 recurse_submodules,
1588 recurse_submodules_default,
1589 verbosity < 0,
1590 max_children);
1591 argv_array_clear(&options);
1594 string_list_clear(&list, 0);
1596 close_all_packs(the_repository->objects);
1598 argv_array_pushl(&argv_gc_auto, "gc", "--auto", NULL);
1599 if (verbosity < 0)
1600 argv_array_push(&argv_gc_auto, "--quiet");
1601 run_command_v_opt(argv_gc_auto.argv, RUN_GIT_CMD);
1602 argv_array_clear(&argv_gc_auto);
1604 return result;