fetch: add --update-shallow to accept refs that update .git/shallow
[git/debian.git] / builtin / fetch.c
blobd2e4fc03d857b8b29bc871c5f983dddb93498ed3
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 "transport.h"
15 #include "submodule.h"
16 #include "connected.h"
17 #include "argv-array.h"
19 static const char * const builtin_fetch_usage[] = {
20 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
21 N_("git fetch [<options>] <group>"),
22 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
23 N_("git fetch --all [<options>]"),
24 NULL
27 enum {
28 TAGS_UNSET = 0,
29 TAGS_DEFAULT = 1,
30 TAGS_SET = 2
33 static int fetch_prune_config = -1; /* unspecified */
34 static int prune = -1; /* unspecified */
35 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
37 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
38 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
39 static int tags = TAGS_DEFAULT, unshallow, update_shallow;
40 static const char *depth;
41 static const char *upload_pack;
42 static struct strbuf default_rla = STRBUF_INIT;
43 static struct transport *gtransport;
44 static struct transport *gsecondary;
45 static const char *submodule_prefix = "";
46 static const char *recurse_submodules_default;
48 static int option_parse_recurse_submodules(const struct option *opt,
49 const char *arg, int unset)
51 if (unset) {
52 recurse_submodules = RECURSE_SUBMODULES_OFF;
53 } else {
54 if (arg)
55 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
56 else
57 recurse_submodules = RECURSE_SUBMODULES_ON;
59 return 0;
62 static int git_fetch_config(const char *k, const char *v, void *cb)
64 if (!strcmp(k, "fetch.prune")) {
65 fetch_prune_config = git_config_bool(k, v);
66 return 0;
68 return 0;
71 static struct option builtin_fetch_options[] = {
72 OPT__VERBOSITY(&verbosity),
73 OPT_BOOL(0, "all", &all,
74 N_("fetch from all remotes")),
75 OPT_BOOL('a', "append", &append,
76 N_("append to .git/FETCH_HEAD instead of overwriting")),
77 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
78 N_("path to upload pack on remote end")),
79 OPT__FORCE(&force, N_("force overwrite of local branch")),
80 OPT_BOOL('m', "multiple", &multiple,
81 N_("fetch from multiple remotes")),
82 OPT_SET_INT('t', "tags", &tags,
83 N_("fetch all tags and associated objects"), TAGS_SET),
84 OPT_SET_INT('n', NULL, &tags,
85 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
86 OPT_BOOL('p', "prune", &prune,
87 N_("prune remote-tracking branches no longer on remote")),
88 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
89 N_("control recursive fetching of submodules"),
90 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
91 OPT_BOOL(0, "dry-run", &dry_run,
92 N_("dry run")),
93 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
94 OPT_BOOL('u', "update-head-ok", &update_head_ok,
95 N_("allow updating of HEAD ref")),
96 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
97 OPT_STRING(0, "depth", &depth, N_("depth"),
98 N_("deepen history of shallow clone")),
99 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
100 N_("convert to a complete repository"),
101 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
102 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
103 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
104 { OPTION_STRING, 0, "recurse-submodules-default",
105 &recurse_submodules_default, NULL,
106 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
107 OPT_BOOL(0, "update-shallow", &update_shallow,
108 N_("accept refs that update .git/shallow")),
109 OPT_END()
112 static void unlock_pack(void)
114 if (gtransport)
115 transport_unlock_pack(gtransport);
116 if (gsecondary)
117 transport_unlock_pack(gsecondary);
120 static void unlock_pack_on_signal(int signo)
122 unlock_pack();
123 sigchain_pop(signo);
124 raise(signo);
127 static void add_merge_config(struct ref **head,
128 const struct ref *remote_refs,
129 struct branch *branch,
130 struct ref ***tail)
132 int i;
134 for (i = 0; i < branch->merge_nr; i++) {
135 struct ref *rm, **old_tail = *tail;
136 struct refspec refspec;
138 for (rm = *head; rm; rm = rm->next) {
139 if (branch_merge_matches(branch, i, rm->name)) {
140 rm->fetch_head_status = FETCH_HEAD_MERGE;
141 break;
144 if (rm)
145 continue;
148 * Not fetched to a remote-tracking branch? We need to fetch
149 * it anyway to allow this branch's "branch.$name.merge"
150 * to be honored by 'git pull', but we do not have to
151 * fail if branch.$name.merge is misconfigured to point
152 * at a nonexisting branch. If we were indeed called by
153 * 'git pull', it will notice the misconfiguration because
154 * there is no entry in the resulting FETCH_HEAD marked
155 * for merging.
157 memset(&refspec, 0, sizeof(refspec));
158 refspec.src = branch->merge[i]->src;
159 get_fetch_map(remote_refs, &refspec, tail, 1);
160 for (rm = *old_tail; rm; rm = rm->next)
161 rm->fetch_head_status = FETCH_HEAD_MERGE;
165 static void find_non_local_tags(struct transport *transport,
166 struct ref **head,
167 struct ref ***tail);
169 static struct ref *get_ref_map(struct transport *transport,
170 struct refspec *refs, int ref_count, int tags,
171 int *autotags)
173 int i;
174 struct ref *rm;
175 struct ref *ref_map = NULL;
176 struct ref **tail = &ref_map;
178 const struct ref *remote_refs = transport_get_remote_refs(transport);
180 if (ref_count || tags == TAGS_SET) {
181 struct ref **old_tail;
183 for (i = 0; i < ref_count; i++) {
184 get_fetch_map(remote_refs, &refs[i], &tail, 0);
185 if (refs[i].dst && refs[i].dst[0])
186 *autotags = 1;
188 /* Merge everything on the command line, but not --tags */
189 for (rm = ref_map; rm; rm = rm->next)
190 rm->fetch_head_status = FETCH_HEAD_MERGE;
191 if (tags == TAGS_SET)
192 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
195 * For any refs that we happen to be fetching via command-line
196 * arguments, take the opportunity to update their configured
197 * counterparts. However, we do not want to mention these
198 * entries in FETCH_HEAD at all, as they would simply be
199 * duplicates of existing entries.
201 old_tail = tail;
202 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
203 get_fetch_map(ref_map, &transport->remote->fetch[i],
204 &tail, 1);
205 for (rm = *old_tail; rm; rm = rm->next)
206 rm->fetch_head_status = FETCH_HEAD_IGNORE;
207 } else {
208 /* Use the defaults */
209 struct remote *remote = transport->remote;
210 struct branch *branch = branch_get(NULL);
211 int has_merge = branch_has_merge_config(branch);
212 if (remote &&
213 (remote->fetch_refspec_nr ||
214 /* Note: has_merge implies non-NULL branch->remote_name */
215 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
216 for (i = 0; i < remote->fetch_refspec_nr; i++) {
217 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
218 if (remote->fetch[i].dst &&
219 remote->fetch[i].dst[0])
220 *autotags = 1;
221 if (!i && !has_merge && ref_map &&
222 !remote->fetch[0].pattern)
223 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
226 * if the remote we're fetching from is the same
227 * as given in branch.<name>.remote, we add the
228 * ref given in branch.<name>.merge, too.
230 * Note: has_merge implies non-NULL branch->remote_name
232 if (has_merge &&
233 !strcmp(branch->remote_name, remote->name))
234 add_merge_config(&ref_map, remote_refs, branch, &tail);
235 } else {
236 ref_map = get_remote_ref(remote_refs, "HEAD");
237 if (!ref_map)
238 die(_("Couldn't find remote ref HEAD"));
239 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
240 tail = &ref_map->next;
243 if (tags == TAGS_DEFAULT && *autotags)
244 find_non_local_tags(transport, &ref_map, &tail);
245 ref_remove_duplicates(ref_map);
247 return ref_map;
250 #define STORE_REF_ERROR_OTHER 1
251 #define STORE_REF_ERROR_DF_CONFLICT 2
253 static int s_update_ref(const char *action,
254 struct ref *ref,
255 int check_old)
257 char msg[1024];
258 char *rla = getenv("GIT_REFLOG_ACTION");
259 static struct ref_lock *lock;
261 if (dry_run)
262 return 0;
263 if (!rla)
264 rla = default_rla.buf;
265 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
266 lock = lock_any_ref_for_update(ref->name,
267 check_old ? ref->old_sha1 : NULL,
268 0, NULL);
269 if (!lock)
270 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
271 STORE_REF_ERROR_OTHER;
272 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
273 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
274 STORE_REF_ERROR_OTHER;
275 return 0;
278 #define REFCOL_WIDTH 10
280 static int update_local_ref(struct ref *ref,
281 const char *remote,
282 const struct ref *remote_ref,
283 struct strbuf *display)
285 struct commit *current = NULL, *updated;
286 enum object_type type;
287 struct branch *current_branch = branch_get(NULL);
288 const char *pretty_ref = prettify_refname(ref->name);
290 type = sha1_object_info(ref->new_sha1, NULL);
291 if (type < 0)
292 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
294 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
295 if (verbosity > 0)
296 strbuf_addf(display, "= %-*s %-*s -> %s",
297 TRANSPORT_SUMMARY(_("[up to date]")),
298 REFCOL_WIDTH, remote, pretty_ref);
299 return 0;
302 if (current_branch &&
303 !strcmp(ref->name, current_branch->name) &&
304 !(update_head_ok || is_bare_repository()) &&
305 !is_null_sha1(ref->old_sha1)) {
307 * If this is the head, and it's not okay to update
308 * the head, and the old value of the head isn't empty...
310 strbuf_addf(display,
311 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
312 TRANSPORT_SUMMARY(_("[rejected]")),
313 REFCOL_WIDTH, remote, pretty_ref);
314 return 1;
317 if (!is_null_sha1(ref->old_sha1) &&
318 !prefixcmp(ref->name, "refs/tags/")) {
319 int r;
320 r = s_update_ref("updating tag", ref, 0);
321 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
322 r ? '!' : '-',
323 TRANSPORT_SUMMARY(_("[tag update]")),
324 REFCOL_WIDTH, remote, pretty_ref,
325 r ? _(" (unable to update local ref)") : "");
326 return r;
329 current = lookup_commit_reference_gently(ref->old_sha1, 1);
330 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
331 if (!current || !updated) {
332 const char *msg;
333 const char *what;
334 int r;
336 * Nicely describe the new ref we're fetching.
337 * Base this on the remote's ref name, as it's
338 * more likely to follow a standard layout.
340 const char *name = remote_ref ? remote_ref->name : "";
341 if (!prefixcmp(name, "refs/tags/")) {
342 msg = "storing tag";
343 what = _("[new tag]");
344 } else if (!prefixcmp(name, "refs/heads/")) {
345 msg = "storing head";
346 what = _("[new branch]");
347 } else {
348 msg = "storing ref";
349 what = _("[new ref]");
352 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
353 (recurse_submodules != RECURSE_SUBMODULES_ON))
354 check_for_new_submodule_commits(ref->new_sha1);
355 r = s_update_ref(msg, ref, 0);
356 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
357 r ? '!' : '*',
358 TRANSPORT_SUMMARY(what),
359 REFCOL_WIDTH, remote, pretty_ref,
360 r ? _(" (unable to update local ref)") : "");
361 return r;
364 if (in_merge_bases(current, updated)) {
365 char quickref[83];
366 int r;
367 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
368 strcat(quickref, "..");
369 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
370 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
371 (recurse_submodules != RECURSE_SUBMODULES_ON))
372 check_for_new_submodule_commits(ref->new_sha1);
373 r = s_update_ref("fast-forward", ref, 1);
374 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
375 r ? '!' : ' ',
376 TRANSPORT_SUMMARY_WIDTH, quickref,
377 REFCOL_WIDTH, remote, pretty_ref,
378 r ? _(" (unable to update local ref)") : "");
379 return r;
380 } else if (force || ref->force) {
381 char quickref[84];
382 int r;
383 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
384 strcat(quickref, "...");
385 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
386 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
387 (recurse_submodules != RECURSE_SUBMODULES_ON))
388 check_for_new_submodule_commits(ref->new_sha1);
389 r = s_update_ref("forced-update", ref, 1);
390 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
391 r ? '!' : '+',
392 TRANSPORT_SUMMARY_WIDTH, quickref,
393 REFCOL_WIDTH, remote, pretty_ref,
394 r ? _("unable to update local ref") : _("forced update"));
395 return r;
396 } else {
397 strbuf_addf(display, "! %-*s %-*s -> %s %s",
398 TRANSPORT_SUMMARY(_("[rejected]")),
399 REFCOL_WIDTH, remote, pretty_ref,
400 _("(non-fast-forward)"));
401 return 1;
405 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
407 struct ref **rm = cb_data;
408 struct ref *ref = *rm;
410 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
411 ref = ref->next;
412 if (!ref)
413 return -1; /* end of the list */
414 *rm = ref->next;
415 hashcpy(sha1, ref->old_sha1);
416 return 0;
419 static int store_updated_refs(const char *raw_url, const char *remote_name,
420 struct ref *ref_map)
422 FILE *fp;
423 struct commit *commit;
424 int url_len, i, shown_url = 0, rc = 0;
425 struct strbuf note = STRBUF_INIT;
426 const char *what, *kind;
427 struct ref *rm;
428 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
429 int want_status;
431 fp = fopen(filename, "a");
432 if (!fp)
433 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
435 if (raw_url)
436 url = transport_anonymize_url(raw_url);
437 else
438 url = xstrdup("foreign");
440 rm = ref_map;
441 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
442 rc = error(_("%s did not send all necessary objects\n"), url);
443 goto abort;
447 * We do a pass for each fetch_head_status type in their enum order, so
448 * merged entries are written before not-for-merge. That lets readers
449 * use FETCH_HEAD as a refname to refer to the ref to be merged.
451 for (want_status = FETCH_HEAD_MERGE;
452 want_status <= FETCH_HEAD_IGNORE;
453 want_status++) {
454 for (rm = ref_map; rm; rm = rm->next) {
455 struct ref *ref = NULL;
456 const char *merge_status_marker = "";
458 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
459 if (want_status == FETCH_HEAD_MERGE)
460 warning(_("reject %s because shallow roots are not allowed to be updated"),
461 rm->peer_ref ? rm->peer_ref->name : rm->name);
462 continue;
465 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
466 if (!commit)
467 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
469 if (rm->fetch_head_status != want_status)
470 continue;
472 if (rm->peer_ref) {
473 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
474 strcpy(ref->name, rm->peer_ref->name);
475 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
476 hashcpy(ref->new_sha1, rm->old_sha1);
477 ref->force = rm->peer_ref->force;
481 if (!strcmp(rm->name, "HEAD")) {
482 kind = "";
483 what = "";
485 else if (!prefixcmp(rm->name, "refs/heads/")) {
486 kind = "branch";
487 what = rm->name + 11;
489 else if (!prefixcmp(rm->name, "refs/tags/")) {
490 kind = "tag";
491 what = rm->name + 10;
493 else if (!prefixcmp(rm->name, "refs/remotes/")) {
494 kind = "remote-tracking branch";
495 what = rm->name + 13;
497 else {
498 kind = "";
499 what = rm->name;
502 url_len = strlen(url);
503 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
505 url_len = i + 1;
506 if (4 < i && !strncmp(".git", url + i - 3, 4))
507 url_len = i - 3;
509 strbuf_reset(&note);
510 if (*what) {
511 if (*kind)
512 strbuf_addf(&note, "%s ", kind);
513 strbuf_addf(&note, "'%s' of ", what);
515 switch (rm->fetch_head_status) {
516 case FETCH_HEAD_NOT_FOR_MERGE:
517 merge_status_marker = "not-for-merge";
518 /* fall-through */
519 case FETCH_HEAD_MERGE:
520 fprintf(fp, "%s\t%s\t%s",
521 sha1_to_hex(rm->old_sha1),
522 merge_status_marker,
523 note.buf);
524 for (i = 0; i < url_len; ++i)
525 if ('\n' == url[i])
526 fputs("\\n", fp);
527 else
528 fputc(url[i], fp);
529 fputc('\n', fp);
530 break;
531 default:
532 /* do not write anything to FETCH_HEAD */
533 break;
536 strbuf_reset(&note);
537 if (ref) {
538 rc |= update_local_ref(ref, what, rm, &note);
539 free(ref);
540 } else
541 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
542 TRANSPORT_SUMMARY_WIDTH,
543 *kind ? kind : "branch",
544 REFCOL_WIDTH,
545 *what ? what : "HEAD");
546 if (note.len) {
547 if (verbosity >= 0 && !shown_url) {
548 fprintf(stderr, _("From %.*s\n"),
549 url_len, url);
550 shown_url = 1;
552 if (verbosity >= 0)
553 fprintf(stderr, " %s\n", note.buf);
558 if (rc & STORE_REF_ERROR_DF_CONFLICT)
559 error(_("some local refs could not be updated; try running\n"
560 " 'git remote prune %s' to remove any old, conflicting "
561 "branches"), remote_name);
563 abort:
564 strbuf_release(&note);
565 free(url);
566 fclose(fp);
567 return rc;
571 * We would want to bypass the object transfer altogether if
572 * everything we are going to fetch already exists and is connected
573 * locally.
575 static int quickfetch(struct ref *ref_map)
577 struct ref *rm = ref_map;
580 * If we are deepening a shallow clone we already have these
581 * objects reachable. Running rev-list here will return with
582 * a good (0) exit status and we'll bypass the fetch that we
583 * really need to perform. Claiming failure now will ensure
584 * we perform the network exchange to deepen our history.
586 if (depth)
587 return -1;
588 return check_everything_connected(iterate_ref_map, 1, &rm);
591 static int fetch_refs(struct transport *transport, struct ref *ref_map)
593 int ret = quickfetch(ref_map);
594 if (ret)
595 ret = transport_fetch_refs(transport, ref_map);
596 if (!ret)
597 ret |= store_updated_refs(transport->url,
598 transport->remote->name,
599 ref_map);
600 transport_unlock_pack(transport);
601 return ret;
604 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map)
606 int result = 0;
607 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
608 const char *dangling_msg = dry_run
609 ? _(" (%s will become dangling)")
610 : _(" (%s has become dangling)");
612 for (ref = stale_refs; ref; ref = ref->next) {
613 if (!dry_run)
614 result |= delete_ref(ref->name, NULL, 0);
615 if (verbosity >= 0) {
616 fprintf(stderr, " x %-*s %-*s -> %s\n",
617 TRANSPORT_SUMMARY(_("[deleted]")),
618 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
619 warn_dangling_symref(stderr, dangling_msg, ref->name);
622 free_refs(stale_refs);
623 return result;
626 static int add_existing(const char *refname, const unsigned char *sha1,
627 int flag, void *cbdata)
629 struct string_list *list = (struct string_list *)cbdata;
630 struct string_list_item *item = string_list_insert(list, refname);
631 item->util = xmalloc(20);
632 hashcpy(item->util, sha1);
633 return 0;
636 static int will_fetch(struct ref **head, const unsigned char *sha1)
638 struct ref *rm = *head;
639 while (rm) {
640 if (!hashcmp(rm->old_sha1, sha1))
641 return 1;
642 rm = rm->next;
644 return 0;
647 static void find_non_local_tags(struct transport *transport,
648 struct ref **head,
649 struct ref ***tail)
651 struct string_list existing_refs = STRING_LIST_INIT_DUP;
652 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
653 const struct ref *ref;
654 struct string_list_item *item = NULL;
656 for_each_ref(add_existing, &existing_refs);
657 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
658 if (prefixcmp(ref->name, "refs/tags/"))
659 continue;
662 * The peeled ref always follows the matching base
663 * ref, so if we see a peeled ref that we don't want
664 * to fetch then we can mark the ref entry in the list
665 * as one to ignore by setting util to NULL.
667 if (!suffixcmp(ref->name, "^{}")) {
668 if (item && !has_sha1_file(ref->old_sha1) &&
669 !will_fetch(head, ref->old_sha1) &&
670 !has_sha1_file(item->util) &&
671 !will_fetch(head, item->util))
672 item->util = NULL;
673 item = NULL;
674 continue;
678 * If item is non-NULL here, then we previously saw a
679 * ref not followed by a peeled reference, so we need
680 * to check if it is a lightweight tag that we want to
681 * fetch.
683 if (item && !has_sha1_file(item->util) &&
684 !will_fetch(head, item->util))
685 item->util = NULL;
687 item = NULL;
689 /* skip duplicates and refs that we already have */
690 if (string_list_has_string(&remote_refs, ref->name) ||
691 string_list_has_string(&existing_refs, ref->name))
692 continue;
694 item = string_list_insert(&remote_refs, ref->name);
695 item->util = (void *)ref->old_sha1;
697 string_list_clear(&existing_refs, 1);
700 * We may have a final lightweight tag that needs to be
701 * checked to see if it needs fetching.
703 if (item && !has_sha1_file(item->util) &&
704 !will_fetch(head, item->util))
705 item->util = NULL;
708 * For all the tags in the remote_refs string list,
709 * add them to the list of refs to be fetched
711 for_each_string_list_item(item, &remote_refs) {
712 /* Unless we have already decided to ignore this item... */
713 if (item->util)
715 struct ref *rm = alloc_ref(item->string);
716 rm->peer_ref = alloc_ref(item->string);
717 hashcpy(rm->old_sha1, item->util);
718 **tail = rm;
719 *tail = &rm->next;
723 string_list_clear(&remote_refs, 0);
726 static void check_not_current_branch(struct ref *ref_map)
728 struct branch *current_branch = branch_get(NULL);
730 if (is_bare_repository() || !current_branch)
731 return;
733 for (; ref_map; ref_map = ref_map->next)
734 if (ref_map->peer_ref && !strcmp(current_branch->refname,
735 ref_map->peer_ref->name))
736 die(_("Refusing to fetch into current branch %s "
737 "of non-bare repository"), current_branch->refname);
740 static int truncate_fetch_head(void)
742 char *filename = git_path("FETCH_HEAD");
743 FILE *fp = fopen(filename, "w");
745 if (!fp)
746 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
747 fclose(fp);
748 return 0;
751 static void set_option(struct transport *transport, const char *name, const char *value)
753 int r = transport_set_option(transport, name, value);
754 if (r < 0)
755 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
756 name, value, transport->url);
757 if (r > 0)
758 warning(_("Option \"%s\" is ignored for %s\n"),
759 name, transport->url);
762 static struct transport *prepare_transport(struct remote *remote)
764 struct transport *transport;
765 transport = transport_get(remote, NULL);
766 transport_set_verbosity(transport, verbosity, progress);
767 if (upload_pack)
768 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
769 if (keep)
770 set_option(transport, TRANS_OPT_KEEP, "yes");
771 if (depth)
772 set_option(transport, TRANS_OPT_DEPTH, depth);
773 if (update_shallow)
774 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
775 return transport;
778 static void backfill_tags(struct transport *transport, struct ref *ref_map)
780 if (transport->cannot_reuse) {
781 gsecondary = prepare_transport(transport->remote);
782 transport = gsecondary;
785 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
786 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
787 fetch_refs(transport, ref_map);
789 if (gsecondary) {
790 transport_disconnect(gsecondary);
791 gsecondary = NULL;
795 static int do_fetch(struct transport *transport,
796 struct refspec *refs, int ref_count)
798 struct string_list existing_refs = STRING_LIST_INIT_DUP;
799 struct ref *ref_map;
800 struct ref *rm;
801 int autotags = (transport->remote->fetch_tags == 1);
802 int retcode = 0;
804 for_each_ref(add_existing, &existing_refs);
806 if (tags == TAGS_DEFAULT) {
807 if (transport->remote->fetch_tags == 2)
808 tags = TAGS_SET;
809 if (transport->remote->fetch_tags == -1)
810 tags = TAGS_UNSET;
813 if (!transport->get_refs_list || !transport->fetch)
814 die(_("Don't know how to fetch from %s"), transport->url);
816 /* if not appending, truncate FETCH_HEAD */
817 if (!append && !dry_run) {
818 retcode = truncate_fetch_head();
819 if (retcode)
820 goto cleanup;
823 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
824 if (!update_head_ok)
825 check_not_current_branch(ref_map);
827 for (rm = ref_map; rm; rm = rm->next) {
828 if (rm->peer_ref) {
829 struct string_list_item *peer_item =
830 string_list_lookup(&existing_refs,
831 rm->peer_ref->name);
832 if (peer_item)
833 hashcpy(rm->peer_ref->old_sha1,
834 peer_item->util);
838 if (tags == TAGS_DEFAULT && autotags)
839 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
840 if (fetch_refs(transport, ref_map)) {
841 free_refs(ref_map);
842 retcode = 1;
843 goto cleanup;
845 if (prune) {
847 * If --tags was specified, pretend that the user gave us
848 * the canonical tags refspec
850 if (tags == TAGS_SET) {
851 const char *tags_str = "refs/tags/*:refs/tags/*";
852 struct refspec *tags_refspec, *refspec;
854 /* Copy the refspec and add the tags to it */
855 refspec = xcalloc(ref_count + 1, sizeof(struct refspec));
856 tags_refspec = parse_fetch_refspec(1, &tags_str);
857 memcpy(refspec, refs, ref_count * sizeof(struct refspec));
858 memcpy(&refspec[ref_count], tags_refspec, sizeof(struct refspec));
859 ref_count++;
861 prune_refs(refspec, ref_count, ref_map);
863 ref_count--;
864 /* The rest of the strings belong to fetch_one */
865 free_refspec(1, tags_refspec);
866 free(refspec);
867 } else if (ref_count) {
868 prune_refs(refs, ref_count, ref_map);
869 } else {
870 prune_refs(transport->remote->fetch, transport->remote->fetch_refspec_nr, ref_map);
873 free_refs(ref_map);
875 /* if neither --no-tags nor --tags was specified, do automated tag
876 * following ... */
877 if (tags == TAGS_DEFAULT && autotags) {
878 struct ref **tail = &ref_map;
879 ref_map = NULL;
880 find_non_local_tags(transport, &ref_map, &tail);
881 if (ref_map)
882 backfill_tags(transport, ref_map);
883 free_refs(ref_map);
886 cleanup:
887 string_list_clear(&existing_refs, 1);
888 return retcode;
891 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
893 struct string_list *list = priv;
894 if (!remote->skip_default_update)
895 string_list_append(list, remote->name);
896 return 0;
899 struct remote_group_data {
900 const char *name;
901 struct string_list *list;
904 static int get_remote_group(const char *key, const char *value, void *priv)
906 struct remote_group_data *g = priv;
908 if (!prefixcmp(key, "remotes.") &&
909 !strcmp(key + 8, g->name)) {
910 /* split list by white space */
911 int space = strcspn(value, " \t\n");
912 while (*value) {
913 if (space > 1) {
914 string_list_append(g->list,
915 xstrndup(value, space));
917 value += space + (value[space] != '\0');
918 space = strcspn(value, " \t\n");
922 return 0;
925 static int add_remote_or_group(const char *name, struct string_list *list)
927 int prev_nr = list->nr;
928 struct remote_group_data g;
929 g.name = name; g.list = list;
931 git_config(get_remote_group, &g);
932 if (list->nr == prev_nr) {
933 struct remote *remote;
934 if (!remote_is_configured(name))
935 return 0;
936 remote = remote_get(name);
937 string_list_append(list, remote->name);
939 return 1;
942 static void add_options_to_argv(struct argv_array *argv)
944 if (dry_run)
945 argv_array_push(argv, "--dry-run");
946 if (prune > 0)
947 argv_array_push(argv, "--prune");
948 if (update_head_ok)
949 argv_array_push(argv, "--update-head-ok");
950 if (force)
951 argv_array_push(argv, "--force");
952 if (keep)
953 argv_array_push(argv, "--keep");
954 if (recurse_submodules == RECURSE_SUBMODULES_ON)
955 argv_array_push(argv, "--recurse-submodules");
956 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
957 argv_array_push(argv, "--recurse-submodules=on-demand");
958 if (tags == TAGS_SET)
959 argv_array_push(argv, "--tags");
960 else if (tags == TAGS_UNSET)
961 argv_array_push(argv, "--no-tags");
962 if (verbosity >= 2)
963 argv_array_push(argv, "-v");
964 if (verbosity >= 1)
965 argv_array_push(argv, "-v");
966 else if (verbosity < 0)
967 argv_array_push(argv, "-q");
971 static int fetch_multiple(struct string_list *list)
973 int i, result = 0;
974 struct argv_array argv = ARGV_ARRAY_INIT;
976 if (!append && !dry_run) {
977 int errcode = truncate_fetch_head();
978 if (errcode)
979 return errcode;
982 argv_array_pushl(&argv, "fetch", "--append", NULL);
983 add_options_to_argv(&argv);
985 for (i = 0; i < list->nr; i++) {
986 const char *name = list->items[i].string;
987 argv_array_push(&argv, name);
988 if (verbosity >= 0)
989 printf(_("Fetching %s\n"), name);
990 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
991 error(_("Could not fetch %s"), name);
992 result = 1;
994 argv_array_pop(&argv);
997 argv_array_clear(&argv);
998 return result;
1001 static int fetch_one(struct remote *remote, int argc, const char **argv)
1003 int i;
1004 static const char **refs = NULL;
1005 struct refspec *refspec;
1006 int ref_nr = 0;
1007 int exit_code;
1009 if (!remote)
1010 die(_("No remote repository specified. Please, specify either a URL or a\n"
1011 "remote name from which new revisions should be fetched."));
1013 gtransport = prepare_transport(remote);
1015 if (prune < 0) {
1016 /* no command line request */
1017 if (0 <= gtransport->remote->prune)
1018 prune = gtransport->remote->prune;
1019 else if (0 <= fetch_prune_config)
1020 prune = fetch_prune_config;
1021 else
1022 prune = PRUNE_BY_DEFAULT;
1025 if (argc > 0) {
1026 int j = 0;
1027 refs = xcalloc(argc + 1, sizeof(const char *));
1028 for (i = 0; i < argc; i++) {
1029 if (!strcmp(argv[i], "tag")) {
1030 char *ref;
1031 i++;
1032 if (i >= argc)
1033 die(_("You need to specify a tag name."));
1034 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1035 strcpy(ref, "refs/tags/");
1036 strcat(ref, argv[i]);
1037 strcat(ref, ":refs/tags/");
1038 strcat(ref, argv[i]);
1039 refs[j++] = ref;
1040 } else
1041 refs[j++] = argv[i];
1043 refs[j] = NULL;
1044 ref_nr = j;
1047 sigchain_push_common(unlock_pack_on_signal);
1048 atexit(unlock_pack);
1049 refspec = parse_fetch_refspec(ref_nr, refs);
1050 exit_code = do_fetch(gtransport, refspec, ref_nr);
1051 free_refspec(ref_nr, refspec);
1052 transport_disconnect(gtransport);
1053 gtransport = NULL;
1054 return exit_code;
1057 int cmd_fetch(int argc, const char **argv, const char *prefix)
1059 int i;
1060 struct string_list list = STRING_LIST_INIT_NODUP;
1061 struct remote *remote;
1062 int result = 0;
1063 static const char *argv_gc_auto[] = {
1064 "gc", "--auto", NULL,
1067 packet_trace_identity("fetch");
1069 /* Record the command line for the reflog */
1070 strbuf_addstr(&default_rla, "fetch");
1071 for (i = 1; i < argc; i++)
1072 strbuf_addf(&default_rla, " %s", argv[i]);
1074 git_config(git_fetch_config, NULL);
1076 argc = parse_options(argc, argv, prefix,
1077 builtin_fetch_options, builtin_fetch_usage, 0);
1079 if (unshallow) {
1080 if (depth)
1081 die(_("--depth and --unshallow cannot be used together"));
1082 else if (!is_repository_shallow())
1083 die(_("--unshallow on a complete repository does not make sense"));
1084 else {
1085 static char inf_depth[12];
1086 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1087 depth = inf_depth;
1091 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1092 if (recurse_submodules_default) {
1093 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1094 set_config_fetch_recurse_submodules(arg);
1096 gitmodules_config();
1097 git_config(submodule_config, NULL);
1100 if (all) {
1101 if (argc == 1)
1102 die(_("fetch --all does not take a repository argument"));
1103 else if (argc > 1)
1104 die(_("fetch --all does not make sense with refspecs"));
1105 (void) for_each_remote(get_one_remote_for_fetch, &list);
1106 result = fetch_multiple(&list);
1107 } else if (argc == 0) {
1108 /* No arguments -- use default remote */
1109 remote = remote_get(NULL);
1110 result = fetch_one(remote, argc, argv);
1111 } else if (multiple) {
1112 /* All arguments are assumed to be remotes or groups */
1113 for (i = 0; i < argc; i++)
1114 if (!add_remote_or_group(argv[i], &list))
1115 die(_("No such remote or remote group: %s"), argv[i]);
1116 result = fetch_multiple(&list);
1117 } else {
1118 /* Single remote or group */
1119 (void) add_remote_or_group(argv[0], &list);
1120 if (list.nr > 1) {
1121 /* More than one remote */
1122 if (argc > 1)
1123 die(_("Fetching a group and specifying refspecs does not make sense"));
1124 result = fetch_multiple(&list);
1125 } else {
1126 /* Zero or one remotes */
1127 remote = remote_get(argv[0]);
1128 result = fetch_one(remote, argc-1, argv+1);
1132 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1133 struct argv_array options = ARGV_ARRAY_INIT;
1135 add_options_to_argv(&options);
1136 result = fetch_populated_submodules(&options,
1137 submodule_prefix,
1138 recurse_submodules,
1139 verbosity < 0);
1140 argv_array_clear(&options);
1143 /* All names were strdup()ed or strndup()ed */
1144 list.strdup_strings = 1;
1145 string_list_clear(&list, 0);
1147 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1149 return result;