do not die on error of parsing fetchrecursesubmodules option
[git/jrn.git] / builtin / fetch.c
blob706326fcc9158a48158f0dc4f6159e2ada42f8b5
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-config.h"
16 #include "submodule.h"
17 #include "connected.h"
18 #include "argv-array.h"
20 static const char * const builtin_fetch_usage[] = {
21 N_("git fetch [<options>] [<repository> [<refspec>...]]"),
22 N_("git fetch [<options>] <group>"),
23 N_("git fetch --multiple [<options>] [(<repository> | <group>)...]"),
24 N_("git fetch --all [<options>]"),
25 NULL
28 enum {
29 TAGS_UNSET = 0,
30 TAGS_DEFAULT = 1,
31 TAGS_SET = 2
34 static int fetch_prune_config = -1; /* unspecified */
35 static int prune = -1; /* unspecified */
36 #define PRUNE_BY_DEFAULT 0 /* do we prune by default? */
38 static int all, append, dry_run, force, keep, multiple, update_head_ok, verbosity;
39 static int progress = -1, recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
40 static int tags = TAGS_DEFAULT, unshallow, update_shallow;
41 static const char *depth;
42 static const char *upload_pack;
43 static struct strbuf default_rla = STRBUF_INIT;
44 static struct transport *gtransport;
45 static struct transport *gsecondary;
46 static const char *submodule_prefix = "";
47 static const char *recurse_submodules_default;
48 static int shown_url = 0;
50 static int option_parse_recurse_submodules(const struct option *opt,
51 const char *arg, int unset)
53 if (unset) {
54 recurse_submodules = RECURSE_SUBMODULES_OFF;
55 } else {
56 if (arg)
57 recurse_submodules = parse_fetch_recurse_submodules_arg(opt->long_name, arg);
58 else
59 recurse_submodules = RECURSE_SUBMODULES_ON;
61 return 0;
64 static int git_fetch_config(const char *k, const char *v, void *cb)
66 if (!strcmp(k, "fetch.prune")) {
67 fetch_prune_config = git_config_bool(k, v);
68 return 0;
70 return 0;
73 static struct option builtin_fetch_options[] = {
74 OPT__VERBOSITY(&verbosity),
75 OPT_BOOL(0, "all", &all,
76 N_("fetch from all remotes")),
77 OPT_BOOL('a', "append", &append,
78 N_("append to .git/FETCH_HEAD instead of overwriting")),
79 OPT_STRING(0, "upload-pack", &upload_pack, N_("path"),
80 N_("path to upload pack on remote end")),
81 OPT__FORCE(&force, N_("force overwrite of local branch")),
82 OPT_BOOL('m', "multiple", &multiple,
83 N_("fetch from multiple remotes")),
84 OPT_SET_INT('t', "tags", &tags,
85 N_("fetch all tags and associated objects"), TAGS_SET),
86 OPT_SET_INT('n', NULL, &tags,
87 N_("do not fetch all tags (--no-tags)"), TAGS_UNSET),
88 OPT_BOOL('p', "prune", &prune,
89 N_("prune remote-tracking branches no longer on remote")),
90 { OPTION_CALLBACK, 0, "recurse-submodules", NULL, N_("on-demand"),
91 N_("control recursive fetching of submodules"),
92 PARSE_OPT_OPTARG, option_parse_recurse_submodules },
93 OPT_BOOL(0, "dry-run", &dry_run,
94 N_("dry run")),
95 OPT_BOOL('k', "keep", &keep, N_("keep downloaded pack")),
96 OPT_BOOL('u', "update-head-ok", &update_head_ok,
97 N_("allow updating of HEAD ref")),
98 OPT_BOOL(0, "progress", &progress, N_("force progress reporting")),
99 OPT_STRING(0, "depth", &depth, N_("depth"),
100 N_("deepen history of shallow clone")),
101 { OPTION_SET_INT, 0, "unshallow", &unshallow, NULL,
102 N_("convert to a complete repository"),
103 PARSE_OPT_NONEG | PARSE_OPT_NOARG, NULL, 1 },
104 { OPTION_STRING, 0, "submodule-prefix", &submodule_prefix, N_("dir"),
105 N_("prepend this to submodule path output"), PARSE_OPT_HIDDEN },
106 { OPTION_STRING, 0, "recurse-submodules-default",
107 &recurse_submodules_default, NULL,
108 N_("default mode for recursion"), PARSE_OPT_HIDDEN },
109 OPT_BOOL(0, "update-shallow", &update_shallow,
110 N_("accept refs that update .git/shallow")),
111 OPT_END()
114 static void unlock_pack(void)
116 if (gtransport)
117 transport_unlock_pack(gtransport);
118 if (gsecondary)
119 transport_unlock_pack(gsecondary);
122 static void unlock_pack_on_signal(int signo)
124 unlock_pack();
125 sigchain_pop(signo);
126 raise(signo);
129 static void add_merge_config(struct ref **head,
130 const struct ref *remote_refs,
131 struct branch *branch,
132 struct ref ***tail)
134 int i;
136 for (i = 0; i < branch->merge_nr; i++) {
137 struct ref *rm, **old_tail = *tail;
138 struct refspec refspec;
140 for (rm = *head; rm; rm = rm->next) {
141 if (branch_merge_matches(branch, i, rm->name)) {
142 rm->fetch_head_status = FETCH_HEAD_MERGE;
143 break;
146 if (rm)
147 continue;
150 * Not fetched to a remote-tracking branch? We need to fetch
151 * it anyway to allow this branch's "branch.$name.merge"
152 * to be honored by 'git pull', but we do not have to
153 * fail if branch.$name.merge is misconfigured to point
154 * at a nonexisting branch. If we were indeed called by
155 * 'git pull', it will notice the misconfiguration because
156 * there is no entry in the resulting FETCH_HEAD marked
157 * for merging.
159 memset(&refspec, 0, sizeof(refspec));
160 refspec.src = branch->merge[i]->src;
161 get_fetch_map(remote_refs, &refspec, tail, 1);
162 for (rm = *old_tail; rm; rm = rm->next)
163 rm->fetch_head_status = FETCH_HEAD_MERGE;
167 static int add_existing(const char *refname, const unsigned char *sha1,
168 int flag, void *cbdata)
170 struct string_list *list = (struct string_list *)cbdata;
171 struct string_list_item *item = string_list_insert(list, refname);
172 item->util = xmalloc(20);
173 hashcpy(item->util, sha1);
174 return 0;
177 static int will_fetch(struct ref **head, const unsigned char *sha1)
179 struct ref *rm = *head;
180 while (rm) {
181 if (!hashcmp(rm->old_sha1, sha1))
182 return 1;
183 rm = rm->next;
185 return 0;
188 static void find_non_local_tags(struct transport *transport,
189 struct ref **head,
190 struct ref ***tail)
192 struct string_list existing_refs = STRING_LIST_INIT_DUP;
193 struct string_list remote_refs = STRING_LIST_INIT_NODUP;
194 const struct ref *ref;
195 struct string_list_item *item = NULL;
197 for_each_ref(add_existing, &existing_refs);
198 for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
199 if (!starts_with(ref->name, "refs/tags/"))
200 continue;
203 * The peeled ref always follows the matching base
204 * ref, so if we see a peeled ref that we don't want
205 * to fetch then we can mark the ref entry in the list
206 * as one to ignore by setting util to NULL.
208 if (ends_with(ref->name, "^{}")) {
209 if (item && !has_sha1_file(ref->old_sha1) &&
210 !will_fetch(head, ref->old_sha1) &&
211 !has_sha1_file(item->util) &&
212 !will_fetch(head, item->util))
213 item->util = NULL;
214 item = NULL;
215 continue;
219 * If item is non-NULL here, then we previously saw a
220 * ref not followed by a peeled reference, so we need
221 * to check if it is a lightweight tag that we want to
222 * fetch.
224 if (item && !has_sha1_file(item->util) &&
225 !will_fetch(head, item->util))
226 item->util = NULL;
228 item = NULL;
230 /* skip duplicates and refs that we already have */
231 if (string_list_has_string(&remote_refs, ref->name) ||
232 string_list_has_string(&existing_refs, ref->name))
233 continue;
235 item = string_list_insert(&remote_refs, ref->name);
236 item->util = (void *)ref->old_sha1;
238 string_list_clear(&existing_refs, 1);
241 * We may have a final lightweight tag that needs to be
242 * checked to see if it needs fetching.
244 if (item && !has_sha1_file(item->util) &&
245 !will_fetch(head, item->util))
246 item->util = NULL;
249 * For all the tags in the remote_refs string list,
250 * add them to the list of refs to be fetched
252 for_each_string_list_item(item, &remote_refs) {
253 /* Unless we have already decided to ignore this item... */
254 if (item->util)
256 struct ref *rm = alloc_ref(item->string);
257 rm->peer_ref = alloc_ref(item->string);
258 hashcpy(rm->old_sha1, item->util);
259 **tail = rm;
260 *tail = &rm->next;
264 string_list_clear(&remote_refs, 0);
267 static struct ref *get_ref_map(struct transport *transport,
268 struct refspec *refspecs, int refspec_count,
269 int tags, int *autotags)
271 int i;
272 struct ref *rm;
273 struct ref *ref_map = NULL;
274 struct ref **tail = &ref_map;
276 /* opportunistically-updated references: */
277 struct ref *orefs = NULL, **oref_tail = &orefs;
279 const struct ref *remote_refs = transport_get_remote_refs(transport);
281 if (refspec_count) {
282 for (i = 0; i < refspec_count; i++) {
283 get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
284 if (refspecs[i].dst && refspecs[i].dst[0])
285 *autotags = 1;
287 /* Merge everything on the command line (but not --tags) */
288 for (rm = ref_map; rm; rm = rm->next)
289 rm->fetch_head_status = FETCH_HEAD_MERGE;
292 * For any refs that we happen to be fetching via
293 * command-line arguments, the destination ref might
294 * have been missing or have been different than the
295 * remote-tracking ref that would be derived from the
296 * configured refspec. In these cases, we want to
297 * take the opportunity to update their configured
298 * remote-tracking reference. However, we do not want
299 * to mention these entries in FETCH_HEAD at all, as
300 * they would simply be duplicates of existing
301 * entries, so we set them FETCH_HEAD_IGNORE below.
303 * We compute these entries now, based only on the
304 * refspecs specified on the command line. But we add
305 * them to the list following the refspecs resulting
306 * from the tags option so that one of the latter,
307 * which has FETCH_HEAD_NOT_FOR_MERGE, is not removed
308 * by ref_remove_duplicates() in favor of one of these
309 * opportunistic entries with FETCH_HEAD_IGNORE.
311 for (i = 0; i < transport->remote->fetch_refspec_nr; i++)
312 get_fetch_map(ref_map, &transport->remote->fetch[i],
313 &oref_tail, 1);
315 if (tags == TAGS_SET)
316 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
317 } else {
318 /* Use the defaults */
319 struct remote *remote = transport->remote;
320 struct branch *branch = branch_get(NULL);
321 int has_merge = branch_has_merge_config(branch);
322 if (remote &&
323 (remote->fetch_refspec_nr ||
324 /* Note: has_merge implies non-NULL branch->remote_name */
325 (has_merge && !strcmp(branch->remote_name, remote->name)))) {
326 for (i = 0; i < remote->fetch_refspec_nr; i++) {
327 get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
328 if (remote->fetch[i].dst &&
329 remote->fetch[i].dst[0])
330 *autotags = 1;
331 if (!i && !has_merge && ref_map &&
332 !remote->fetch[0].pattern)
333 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
336 * if the remote we're fetching from is the same
337 * as given in branch.<name>.remote, we add the
338 * ref given in branch.<name>.merge, too.
340 * Note: has_merge implies non-NULL branch->remote_name
342 if (has_merge &&
343 !strcmp(branch->remote_name, remote->name))
344 add_merge_config(&ref_map, remote_refs, branch, &tail);
345 } else {
346 ref_map = get_remote_ref(remote_refs, "HEAD");
347 if (!ref_map)
348 die(_("Couldn't find remote ref HEAD"));
349 ref_map->fetch_head_status = FETCH_HEAD_MERGE;
350 tail = &ref_map->next;
354 if (tags == TAGS_SET)
355 /* also fetch all tags */
356 get_fetch_map(remote_refs, tag_refspec, &tail, 0);
357 else if (tags == TAGS_DEFAULT && *autotags)
358 find_non_local_tags(transport, &ref_map, &tail);
360 /* Now append any refs to be updated opportunistically: */
361 *tail = orefs;
362 for (rm = orefs; rm; rm = rm->next) {
363 rm->fetch_head_status = FETCH_HEAD_IGNORE;
364 tail = &rm->next;
367 return ref_remove_duplicates(ref_map);
370 #define STORE_REF_ERROR_OTHER 1
371 #define STORE_REF_ERROR_DF_CONFLICT 2
373 static int s_update_ref(const char *action,
374 struct ref *ref,
375 int check_old)
377 char msg[1024];
378 char *rla = getenv("GIT_REFLOG_ACTION");
379 static struct ref_lock *lock;
381 if (dry_run)
382 return 0;
383 if (!rla)
384 rla = default_rla.buf;
385 snprintf(msg, sizeof(msg), "%s: %s", rla, action);
386 lock = lock_any_ref_for_update(ref->name,
387 check_old ? ref->old_sha1 : NULL,
388 0, NULL);
389 if (!lock)
390 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
391 STORE_REF_ERROR_OTHER;
392 if (write_ref_sha1(lock, ref->new_sha1, msg) < 0)
393 return errno == ENOTDIR ? STORE_REF_ERROR_DF_CONFLICT :
394 STORE_REF_ERROR_OTHER;
395 return 0;
398 #define REFCOL_WIDTH 10
400 static int update_local_ref(struct ref *ref,
401 const char *remote,
402 const struct ref *remote_ref,
403 struct strbuf *display)
405 struct commit *current = NULL, *updated;
406 enum object_type type;
407 struct branch *current_branch = branch_get(NULL);
408 const char *pretty_ref = prettify_refname(ref->name);
410 type = sha1_object_info(ref->new_sha1, NULL);
411 if (type < 0)
412 die(_("object %s not found"), sha1_to_hex(ref->new_sha1));
414 if (!hashcmp(ref->old_sha1, ref->new_sha1)) {
415 if (verbosity > 0)
416 strbuf_addf(display, "= %-*s %-*s -> %s",
417 TRANSPORT_SUMMARY(_("[up to date]")),
418 REFCOL_WIDTH, remote, pretty_ref);
419 return 0;
422 if (current_branch &&
423 !strcmp(ref->name, current_branch->name) &&
424 !(update_head_ok || is_bare_repository()) &&
425 !is_null_sha1(ref->old_sha1)) {
427 * If this is the head, and it's not okay to update
428 * the head, and the old value of the head isn't empty...
430 strbuf_addf(display,
431 _("! %-*s %-*s -> %s (can't fetch in current branch)"),
432 TRANSPORT_SUMMARY(_("[rejected]")),
433 REFCOL_WIDTH, remote, pretty_ref);
434 return 1;
437 if (!is_null_sha1(ref->old_sha1) &&
438 starts_with(ref->name, "refs/tags/")) {
439 int r;
440 r = s_update_ref("updating tag", ref, 0);
441 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
442 r ? '!' : '-',
443 TRANSPORT_SUMMARY(_("[tag update]")),
444 REFCOL_WIDTH, remote, pretty_ref,
445 r ? _(" (unable to update local ref)") : "");
446 return r;
449 current = lookup_commit_reference_gently(ref->old_sha1, 1);
450 updated = lookup_commit_reference_gently(ref->new_sha1, 1);
451 if (!current || !updated) {
452 const char *msg;
453 const char *what;
454 int r;
456 * Nicely describe the new ref we're fetching.
457 * Base this on the remote's ref name, as it's
458 * more likely to follow a standard layout.
460 const char *name = remote_ref ? remote_ref->name : "";
461 if (starts_with(name, "refs/tags/")) {
462 msg = "storing tag";
463 what = _("[new tag]");
464 } else if (starts_with(name, "refs/heads/")) {
465 msg = "storing head";
466 what = _("[new branch]");
467 } else {
468 msg = "storing ref";
469 what = _("[new ref]");
472 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
473 (recurse_submodules != RECURSE_SUBMODULES_ON))
474 check_for_new_submodule_commits(ref->new_sha1);
475 r = s_update_ref(msg, ref, 0);
476 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
477 r ? '!' : '*',
478 TRANSPORT_SUMMARY(what),
479 REFCOL_WIDTH, remote, pretty_ref,
480 r ? _(" (unable to update local ref)") : "");
481 return r;
484 if (in_merge_bases(current, updated)) {
485 char quickref[83];
486 int r;
487 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
488 strcat(quickref, "..");
489 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
490 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
491 (recurse_submodules != RECURSE_SUBMODULES_ON))
492 check_for_new_submodule_commits(ref->new_sha1);
493 r = s_update_ref("fast-forward", ref, 1);
494 strbuf_addf(display, "%c %-*s %-*s -> %s%s",
495 r ? '!' : ' ',
496 TRANSPORT_SUMMARY_WIDTH, quickref,
497 REFCOL_WIDTH, remote, pretty_ref,
498 r ? _(" (unable to update local ref)") : "");
499 return r;
500 } else if (force || ref->force) {
501 char quickref[84];
502 int r;
503 strcpy(quickref, find_unique_abbrev(current->object.sha1, DEFAULT_ABBREV));
504 strcat(quickref, "...");
505 strcat(quickref, find_unique_abbrev(ref->new_sha1, DEFAULT_ABBREV));
506 if ((recurse_submodules != RECURSE_SUBMODULES_OFF) &&
507 (recurse_submodules != RECURSE_SUBMODULES_ON))
508 check_for_new_submodule_commits(ref->new_sha1);
509 r = s_update_ref("forced-update", ref, 1);
510 strbuf_addf(display, "%c %-*s %-*s -> %s (%s)",
511 r ? '!' : '+',
512 TRANSPORT_SUMMARY_WIDTH, quickref,
513 REFCOL_WIDTH, remote, pretty_ref,
514 r ? _("unable to update local ref") : _("forced update"));
515 return r;
516 } else {
517 strbuf_addf(display, "! %-*s %-*s -> %s %s",
518 TRANSPORT_SUMMARY(_("[rejected]")),
519 REFCOL_WIDTH, remote, pretty_ref,
520 _("(non-fast-forward)"));
521 return 1;
525 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
527 struct ref **rm = cb_data;
528 struct ref *ref = *rm;
530 while (ref && ref->status == REF_STATUS_REJECT_SHALLOW)
531 ref = ref->next;
532 if (!ref)
533 return -1; /* end of the list */
534 *rm = ref->next;
535 hashcpy(sha1, ref->old_sha1);
536 return 0;
539 static int store_updated_refs(const char *raw_url, const char *remote_name,
540 struct ref *ref_map)
542 FILE *fp;
543 struct commit *commit;
544 int url_len, i, rc = 0;
545 struct strbuf note = STRBUF_INIT;
546 const char *what, *kind;
547 struct ref *rm;
548 char *url, *filename = dry_run ? "/dev/null" : git_path("FETCH_HEAD");
549 int want_status;
551 fp = fopen(filename, "a");
552 if (!fp)
553 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
555 if (raw_url)
556 url = transport_anonymize_url(raw_url);
557 else
558 url = xstrdup("foreign");
560 rm = ref_map;
561 if (check_everything_connected(iterate_ref_map, 0, &rm)) {
562 rc = error(_("%s did not send all necessary objects\n"), url);
563 goto abort;
567 * We do a pass for each fetch_head_status type in their enum order, so
568 * merged entries are written before not-for-merge. That lets readers
569 * use FETCH_HEAD as a refname to refer to the ref to be merged.
571 for (want_status = FETCH_HEAD_MERGE;
572 want_status <= FETCH_HEAD_IGNORE;
573 want_status++) {
574 for (rm = ref_map; rm; rm = rm->next) {
575 struct ref *ref = NULL;
576 const char *merge_status_marker = "";
578 if (rm->status == REF_STATUS_REJECT_SHALLOW) {
579 if (want_status == FETCH_HEAD_MERGE)
580 warning(_("reject %s because shallow roots are not allowed to be updated"),
581 rm->peer_ref ? rm->peer_ref->name : rm->name);
582 continue;
585 commit = lookup_commit_reference_gently(rm->old_sha1, 1);
586 if (!commit)
587 rm->fetch_head_status = FETCH_HEAD_NOT_FOR_MERGE;
589 if (rm->fetch_head_status != want_status)
590 continue;
592 if (rm->peer_ref) {
593 ref = xcalloc(1, sizeof(*ref) + strlen(rm->peer_ref->name) + 1);
594 strcpy(ref->name, rm->peer_ref->name);
595 hashcpy(ref->old_sha1, rm->peer_ref->old_sha1);
596 hashcpy(ref->new_sha1, rm->old_sha1);
597 ref->force = rm->peer_ref->force;
601 if (!strcmp(rm->name, "HEAD")) {
602 kind = "";
603 what = "";
605 else if (starts_with(rm->name, "refs/heads/")) {
606 kind = "branch";
607 what = rm->name + 11;
609 else if (starts_with(rm->name, "refs/tags/")) {
610 kind = "tag";
611 what = rm->name + 10;
613 else if (starts_with(rm->name, "refs/remotes/")) {
614 kind = "remote-tracking branch";
615 what = rm->name + 13;
617 else {
618 kind = "";
619 what = rm->name;
622 url_len = strlen(url);
623 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
625 url_len = i + 1;
626 if (4 < i && !strncmp(".git", url + i - 3, 4))
627 url_len = i - 3;
629 strbuf_reset(&note);
630 if (*what) {
631 if (*kind)
632 strbuf_addf(&note, "%s ", kind);
633 strbuf_addf(&note, "'%s' of ", what);
635 switch (rm->fetch_head_status) {
636 case FETCH_HEAD_NOT_FOR_MERGE:
637 merge_status_marker = "not-for-merge";
638 /* fall-through */
639 case FETCH_HEAD_MERGE:
640 fprintf(fp, "%s\t%s\t%s",
641 sha1_to_hex(rm->old_sha1),
642 merge_status_marker,
643 note.buf);
644 for (i = 0; i < url_len; ++i)
645 if ('\n' == url[i])
646 fputs("\\n", fp);
647 else
648 fputc(url[i], fp);
649 fputc('\n', fp);
650 break;
651 default:
652 /* do not write anything to FETCH_HEAD */
653 break;
656 strbuf_reset(&note);
657 if (ref) {
658 rc |= update_local_ref(ref, what, rm, &note);
659 free(ref);
660 } else
661 strbuf_addf(&note, "* %-*s %-*s -> FETCH_HEAD",
662 TRANSPORT_SUMMARY_WIDTH,
663 *kind ? kind : "branch",
664 REFCOL_WIDTH,
665 *what ? what : "HEAD");
666 if (note.len) {
667 if (verbosity >= 0 && !shown_url) {
668 fprintf(stderr, _("From %.*s\n"),
669 url_len, url);
670 shown_url = 1;
672 if (verbosity >= 0)
673 fprintf(stderr, " %s\n", note.buf);
678 if (rc & STORE_REF_ERROR_DF_CONFLICT)
679 error(_("some local refs could not be updated; try running\n"
680 " 'git remote prune %s' to remove any old, conflicting "
681 "branches"), remote_name);
683 abort:
684 strbuf_release(&note);
685 free(url);
686 fclose(fp);
687 return rc;
691 * We would want to bypass the object transfer altogether if
692 * everything we are going to fetch already exists and is connected
693 * locally.
695 static int quickfetch(struct ref *ref_map)
697 struct ref *rm = ref_map;
700 * If we are deepening a shallow clone we already have these
701 * objects reachable. Running rev-list here will return with
702 * a good (0) exit status and we'll bypass the fetch that we
703 * really need to perform. Claiming failure now will ensure
704 * we perform the network exchange to deepen our history.
706 if (depth)
707 return -1;
708 return check_everything_connected(iterate_ref_map, 1, &rm);
711 static int fetch_refs(struct transport *transport, struct ref *ref_map)
713 int ret = quickfetch(ref_map);
714 if (ret)
715 ret = transport_fetch_refs(transport, ref_map);
716 if (!ret)
717 ret |= store_updated_refs(transport->url,
718 transport->remote->name,
719 ref_map);
720 transport_unlock_pack(transport);
721 return ret;
724 static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
725 const char *raw_url)
727 int url_len, i, result = 0;
728 struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
729 char *url;
730 const char *dangling_msg = dry_run
731 ? _(" (%s will become dangling)")
732 : _(" (%s has become dangling)");
734 if (raw_url)
735 url = transport_anonymize_url(raw_url);
736 else
737 url = xstrdup("foreign");
739 url_len = strlen(url);
740 for (i = url_len - 1; url[i] == '/' && 0 <= i; i--)
743 url_len = i + 1;
744 if (4 < i && !strncmp(".git", url + i - 3, 4))
745 url_len = i - 3;
747 for (ref = stale_refs; ref; ref = ref->next) {
748 if (!dry_run)
749 result |= delete_ref(ref->name, NULL, 0);
750 if (verbosity >= 0 && !shown_url) {
751 fprintf(stderr, _("From %.*s\n"), url_len, url);
752 shown_url = 1;
754 if (verbosity >= 0) {
755 fprintf(stderr, " x %-*s %-*s -> %s\n",
756 TRANSPORT_SUMMARY(_("[deleted]")),
757 REFCOL_WIDTH, _("(none)"), prettify_refname(ref->name));
758 warn_dangling_symref(stderr, dangling_msg, ref->name);
761 free(url);
762 free_refs(stale_refs);
763 return result;
766 static void check_not_current_branch(struct ref *ref_map)
768 struct branch *current_branch = branch_get(NULL);
770 if (is_bare_repository() || !current_branch)
771 return;
773 for (; ref_map; ref_map = ref_map->next)
774 if (ref_map->peer_ref && !strcmp(current_branch->refname,
775 ref_map->peer_ref->name))
776 die(_("Refusing to fetch into current branch %s "
777 "of non-bare repository"), current_branch->refname);
780 static int truncate_fetch_head(void)
782 char *filename = git_path("FETCH_HEAD");
783 FILE *fp = fopen(filename, "w");
785 if (!fp)
786 return error(_("cannot open %s: %s\n"), filename, strerror(errno));
787 fclose(fp);
788 return 0;
791 static void set_option(struct transport *transport, const char *name, const char *value)
793 int r = transport_set_option(transport, name, value);
794 if (r < 0)
795 die(_("Option \"%s\" value \"%s\" is not valid for %s"),
796 name, value, transport->url);
797 if (r > 0)
798 warning(_("Option \"%s\" is ignored for %s\n"),
799 name, transport->url);
802 static struct transport *prepare_transport(struct remote *remote)
804 struct transport *transport;
805 transport = transport_get(remote, NULL);
806 transport_set_verbosity(transport, verbosity, progress);
807 if (upload_pack)
808 set_option(transport, TRANS_OPT_UPLOADPACK, upload_pack);
809 if (keep)
810 set_option(transport, TRANS_OPT_KEEP, "yes");
811 if (depth)
812 set_option(transport, TRANS_OPT_DEPTH, depth);
813 if (update_shallow)
814 set_option(transport, TRANS_OPT_UPDATE_SHALLOW, "yes");
815 return transport;
818 static void backfill_tags(struct transport *transport, struct ref *ref_map)
820 if (transport->cannot_reuse) {
821 gsecondary = prepare_transport(transport->remote);
822 transport = gsecondary;
825 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, NULL);
826 transport_set_option(transport, TRANS_OPT_DEPTH, "0");
827 fetch_refs(transport, ref_map);
829 if (gsecondary) {
830 transport_disconnect(gsecondary);
831 gsecondary = NULL;
835 static int do_fetch(struct transport *transport,
836 struct refspec *refs, int ref_count)
838 struct string_list existing_refs = STRING_LIST_INIT_DUP;
839 struct ref *ref_map;
840 struct ref *rm;
841 int autotags = (transport->remote->fetch_tags == 1);
842 int retcode = 0;
844 for_each_ref(add_existing, &existing_refs);
846 if (tags == TAGS_DEFAULT) {
847 if (transport->remote->fetch_tags == 2)
848 tags = TAGS_SET;
849 if (transport->remote->fetch_tags == -1)
850 tags = TAGS_UNSET;
853 if (!transport->get_refs_list || !transport->fetch)
854 die(_("Don't know how to fetch from %s"), transport->url);
856 /* if not appending, truncate FETCH_HEAD */
857 if (!append && !dry_run) {
858 retcode = truncate_fetch_head();
859 if (retcode)
860 goto cleanup;
863 ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
864 if (!update_head_ok)
865 check_not_current_branch(ref_map);
867 for (rm = ref_map; rm; rm = rm->next) {
868 if (rm->peer_ref) {
869 struct string_list_item *peer_item =
870 string_list_lookup(&existing_refs,
871 rm->peer_ref->name);
872 if (peer_item)
873 hashcpy(rm->peer_ref->old_sha1,
874 peer_item->util);
878 if (tags == TAGS_DEFAULT && autotags)
879 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
880 if (prune) {
882 * We only prune based on refspecs specified
883 * explicitly (via command line or configuration); we
884 * don't care whether --tags was specified.
886 if (ref_count) {
887 prune_refs(refs, ref_count, ref_map, transport->url);
888 } else {
889 prune_refs(transport->remote->fetch,
890 transport->remote->fetch_refspec_nr,
891 ref_map,
892 transport->url);
895 if (fetch_refs(transport, ref_map)) {
896 free_refs(ref_map);
897 retcode = 1;
898 goto cleanup;
900 free_refs(ref_map);
902 /* if neither --no-tags nor --tags was specified, do automated tag
903 * following ... */
904 if (tags == TAGS_DEFAULT && autotags) {
905 struct ref **tail = &ref_map;
906 ref_map = NULL;
907 find_non_local_tags(transport, &ref_map, &tail);
908 if (ref_map)
909 backfill_tags(transport, ref_map);
910 free_refs(ref_map);
913 cleanup:
914 string_list_clear(&existing_refs, 1);
915 return retcode;
918 static int get_one_remote_for_fetch(struct remote *remote, void *priv)
920 struct string_list *list = priv;
921 if (!remote->skip_default_update)
922 string_list_append(list, remote->name);
923 return 0;
926 struct remote_group_data {
927 const char *name;
928 struct string_list *list;
931 static int get_remote_group(const char *key, const char *value, void *priv)
933 struct remote_group_data *g = priv;
935 if (starts_with(key, "remotes.") &&
936 !strcmp(key + 8, g->name)) {
937 /* split list by white space */
938 int space = strcspn(value, " \t\n");
939 while (*value) {
940 if (space > 1) {
941 string_list_append(g->list,
942 xstrndup(value, space));
944 value += space + (value[space] != '\0');
945 space = strcspn(value, " \t\n");
949 return 0;
952 static int add_remote_or_group(const char *name, struct string_list *list)
954 int prev_nr = list->nr;
955 struct remote_group_data g;
956 g.name = name; g.list = list;
958 git_config(get_remote_group, &g);
959 if (list->nr == prev_nr) {
960 struct remote *remote;
961 if (!remote_is_configured(name))
962 return 0;
963 remote = remote_get(name);
964 string_list_append(list, remote->name);
966 return 1;
969 static void add_options_to_argv(struct argv_array *argv)
971 if (dry_run)
972 argv_array_push(argv, "--dry-run");
973 if (prune != -1)
974 argv_array_push(argv, prune ? "--prune" : "--no-prune");
975 if (update_head_ok)
976 argv_array_push(argv, "--update-head-ok");
977 if (force)
978 argv_array_push(argv, "--force");
979 if (keep)
980 argv_array_push(argv, "--keep");
981 if (recurse_submodules == RECURSE_SUBMODULES_ON)
982 argv_array_push(argv, "--recurse-submodules");
983 else if (recurse_submodules == RECURSE_SUBMODULES_ON_DEMAND)
984 argv_array_push(argv, "--recurse-submodules=on-demand");
985 if (tags == TAGS_SET)
986 argv_array_push(argv, "--tags");
987 else if (tags == TAGS_UNSET)
988 argv_array_push(argv, "--no-tags");
989 if (verbosity >= 2)
990 argv_array_push(argv, "-v");
991 if (verbosity >= 1)
992 argv_array_push(argv, "-v");
993 else if (verbosity < 0)
994 argv_array_push(argv, "-q");
998 static int fetch_multiple(struct string_list *list)
1000 int i, result = 0;
1001 struct argv_array argv = ARGV_ARRAY_INIT;
1003 if (!append && !dry_run) {
1004 int errcode = truncate_fetch_head();
1005 if (errcode)
1006 return errcode;
1009 argv_array_pushl(&argv, "fetch", "--append", NULL);
1010 add_options_to_argv(&argv);
1012 for (i = 0; i < list->nr; i++) {
1013 const char *name = list->items[i].string;
1014 argv_array_push(&argv, name);
1015 if (verbosity >= 0)
1016 printf(_("Fetching %s\n"), name);
1017 if (run_command_v_opt(argv.argv, RUN_GIT_CMD)) {
1018 error(_("Could not fetch %s"), name);
1019 result = 1;
1021 argv_array_pop(&argv);
1024 argv_array_clear(&argv);
1025 return result;
1028 static int fetch_one(struct remote *remote, int argc, const char **argv)
1030 static const char **refs = NULL;
1031 struct refspec *refspec;
1032 int ref_nr = 0;
1033 int exit_code;
1035 if (!remote)
1036 die(_("No remote repository specified. Please, specify either a URL or a\n"
1037 "remote name from which new revisions should be fetched."));
1039 gtransport = prepare_transport(remote);
1041 if (prune < 0) {
1042 /* no command line request */
1043 if (0 <= gtransport->remote->prune)
1044 prune = gtransport->remote->prune;
1045 else if (0 <= fetch_prune_config)
1046 prune = fetch_prune_config;
1047 else
1048 prune = PRUNE_BY_DEFAULT;
1051 if (argc > 0) {
1052 int j = 0;
1053 int i;
1054 refs = xcalloc(argc + 1, sizeof(const char *));
1055 for (i = 0; i < argc; i++) {
1056 if (!strcmp(argv[i], "tag")) {
1057 char *ref;
1058 i++;
1059 if (i >= argc)
1060 die(_("You need to specify a tag name."));
1061 ref = xmalloc(strlen(argv[i]) * 2 + 22);
1062 strcpy(ref, "refs/tags/");
1063 strcat(ref, argv[i]);
1064 strcat(ref, ":refs/tags/");
1065 strcat(ref, argv[i]);
1066 refs[j++] = ref;
1067 } else
1068 refs[j++] = argv[i];
1070 refs[j] = NULL;
1071 ref_nr = j;
1074 sigchain_push_common(unlock_pack_on_signal);
1075 atexit(unlock_pack);
1076 refspec = parse_fetch_refspec(ref_nr, refs);
1077 exit_code = do_fetch(gtransport, refspec, ref_nr);
1078 free_refspec(ref_nr, refspec);
1079 transport_disconnect(gtransport);
1080 gtransport = NULL;
1081 return exit_code;
1084 int cmd_fetch(int argc, const char **argv, const char *prefix)
1086 int i;
1087 struct string_list list = STRING_LIST_INIT_NODUP;
1088 struct remote *remote;
1089 int result = 0;
1090 static const char *argv_gc_auto[] = {
1091 "gc", "--auto", NULL,
1094 packet_trace_identity("fetch");
1096 /* Record the command line for the reflog */
1097 strbuf_addstr(&default_rla, "fetch");
1098 for (i = 1; i < argc; i++)
1099 strbuf_addf(&default_rla, " %s", argv[i]);
1101 git_config(git_fetch_config, NULL);
1103 argc = parse_options(argc, argv, prefix,
1104 builtin_fetch_options, builtin_fetch_usage, 0);
1106 if (unshallow) {
1107 if (depth)
1108 die(_("--depth and --unshallow cannot be used together"));
1109 else if (!is_repository_shallow())
1110 die(_("--unshallow on a complete repository does not make sense"));
1111 else {
1112 static char inf_depth[12];
1113 sprintf(inf_depth, "%d", INFINITE_DEPTH);
1114 depth = inf_depth;
1118 /* no need to be strict, transport_set_option() will validate it again */
1119 if (depth && atoi(depth) < 1)
1120 die(_("depth %s is not a positive number"), depth);
1122 if (recurse_submodules != RECURSE_SUBMODULES_OFF) {
1123 if (recurse_submodules_default) {
1124 int arg = parse_fetch_recurse_submodules_arg("--recurse-submodules-default", recurse_submodules_default);
1125 set_config_fetch_recurse_submodules(arg);
1127 gitmodules_config();
1128 git_config(submodule_config, NULL);
1131 if (all) {
1132 if (argc == 1)
1133 die(_("fetch --all does not take a repository argument"));
1134 else if (argc > 1)
1135 die(_("fetch --all does not make sense with refspecs"));
1136 (void) for_each_remote(get_one_remote_for_fetch, &list);
1137 result = fetch_multiple(&list);
1138 } else if (argc == 0) {
1139 /* No arguments -- use default remote */
1140 remote = remote_get(NULL);
1141 result = fetch_one(remote, argc, argv);
1142 } else if (multiple) {
1143 /* All arguments are assumed to be remotes or groups */
1144 for (i = 0; i < argc; i++)
1145 if (!add_remote_or_group(argv[i], &list))
1146 die(_("No such remote or remote group: %s"), argv[i]);
1147 result = fetch_multiple(&list);
1148 } else {
1149 /* Single remote or group */
1150 (void) add_remote_or_group(argv[0], &list);
1151 if (list.nr > 1) {
1152 /* More than one remote */
1153 if (argc > 1)
1154 die(_("Fetching a group and specifying refspecs does not make sense"));
1155 result = fetch_multiple(&list);
1156 } else {
1157 /* Zero or one remotes */
1158 remote = remote_get(argv[0]);
1159 result = fetch_one(remote, argc-1, argv+1);
1163 if (!result && (recurse_submodules != RECURSE_SUBMODULES_OFF)) {
1164 struct argv_array options = ARGV_ARRAY_INIT;
1166 add_options_to_argv(&options);
1167 result = fetch_populated_submodules(&options,
1168 submodule_prefix,
1169 recurse_submodules,
1170 verbosity < 0);
1171 argv_array_clear(&options);
1174 /* All names were strdup()ed or strndup()ed */
1175 list.strdup_strings = 1;
1176 string_list_clear(&list, 0);
1178 run_command_v_opt(argv_gc_auto, RUN_GIT_CMD);
1180 return result;