Merge branch 'mm/mv-file-to-no-such-dir-with-slash'
[alt-git.git] / builtin / fetch.c
blob09825c84d731014e075a6f77791f0681b7c4efb0
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;
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;
47 static int shown_url = 0;
49 static int option_parse_recurse_submodules(const struct option *opt,
50 const char *arg, int unset)
52 if (unset) {
53 recurse_submodules = RECURSE_SUBMODULES_OFF;
54 } else {
55 if (arg)
56 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
57 else
58 recurse_submodules = RECURSE_SUBMODULES_ON;
60 return 0;
63 static int git_fetch_config(const char *k, const char *v, void *cb)
65 if (!strcmp(k, "fetch.prune")) {
66 fetch_prune_config = git_config_bool(k, v);
67 return 0;
69 return 0;
72 static struct option builtin_fetch_options[] = {
73 OPT__VERBOSITY(&verbosity),
74 OPT_BOOL(0, "all", &all,
75 N_("fetch from all remotes")),
76 OPT_BOOL('a', "append", &append,
77 N_("append to .git/FETCH_HEAD instead of overwriting")),
78 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
79 N_("path to upload pack on remote end")),
80 OPT__FORCE(&force, N_("force overwrite of local branch")),
81 OPT_BOOL('m', "multiple", &multiple,
82 N_("fetch from multiple remotes")),
83 OPT_SET_INT('t', "tags", &tags,
84 N_("fetch all tags and associated objects"), TAGS_SET),
85 OPT_SET_INT('n', NULL, &tags,
86 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
87 OPT_BOOL('p', "prune", &prune,
88 N_("prune remote-tracking branches no longer on remote")),
89 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
90 N_("control recursive fetching of submodules"),
91 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
92 OPT_BOOL(0, "dry-run", &dry_run,
93 N_("dry run")),
94 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
95 OPT_BOOL('u', "update-head-ok", &update_head_ok,
96 N_("allow updating of HEAD ref")),
97 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
98 OPT_STRING(0, "depth", &depth, N_("depth"),
99 N_("deepen history of shallow clone")),
100 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
101 N_("convert to a complete repository"),
102 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
103 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
104 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
105 { OPTION_STRING, 0, "recurse-submodules-default",
106 &recurse_submodules_default, NULL,
107 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
108 OPT_END()
111 static void unlock_pack(void)
113 if (gtransport)
114 transport_unlock_pack(gtransport);
115 if (gsecondary)
116 transport_unlock_pack(gsecondary);
119 static void unlock_pack_on_signal(int signo)
121 unlock_pack();
122 sigchain_pop(signo);
123 raise(signo);
126 static void add_merge_config(struct ref **head,
127 const struct ref *remote_refs,
128 struct branch *branch,
129 struct ref ***tail)
131 int i;
133 for (i = 0; i < branch->merge_nr; i++) {
134 struct ref *rm, **old_tail = *tail;
135 struct refspec refspec;
137 for (rm = *head; rm; rm = rm->next) {
138 if (branch_merge_matches(branch, i, rm->name)) {
139 rm->fetch_head_status = FETCH_HEAD_MERGE;
140 break;
143 if (rm)
144 continue;
147 * Not fetched to a remote-tracking branch? We need to fetch
148 * it anyway to allow this branch's "branch.$name.merge"
149 * to be honored by 'git pull', but we do not have to
150 * fail if branch.$name.merge is misconfigured to point
151 * at a nonexisting branch. If we were indeed called by
152 * 'git pull', it will notice the misconfiguration because
153 * there is no entry in the resulting FETCH_HEAD marked
154 * for merging.
156 memset(&refspec, 0, sizeof(refspec));
157 refspec.src = branch->merge[i]->src;
158 get_fetch_map(remote_refs, &refspec, tail, 1);
159 for (rm = *old_tail; rm; rm = rm->next)
160 rm->fetch_head_status = FETCH_HEAD_MERGE;
164 static int add_existing(const char *refname, const unsigned char *sha1,
165 int flag, void *cbdata)
167 struct string_list *list = (struct string_list *)cbdata;
168 struct string_list_item *item = string_list_insert(list, refname);
169 item->util = xmalloc(20);
170 hashcpy(item->util, sha1);
171 return 0;
174 static int will_fetch(struct ref **head, const unsigned char *sha1)
176 struct ref *rm = *head;
177 while (rm) {
178 if (!hashcmp(rm->old_sha1, sha1))
179 return 1;
180 rm = rm->next;
182 return 0;
185 static void find_non_local_tags(struct transport *transport,
186 struct ref **head,
187 struct ref ***tail)
189 struct string_list existing_refs = STRING_LIST_INIT_DUP;
190 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
191 const struct ref *ref;
192 struct string_list_item *item = NULL;
194 for_each_ref(add_existing, &existing_refs);
195 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
196 if (!starts_with(ref->name, "refs/tags/"))
197 continue;
200 * The peeled ref always follows the matching base
201 * ref, so if we see a peeled ref that we don't want
202 * to fetch then we can mark the ref entry in the list
203 * as one to ignore by setting util to NULL.
205 if (ends_with(ref->name, "^{}")) {
206 if (item && !has_sha1_file(ref->old_sha1) &&
207 !will_fetch(head, ref->old_sha1) &&
208 !has_sha1_file(item->util) &&
209 !will_fetch(head, item->util))
210 item->util = NULL;
211 item = NULL;
212 continue;
216 * If item is non-NULL here, then we previously saw a
217 * ref not followed by a peeled reference, so we need
218 * to check if it is a lightweight tag that we want to
219 * fetch.
221 if (item && !has_sha1_file(item->util) &&
222 !will_fetch(head, item->util))
223 item->util = NULL;
225 item = NULL;
227 /* skip duplicates and refs that we already have */
228 if (string_list_has_string(&remote_refs, ref->name) ||
229 string_list_has_string(&existing_refs, ref->name))
230 continue;
232 item = string_list_insert(&remote_refs, ref->name);
233 item->util = (void *)ref->old_sha1;
235 string_list_clear(&existing_refs, 1);
238 * We may have a final lightweight tag that needs to be
239 * checked to see if it needs fetching.
241 if (item && !has_sha1_file(item->util) &&
242 !will_fetch(head, item->util))
243 item->util = NULL;
246 * For all the tags in the remote_refs string list,
247 * add them to the list of refs to be fetched
249 for_each_string_list_item(item, &remote_refs) {
250 /* Unless we have already decided to ignore this item... */
251 if (item->util)
253 struct ref *rm = alloc_ref(item->string);
254 rm->peer_ref = alloc_ref(item->string);
255 hashcpy(rm->old_sha1, item->util);
256 **tail = rm;
257 *tail = &rm->next;
261 string_list_clear(&remote_refs, 0);
264 static struct ref *get_ref_map(struct transport *transport,
265 struct refspec *refspecs, int refspec_count,
266 int tags, int *autotags)
268 int i;
269 struct ref *rm;
270 struct ref *ref_map = NULL;
271 struct ref **tail = &ref_map;
273 /* opportunistically-updated references: */
274 struct ref *orefs = NULL, **oref_tail = &orefs;
276 const struct ref *remote_refs = transport_get_remote_refs(transport);
278 if (refspec_count) {
279 for (i = 0; i < refspec_count; i++) {
280 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
281 if (refspecs[i].dst && refspecs[i].dst[0])
282 *autotags = 1;
284 /* Merge everything on the command line (but not --tags) */
285 for (rm = ref_map; rm; rm = rm->next)
286 rm->fetch_head_status = FETCH_HEAD_MERGE;
289 * For any refs that we happen to be fetching via
290 * command-line arguments, the destination ref might
291 * have been missing or have been different than the
292 * remote-tracking ref that would be derived from the
293 * configured refspec. In these cases, we want to
294 * take the opportunity to update their configured
295 * remote-tracking reference. However, we do not want
296 * to mention these entries in FETCH_HEAD at all, as
297 * they would simply be duplicates of existing
298 * entries, so we set them FETCH_HEAD_IGNORE below.
300 * We compute these entries now, based only on the
301 * refspecs specified on the command line. But we add
302 * them to the list following the refspecs resulting
303 * from the tags option so that one of the latter,
304 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
305 * by ref_remove_duplicates() in favor of one of these
306 * opportunistic entries with FETCH_HEAD_IGNORE.
308 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
309 get_fetch_map(ref_map, &transport->remote->fetch[i],
310 &oref_tail, 1);
312 if (tags == TAGS_SET)
313 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
314 } else {
315 /* Use the defaults */
316 struct remote *remote = transport->remote;
317 struct branch *branch = branch_get(NULL);
318 int has_merge = branch_has_merge_config(branch);
319 if (remote &&
320 (remote->fetch_refspec_nr ||
321 /* Note: has_merge implies non-NULL branch->remote_name */
322 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
323 for (i = 0; i < remote->fetch_refspec_nr; i++) {
324 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
325 if (remote->fetch[i].dst &&
326 remote->fetch[i].dst[0])
327 *autotags = 1;
328 if (!i && !has_merge && ref_map &&
329 !remote->fetch[0].pattern)
330 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
333 * if the remote we're fetching from is the same
334 * as given in branch.<name>.remote, we add the
335 * ref given in branch.<name>.merge, too.
337 * Note: has_merge implies non-NULL branch->remote_name
339 if (has_merge &&
340 !strcmp(branch->remote_name, remote->name))
341 add_merge_config(&ref_map, remote_refs, branch, &tail);
342 } else {
343 ref_map = get_remote_ref(remote_refs, "HEAD");
344 if (!ref_map)
345 die(_("Couldn't find remote ref HEAD"));
346 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
347 tail = &ref_map->next;
351 if (tags == TAGS_SET)
352 /* also fetch all tags */
353 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
354 else if (tags == TAGS_DEFAULT && *autotags)
355 find_non_local_tags(transport, &ref_map, &tail);
357 /* Now append any refs to be updated opportunistically: */
358 *tail = orefs;
359 for (rm = orefs; rm; rm = rm->next) {
360 rm->fetch_head_status = FETCH_HEAD_IGNORE;
361 tail = &rm->next;
364 return ref_remove_duplicates(ref_map);
367 #define STORE_REF_ERROR_OTHER 1
368 #define STORE_REF_ERROR_DF_CONFLICT 2
370 static int s_update_ref(const char *action,
371 struct ref *ref,
372 int check_old)
374 char msg[1024];
375 char *rla = getenv("GIT_REFLOG_ACTION");
376 static struct ref_lock *lock;
378 if (dry_run)
379 return 0;
380 if (!rla)
381 rla = default_rla.buf;
382 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
383 lock = lock_any_ref_for_update(ref->name,
384 check_old ? ref->old_sha1 : NULL,
385 0, NULL);
386 if (!lock)
387 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
388 STORE_REF_ERROR_OTHER;
389 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
390 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
391 STORE_REF_ERROR_OTHER;
392 return 0;
395 #define REFCOL_WIDTH 10
397 static int update_local_ref(struct ref *ref,
398 const char *remote,
399 const struct ref *remote_ref,
400 struct strbuf *display)
402 struct commit *current = NULL, *updated;
403 enum object_type type;
404 struct branch *current_branch = branch_get(NULL);
405 const char *pretty_ref = prettify_refname(ref->name);
407 type = sha1_object_info(ref->new_sha1, NULL);
408 if (type < 0)
409 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
411 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
412 if (verbosity > 0)
413 strbuf_addf(display, "= %-*s %-*s -> %s",
414 TRANSPORT_SUMMARY(_("[up to date]")),
415 REFCOL_WIDTH, remote, pretty_ref);
416 return 0;
419 if (current_branch &&
420 !strcmp(ref->name, current_branch->name) &&
421 !(update_head_ok || is_bare_repository()) &&
422 !is_null_sha1(ref->old_sha1)) {
424 * If this is the head, and it's not okay to update
425 * the head, and the old value of the head isn't empty...
427 strbuf_addf(display,
428 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
429 TRANSPORT_SUMMARY(_("[rejected]")),
430 REFCOL_WIDTH, remote, pretty_ref);
431 return 1;
434 if (!is_null_sha1(ref->old_sha1) &&
435 starts_with(ref->name, "refs/tags/")) {
436 int r;
437 r = s_update_ref("updating tag", ref, 0);
438 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
439 r ? '!' : '-',
440 TRANSPORT_SUMMARY(_("[tag update]")),
441 REFCOL_WIDTH, remote, pretty_ref,
442 r ? _(" (unable to update local ref)") : "");
443 return r;
446 current = lookup_commit_reference_gently(ref->old_sha1, 1);
447 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
448 if (!current || !updated) {
449 const char *msg;
450 const char *what;
451 int r;
453 * Nicely describe the new ref we're fetching.
454 * Base this on the remote's ref name, as it's
455 * more likely to follow a standard layout.
457 const char *name = remote_ref ? remote_ref->name : "";
458 if (starts_with(name, "refs/tags/")) {
459 msg = "storing tag";
460 what = _("[new tag]");
461 } else if (starts_with(name, "refs/heads/")) {
462 msg = "storing head";
463 what = _("[new branch]");
464 } else {
465 msg = "storing ref";
466 what = _("[new ref]");
469 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
470 (recurse_submodules != RECURSE_SUBMODULES_ON))
471 check_for_new_submodule_commits(ref->new_sha1);
472 r = s_update_ref(msg, ref, 0);
473 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
474 r ? '!' : '*',
475 TRANSPORT_SUMMARY(what),
476 REFCOL_WIDTH, remote, pretty_ref,
477 r ? _(" (unable to update local ref)") : "");
478 return r;
481 if (in_merge_bases(current, updated)) {
482 char quickref[83];
483 int r;
484 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
485 strcat(quickref, "..");
486 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
487 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
488 (recurse_submodules != RECURSE_SUBMODULES_ON))
489 check_for_new_submodule_commits(ref->new_sha1);
490 r = s_update_ref("fast-forward", ref, 1);
491 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
492 r ? '!' : ' ',
493 TRANSPORT_SUMMARY_WIDTH, quickref,
494 REFCOL_WIDTH, remote, pretty_ref,
495 r ? _(" (unable to update local ref)") : "");
496 return r;
497 } else if (force || ref->force) {
498 char quickref[84];
499 int r;
500 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
501 strcat(quickref, "...");
502 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
503 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
504 (recurse_submodules != RECURSE_SUBMODULES_ON))
505 check_for_new_submodule_commits(ref->new_sha1);
506 r = s_update_ref("forced-update", ref, 1);
507 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
508 r ? '!' : '+',
509 TRANSPORT_SUMMARY_WIDTH, quickref,
510 REFCOL_WIDTH, remote, pretty_ref,
511 r ? _("unable to update local ref") : _("forced update"));
512 return r;
513 } else {
514 strbuf_addf(display, "! %-*s %-*s -> %s %s",
515 TRANSPORT_SUMMARY(_("[rejected]")),
516 REFCOL_WIDTH, remote, pretty_ref,
517 _("(non-fast-forward)"));
518 return 1;
522 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
524 struct ref **rm = cb_data;
525 struct ref *ref = *rm;
527 if (!ref)
528 return -1; /* end of the list */
529 *rm = ref->next;
530 hashcpy(sha1, ref->old_sha1);
531 return 0;
534 static int store_updated_refs(const char *raw_url, const char *remote_name,
535 struct ref *ref_map)
537 FILE *fp;
538 struct commit *commit;
539 int url_len, i, rc = 0;
540 struct strbuf note = STRBUF_INIT;
541 const char *what, *kind;
542 struct ref *rm;
543 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
544 int want_status;
546 fp = fopen(filename, "a");
547 if (!fp)
548 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
550 if (raw_url)
551 url = transport_anonymize_url(raw_url);
552 else
553 url = xstrdup("foreign");
555 rm = ref_map;
556 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
557 rc = error(_("%s did not send all necessary objects\n"), url);
558 goto abort;
562 * We do a pass for each fetch_head_status type in their enum order, so
563 * merged entries are written before not-for-merge. That lets readers
564 * use FETCH_HEAD as a refname to refer to the ref to be merged.
566 for (want_status = FETCH_HEAD_MERGE;
567 want_status <= FETCH_HEAD_IGNORE;
568 want_status++) {
569 for (rm = ref_map; rm; rm = rm->next) {
570 struct ref *ref = NULL;
571 const char *merge_status_marker = "";
573 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
574 if (!commit)
575 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
577 if (rm->fetch_head_status != want_status)
578 continue;
580 if (rm->peer_ref) {
581 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
582 strcpy(ref->name, rm->peer_ref->name);
583 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
584 hashcpy(ref->new_sha1, rm->old_sha1);
585 ref->force = rm->peer_ref->force;
589 if (!strcmp(rm->name, "HEAD")) {
590 kind = "";
591 what = "";
593 else if (starts_with(rm->name, "refs/heads/")) {
594 kind = "branch";
595 what = rm->name + 11;
597 else if (starts_with(rm->name, "refs/tags/")) {
598 kind = "tag";
599 what = rm->name + 10;
601 else if (starts_with(rm->name, "refs/remotes/")) {
602 kind = "remote-tracking branch";
603 what = rm->name + 13;
605 else {
606 kind = "";
607 what = rm->name;
610 url_len = strlen(url);
611 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
613 url_len = i + 1;
614 if (4 < i && !strncmp(".git", url + i - 3, 4))
615 url_len = i - 3;
617 strbuf_reset(&note);
618 if (*what) {
619 if (*kind)
620 strbuf_addf(&note, "%s ", kind);
621 strbuf_addf(&note, "'%s' of ", what);
623 switch (rm->fetch_head_status) {
624 case FETCH_HEAD_NOT_FOR_MERGE:
625 merge_status_marker = "not-for-merge";
626 /* fall-through */
627 case FETCH_HEAD_MERGE:
628 fprintf(fp, "%s\t%s\t%s",
629 sha1_to_hex(rm->old_sha1),
630 merge_status_marker,
631 note.buf);
632 for (i = 0; i < url_len; ++i)
633 if ('\n' == url[i])
634 fputs("\\n", fp);
635 else
636 fputc(url[i], fp);
637 fputc('\n', fp);
638 break;
639 default:
640 /* do not write anything to FETCH_HEAD */
641 break;
644 strbuf_reset(&note);
645 if (ref) {
646 rc |= update_local_ref(ref, what, rm, &note);
647 free(ref);
648 } else
649 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
650 TRANSPORT_SUMMARY_WIDTH,
651 *kind ? kind : "branch",
652 REFCOL_WIDTH,
653 *what ? what : "HEAD");
654 if (note.len) {
655 if (verbosity >= 0 && !shown_url) {
656 fprintf(stderr, _("From %.*s\n"),
657 url_len, url);
658 shown_url = 1;
660 if (verbosity >= 0)
661 fprintf(stderr, " %s\n", note.buf);
666 if (rc & STORE_REF_ERROR_DF_CONFLICT)
667 error(_("some local refs could not be updated; try running\n"
668 " 'git remote prune %s' to remove any old, conflicting "
669 "branches"), remote_name);
671 abort:
672 strbuf_release(&note);
673 free(url);
674 fclose(fp);
675 return rc;
679 * We would want to bypass the object transfer altogether if
680 * everything we are going to fetch already exists and is connected
681 * locally.
683 static int quickfetch(struct ref *ref_map)
685 struct ref *rm = ref_map;
688 * If we are deepening a shallow clone we already have these
689 * objects reachable. Running rev-list here will return with
690 * a good (0) exit status and we'll bypass the fetch that we
691 * really need to perform. Claiming failure now will ensure
692 * we perform the network exchange to deepen our history.
694 if (depth)
695 return -1;
696 return check_everything_connected(iterate_ref_map, 1, &rm);
699 static int fetch_refs(struct transport *transport, struct ref *ref_map)
701 int ret = quickfetch(ref_map);
702 if (ret)
703 ret = transport_fetch_refs(transport, ref_map);
704 if (!ret)
705 ret |= store_updated_refs(transport->url,
706 transport->remote->name,
707 ref_map);
708 transport_unlock_pack(transport);
709 return ret;
712 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
713 const char *raw_url)
715 int url_len, i, result = 0;
716 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
717 char *url;
718 const char *dangling_msg = dry_run
719 ? _(" (%s will become dangling)")
720 : _(" (%s has become dangling)");
722 if (raw_url)
723 url = transport_anonymize_url(raw_url);
724 else
725 url = xstrdup("foreign");
727 url_len = strlen(url);
728 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
731 url_len = i + 1;
732 if (4 < i && !strncmp(".git", url + i - 3, 4))
733 url_len = i - 3;
735 for (ref = stale_refs; ref; ref = ref->next) {
736 if (!dry_run)
737 result |= delete_ref(ref->name, NULL, 0);
738 if (verbosity >= 0 && !shown_url) {
739 fprintf(stderr, _("From %.*s\n"), url_len, url);
740 shown_url = 1;
742 if (verbosity >= 0) {
743 fprintf(stderr, " x %-*s %-*s -> %s\n",
744 TRANSPORT_SUMMARY(_("[deleted]")),
745 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
746 warn_dangling_symref(stderr, dangling_msg, ref->name);
749 free(url);
750 free_refs(stale_refs);
751 return result;
754 static void check_not_current_branch(struct ref *ref_map)
756 struct branch *current_branch = branch_get(NULL);
758 if (is_bare_repository() || !current_branch)
759 return;
761 for (; ref_map; ref_map = ref_map->next)
762 if (ref_map->peer_ref && !strcmp(current_branch->refname,
763 ref_map->peer_ref->name))
764 die(_("Refusing to fetch into current branch %s "
765 "of non-bare repository"), current_branch->refname);
768 static int truncate_fetch_head(void)
770 char *filename = git_path("FETCH_HEAD");
771 FILE *fp = fopen(filename, "w");
773 if (!fp)
774 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
775 fclose(fp);
776 return 0;
779 static void set_option(struct transport *transport, const char *name, const char *value)
781 int r = transport_set_option(transport, name, value);
782 if (r < 0)
783 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
784 name, value, transport->url);
785 if (r > 0)
786 warning(_("Option \"%s\" is ignored for %s\n"),
787 name, transport->url);
790 static struct transport *prepare_transport(struct remote *remote)
792 struct transport *transport;
793 transport = transport_get(remote, NULL);
794 transport_set_verbosity(transport, verbosity, progress);
795 if (upload_pack)
796 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
797 if (keep)
798 set_option(transport, TRANS_OPT_KEEP, "yes");
799 if (depth)
800 set_option(transport, TRANS_OPT_DEPTH, depth);
801 return transport;
804 static void backfill_tags(struct transport *transport, struct ref *ref_map)
806 if (transport->cannot_reuse) {
807 gsecondary = prepare_transport(transport->remote);
808 transport = gsecondary;
811 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
812 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
813 fetch_refs(transport, ref_map);
815 if (gsecondary) {
816 transport_disconnect(gsecondary);
817 gsecondary = NULL;
821 static int do_fetch(struct transport *transport,
822 struct refspec *refs, int ref_count)
824 struct string_list existing_refs = STRING_LIST_INIT_DUP;
825 struct ref *ref_map;
826 struct ref *rm;
827 int autotags = (transport->remote->fetch_tags == 1);
828 int retcode = 0;
830 for_each_ref(add_existing, &existing_refs);
832 if (tags == TAGS_DEFAULT) {
833 if (transport->remote->fetch_tags == 2)
834 tags = TAGS_SET;
835 if (transport->remote->fetch_tags == -1)
836 tags = TAGS_UNSET;
839 if (!transport->get_refs_list || !transport->fetch)
840 die(_("Don't know how to fetch from %s"), transport->url);
842 /* if not appending, truncate FETCH_HEAD */
843 if (!append && !dry_run) {
844 retcode = truncate_fetch_head();
845 if (retcode)
846 goto cleanup;
849 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
850 if (!update_head_ok)
851 check_not_current_branch(ref_map);
853 for (rm = ref_map; rm; rm = rm->next) {
854 if (rm->peer_ref) {
855 struct string_list_item *peer_item =
856 string_list_lookup(&existing_refs,
857 rm->peer_ref->name);
858 if (peer_item)
859 hashcpy(rm->peer_ref->old_sha1,
860 peer_item->util);
864 if (tags == TAGS_DEFAULT && autotags)
865 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
866 if (prune) {
868 * We only prune based on refspecs specified
869 * explicitly (via command line or configuration); we
870 * don't care whether --tags was specified.
872 if (ref_count) {
873 prune_refs(refs, ref_count, ref_map, transport->url);
874 } else {
875 prune_refs(transport->remote->fetch,
876 transport->remote->fetch_refspec_nr,
877 ref_map,
878 transport->url);
881 if (fetch_refs(transport, ref_map)) {
882 free_refs(ref_map);
883 retcode = 1;
884 goto cleanup;
886 free_refs(ref_map);
888 /* if neither --no-tags nor --tags was specified, do automated tag
889 * following ... */
890 if (tags == TAGS_DEFAULT && autotags) {
891 struct ref **tail = &ref_map;
892 ref_map = NULL;
893 find_non_local_tags(transport, &ref_map, &tail);
894 if (ref_map)
895 backfill_tags(transport, ref_map);
896 free_refs(ref_map);
899 cleanup:
900 string_list_clear(&existing_refs, 1);
901 return retcode;
904 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
906 struct string_list *list = priv;
907 if (!remote->skip_default_update)
908 string_list_append(list, remote->name);
909 return 0;
912 struct remote_group_data {
913 const char *name;
914 struct string_list *list;
917 static int get_remote_group(const char *key, const char *value, void *priv)
919 struct remote_group_data *g = priv;
921 if (starts_with(key, "remotes.") &&
922 !strcmp(key + 8, g->name)) {
923 /* split list by white space */
924 int space = strcspn(value, " \t\n");
925 while (*value) {
926 if (space > 1) {
927 string_list_append(g->list,
928 xstrndup(value, space));
930 value += space + (value[space] != '\0');
931 space = strcspn(value, " \t\n");
935 return 0;
938 static int add_remote_or_group(const char *name, struct string_list *list)
940 int prev_nr = list->nr;
941 struct remote_group_data g;
942 g.name = name; g.list = list;
944 git_config(get_remote_group, &g);
945 if (list->nr == prev_nr) {
946 struct remote *remote;
947 if (!remote_is_configured(name))
948 return 0;
949 remote = remote_get(name);
950 string_list_append(list, remote->name);
952 return 1;
955 static void add_options_to_argv(struct argv_array *argv)
957 if (dry_run)
958 argv_array_push(argv, "--dry-run");
959 if (prune != -1)
960 argv_array_push(argv, prune ? "--prune" : "--no-prune");
961 if (update_head_ok)
962 argv_array_push(argv, "--update-head-ok");
963 if (force)
964 argv_array_push(argv, "--force");
965 if (keep)
966 argv_array_push(argv, "--keep");
967 if (recurse_submodules == RECURSE_SUBMODULES_ON)
968 argv_array_push(argv, "--recurse-submodules");
969 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
970 argv_array_push(argv, "--recurse-submodules=on-demand");
971 if (tags == TAGS_SET)
972 argv_array_push(argv, "--tags");
973 else if (tags == TAGS_UNSET)
974 argv_array_push(argv, "--no-tags");
975 if (verbosity >= 2)
976 argv_array_push(argv, "-v");
977 if (verbosity >= 1)
978 argv_array_push(argv, "-v");
979 else if (verbosity < 0)
980 argv_array_push(argv, "-q");
984 static int fetch_multiple(struct string_list *list)
986 int i, result = 0;
987 struct argv_array argv = ARGV_ARRAY_INIT;
989 if (!append && !dry_run) {
990 int errcode = truncate_fetch_head();
991 if (errcode)
992 return errcode;
995 argv_array_pushl(&argv, "fetch", "--append", NULL);
996 add_options_to_argv(&argv);
998 for (i = 0; i < list->nr; i++) {
999 const char *name = list->items[i].string;
1000 argv_array_push(&argv, name);
1001 if (verbosity >= 0)
1002 printf(_("Fetching %s\n"), name);
1003 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1004 error(_("Could not fetch %s"), name);
1005 result = 1;
1007 argv_array_pop(&argv);
1010 argv_array_clear(&argv);
1011 return result;
1014 static int fetch_one(struct remote *remote, int argc, const char **argv)
1016 int i;
1017 static const char **refs = NULL;
1018 struct refspec *refspec;
1019 int ref_nr = 0;
1020 int exit_code;
1022 if (!remote)
1023 die(_("No remote repository specified. Please, specify either a URL or a\n"
1024 "remote name from which new revisions should be fetched."));
1026 gtransport = prepare_transport(remote);
1028 if (prune < 0) {
1029 /* no command line request */
1030 if (0 <= gtransport->remote->prune)
1031 prune = gtransport->remote->prune;
1032 else if (0 <= fetch_prune_config)
1033 prune = fetch_prune_config;
1034 else
1035 prune = PRUNE_BY_DEFAULT;
1038 if (argc > 0) {
1039 int j = 0;
1040 refs = xcalloc(argc + 1, sizeof(const char *));
1041 for (i = 0; i < argc; i++) {
1042 if (!strcmp(argv[i], "tag")) {
1043 char *ref;
1044 i++;
1045 if (i >= argc)
1046 die(_("You need to specify a tag name."));
1047 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1048 strcpy(ref, "refs/tags/");
1049 strcat(ref, argv[i]);
1050 strcat(ref, ":refs/tags/");
1051 strcat(ref, argv[i]);
1052 refs[j++] = ref;
1053 } else
1054 refs[j++] = argv[i];
1056 refs[j] = NULL;
1057 ref_nr = j;
1060 sigchain_push_common(unlock_pack_on_signal);
1061 atexit(unlock_pack);
1062 refspec = parse_fetch_refspec(ref_nr, refs);
1063 exit_code = do_fetch(gtransport, refspec, ref_nr);
1064 free_refspec(ref_nr, refspec);
1065 transport_disconnect(gtransport);
1066 gtransport = NULL;
1067 return exit_code;
1070 int cmd_fetch(int argc, const char **argv, const char *prefix)
1072 int i;
1073 struct string_list list = STRING_LIST_INIT_NODUP;
1074 struct remote *remote;
1075 int result = 0;
1076 static const char *argv_gc_auto[] = {
1077 "gc", "--auto", NULL,
1080 packet_trace_identity("fetch");
1082 /* Record the command line for the reflog */
1083 strbuf_addstr(&default_rla, "fetch");
1084 for (i = 1; i < argc; i++)
1085 strbuf_addf(&default_rla, " %s", argv[i]);
1087 git_config(git_fetch_config, NULL);
1089 argc = parse_options(argc, argv, prefix,
1090 builtin_fetch_options, builtin_fetch_usage, 0);
1092 if (unshallow) {
1093 if (depth)
1094 die(_("--depth and --unshallow cannot be used together"));
1095 else if (!is_repository_shallow())
1096 die(_("--unshallow on a complete repository does not make sense"));
1097 else {
1098 static char inf_depth[12];
1099 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1100 depth = inf_depth;
1104 /* no need to be strict, transport_set_option() will validate it again */
1105 if (depth && atoi(depth) < 1)
1106 die(_("depth %s is not a positive number"), depth);
1108 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1109 if (recurse_submodules_default) {
1110 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1111 set_config_fetch_recurse_submodules(arg);
1113 gitmodules_config();
1114 git_config(submodule_config, NULL);
1117 if (all) {
1118 if (argc == 1)
1119 die(_("fetch --all does not take a repository argument"));
1120 else if (argc > 1)
1121 die(_("fetch --all does not make sense with refspecs"));
1122 (void) for_each_remote(get_one_remote_for_fetch, &list);
1123 result = fetch_multiple(&list);
1124 } else if (argc == 0) {
1125 /* No arguments -- use default remote */
1126 remote = remote_get(NULL);
1127 result = fetch_one(remote, argc, argv);
1128 } else if (multiple) {
1129 /* All arguments are assumed to be remotes or groups */
1130 for (i = 0; i < argc; i++)
1131 if (!add_remote_or_group(argv[i], &list))
1132 die(_("No such remote or remote group: %s"), argv[i]);
1133 result = fetch_multiple(&list);
1134 } else {
1135 /* Single remote or group */
1136 (void) add_remote_or_group(argv[0], &list);
1137 if (list.nr > 1) {
1138 /* More than one remote */
1139 if (argc > 1)
1140 die(_("Fetching a group and specifying refspecs does not make sense"));
1141 result = fetch_multiple(&list);
1142 } else {
1143 /* Zero or one remotes */
1144 remote = remote_get(argv[0]);
1145 result = fetch_one(remote, argc-1, argv+1);
1149 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1150 struct argv_array options = ARGV_ARRAY_INIT;
1152 add_options_to_argv(&options);
1153 result = fetch_populated_submodules(&options,
1154 submodule_prefix,
1155 recurse_submodules,
1156 verbosity < 0);
1157 argv_array_clear(&options);
1160 /* All names were strdup()ed or strndup()ed */
1161 list.strdup_strings = 1;
1162 string_list_clear(&list, 0);
1164 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1166 return result;