The fourteenth batch
[alt-git.git] / builtin / clone.c
blob45d78614a414a1dee6f1accf4c708ca8cd669c6d
1 /*
2 * Builtin "git clone"
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>,
5 * 2008 Daniel Barkalow <barkalow@iabervon.org>
6 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
8 * Clone a repository into a different directory that does not yet exist.
9 */
11 #include "builtin.h"
12 #include "abspath.h"
13 #include "advice.h"
14 #include "config.h"
15 #include "copy.h"
16 #include "environment.h"
17 #include "gettext.h"
18 #include "hex.h"
19 #include "lockfile.h"
20 #include "parse-options.h"
21 #include "refs.h"
22 #include "refspec.h"
23 #include "object-file.h"
24 #include "object-store-ll.h"
25 #include "tree.h"
26 #include "tree-walk.h"
27 #include "unpack-trees.h"
28 #include "transport.h"
29 #include "strbuf.h"
30 #include "dir.h"
31 #include "dir-iterator.h"
32 #include "iterator.h"
33 #include "sigchain.h"
34 #include "branch.h"
35 #include "remote.h"
36 #include "run-command.h"
37 #include "setup.h"
38 #include "connected.h"
39 #include "packfile.h"
40 #include "path.h"
41 #include "pkt-line.h"
42 #include "list-objects-filter-options.h"
43 #include "hook.h"
44 #include "bundle.h"
45 #include "bundle-uri.h"
48 * Overall FIXMEs:
49 * - respect DB_ENVIRONMENT for .git/objects.
51 * Implementation notes:
52 * - dropping use-separate-remote and no-separate-remote compatibility
55 static const char * const builtin_clone_usage[] = {
56 N_("git clone [<options>] [--] <repo> [<dir>]"),
57 NULL
60 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
61 static int option_local = -1, option_no_hardlinks, option_shared;
62 static int option_no_tags;
63 static int option_shallow_submodules;
64 static int option_reject_shallow = -1; /* unspecified */
65 static int config_reject_shallow = -1; /* unspecified */
66 static int deepen;
67 static char *option_template, *option_depth, *option_since;
68 static char *option_origin = NULL;
69 static char *remote_name = NULL;
70 static char *option_branch = NULL;
71 static struct string_list option_not = STRING_LIST_INIT_NODUP;
72 static const char *real_git_dir;
73 static const char *ref_format;
74 static const char *option_upload_pack = "git-upload-pack";
75 static int option_verbosity;
76 static int option_progress = -1;
77 static int option_sparse_checkout;
78 static enum transport_family family;
79 static struct string_list option_config = STRING_LIST_INIT_NODUP;
80 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
81 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
82 static int option_dissociate;
83 static int max_jobs = -1;
84 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
85 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
86 static int option_filter_submodules = -1; /* unspecified */
87 static int config_filter_submodules = -1; /* unspecified */
88 static struct string_list server_options = STRING_LIST_INIT_NODUP;
89 static int option_remote_submodules;
90 static const char *bundle_uri;
92 static int recurse_submodules_cb(const struct option *opt,
93 const char *arg, int unset)
95 if (unset)
96 string_list_clear((struct string_list *)opt->value, 0);
97 else if (arg)
98 string_list_append((struct string_list *)opt->value, arg);
99 else
100 string_list_append((struct string_list *)opt->value,
101 (const char *)opt->defval);
103 return 0;
106 static struct option builtin_clone_options[] = {
107 OPT__VERBOSITY(&option_verbosity),
108 OPT_BOOL(0, "progress", &option_progress,
109 N_("force progress reporting")),
110 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
111 N_("don't clone shallow repository")),
112 OPT_BOOL('n', "no-checkout", &option_no_checkout,
113 N_("don't create a checkout")),
114 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
115 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
116 N_("create a bare repository")),
117 OPT_BOOL(0, "mirror", &option_mirror,
118 N_("create a mirror repository (implies --bare)")),
119 OPT_BOOL('l', "local", &option_local,
120 N_("to clone from a local repository")),
121 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
122 N_("don't use local hardlinks, always copy")),
123 OPT_BOOL('s', "shared", &option_shared,
124 N_("setup as shared repository")),
125 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
126 N_("pathspec"), N_("initialize submodules in the clone"),
127 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
128 OPT_ALIAS(0, "recursive", "recurse-submodules"),
129 OPT_INTEGER('j', "jobs", &max_jobs,
130 N_("number of submodules cloned in parallel")),
131 OPT_STRING(0, "template", &option_template, N_("template-directory"),
132 N_("directory from which templates will be used")),
133 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
134 N_("reference repository")),
135 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
136 N_("repo"), N_("reference repository")),
137 OPT_BOOL(0, "dissociate", &option_dissociate,
138 N_("use --reference only while cloning")),
139 OPT_STRING('o', "origin", &option_origin, N_("name"),
140 N_("use <name> instead of 'origin' to track upstream")),
141 OPT_STRING('b', "branch", &option_branch, N_("branch"),
142 N_("checkout <branch> instead of the remote's HEAD")),
143 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
144 N_("path to git-upload-pack on the remote")),
145 OPT_STRING(0, "depth", &option_depth, N_("depth"),
146 N_("create a shallow clone of that depth")),
147 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
148 N_("create a shallow clone since a specific time")),
149 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
150 N_("deepen history of shallow clone, excluding rev")),
151 OPT_BOOL(0, "single-branch", &option_single_branch,
152 N_("clone only one branch, HEAD or --branch")),
153 OPT_BOOL(0, "no-tags", &option_no_tags,
154 N_("don't clone any tags, and make later fetches not to follow them")),
155 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
156 N_("any cloned submodules will be shallow")),
157 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
158 N_("separate git dir from working tree")),
159 OPT_STRING(0, "ref-format", &ref_format, N_("format"),
160 N_("specify the reference format to use")),
161 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
162 N_("set config inside the new repository")),
163 OPT_STRING_LIST(0, "server-option", &server_options,
164 N_("server-specific"), N_("option to transmit")),
165 OPT_IPVERSION(&family),
166 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
167 OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
168 N_("apply partial clone filters to submodules")),
169 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
170 N_("any cloned submodules will use their remote-tracking branch")),
171 OPT_BOOL(0, "sparse", &option_sparse_checkout,
172 N_("initialize sparse-checkout file to include only files at root")),
173 OPT_STRING(0, "bundle-uri", &bundle_uri,
174 N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
175 OPT_END()
178 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
180 static const char *suffix[] = { "/.git", "", ".git/.git", ".git" };
181 static const char *bundle_suffix[] = { ".bundle", "" };
182 size_t baselen = path->len;
183 struct stat st;
184 int i;
186 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
187 strbuf_setlen(path, baselen);
188 strbuf_addstr(path, suffix[i]);
189 if (stat(path->buf, &st))
190 continue;
191 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
192 *is_bundle = 0;
193 return path->buf;
194 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
195 /* Is it a "gitfile"? */
196 char signature[8];
197 const char *dst;
198 int len, fd = open(path->buf, O_RDONLY);
199 if (fd < 0)
200 continue;
201 len = read_in_full(fd, signature, 8);
202 close(fd);
203 if (len != 8 || strncmp(signature, "gitdir: ", 8))
204 continue;
205 dst = read_gitfile(path->buf);
206 if (dst) {
207 *is_bundle = 0;
208 return dst;
213 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
214 strbuf_setlen(path, baselen);
215 strbuf_addstr(path, bundle_suffix[i]);
216 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
217 *is_bundle = 1;
218 return path->buf;
222 return NULL;
225 static char *get_repo_path(const char *repo, int *is_bundle)
227 struct strbuf path = STRBUF_INIT;
228 const char *raw;
229 char *canon;
231 strbuf_addstr(&path, repo);
232 raw = get_repo_path_1(&path, is_bundle);
233 canon = raw ? absolute_pathdup(raw) : NULL;
234 strbuf_release(&path);
235 return canon;
238 static int add_one_reference(struct string_list_item *item, void *cb_data)
240 struct strbuf err = STRBUF_INIT;
241 int *required = cb_data;
242 char *ref_git = compute_alternate_path(item->string, &err);
244 if (!ref_git) {
245 if (*required)
246 die("%s", err.buf);
247 else
248 fprintf(stderr,
249 _("info: Could not add alternate for '%s': %s\n"),
250 item->string, err.buf);
251 } else {
252 struct strbuf sb = STRBUF_INIT;
253 strbuf_addf(&sb, "%s/objects", ref_git);
254 add_to_alternates_file(sb.buf);
255 strbuf_release(&sb);
258 strbuf_release(&err);
259 free(ref_git);
260 return 0;
263 static void setup_reference(void)
265 int required = 1;
266 for_each_string_list(&option_required_reference,
267 add_one_reference, &required);
268 required = 0;
269 for_each_string_list(&option_optional_reference,
270 add_one_reference, &required);
273 static void copy_alternates(struct strbuf *src, const char *src_repo)
276 * Read from the source objects/info/alternates file
277 * and copy the entries to corresponding file in the
278 * destination repository with add_to_alternates_file().
279 * Both src and dst have "$path/objects/info/alternates".
281 * Instead of copying bit-for-bit from the original,
282 * we need to append to existing one so that the already
283 * created entry via "clone -s" is not lost, and also
284 * to turn entries with paths relative to the original
285 * absolute, so that they can be used in the new repository.
287 FILE *in = xfopen(src->buf, "r");
288 struct strbuf line = STRBUF_INIT;
290 while (strbuf_getline(&line, in) != EOF) {
291 char *abs_path;
292 if (!line.len || line.buf[0] == '#')
293 continue;
294 if (is_absolute_path(line.buf)) {
295 add_to_alternates_file(line.buf);
296 continue;
298 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
299 if (!normalize_path_copy(abs_path, abs_path))
300 add_to_alternates_file(abs_path);
301 else
302 warning("skipping invalid relative alternate: %s/%s",
303 src_repo, line.buf);
304 free(abs_path);
306 strbuf_release(&line);
307 fclose(in);
310 static void mkdir_if_missing(const char *pathname, mode_t mode)
312 struct stat st;
314 if (!mkdir(pathname, mode))
315 return;
317 if (errno != EEXIST)
318 die_errno(_("failed to create directory '%s'"), pathname);
319 else if (stat(pathname, &st))
320 die_errno(_("failed to stat '%s'"), pathname);
321 else if (!S_ISDIR(st.st_mode))
322 die(_("%s exists and is not a directory"), pathname);
325 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
326 const char *src_repo)
328 int src_len, dest_len;
329 struct dir_iterator *iter;
330 int iter_status;
333 * Refuse copying directories by default which aren't owned by us. The
334 * code that performs either the copying or hardlinking is not prepared
335 * to handle various edge cases where an adversary may for example
336 * racily swap out files for symlinks. This can cause us to
337 * inadvertently use the wrong source file.
339 * Furthermore, even if we were prepared to handle such races safely,
340 * creating hardlinks across user boundaries is an inherently unsafe
341 * operation as the hardlinked files can be rewritten at will by the
342 * potentially-untrusted user. We thus refuse to do so by default.
344 die_upon_dubious_ownership(NULL, NULL, src_repo);
346 mkdir_if_missing(dest->buf, 0777);
348 iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
350 if (!iter) {
351 if (errno == ENOTDIR) {
352 int saved_errno = errno;
353 struct stat st;
355 if (!lstat(src->buf, &st) && S_ISLNK(st.st_mode))
356 die(_("'%s' is a symlink, refusing to clone with --local"),
357 src->buf);
358 errno = saved_errno;
360 die_errno(_("failed to start iterator over '%s'"), src->buf);
363 strbuf_addch(src, '/');
364 src_len = src->len;
365 strbuf_addch(dest, '/');
366 dest_len = dest->len;
368 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
369 strbuf_setlen(src, src_len);
370 strbuf_addstr(src, iter->relative_path);
371 strbuf_setlen(dest, dest_len);
372 strbuf_addstr(dest, iter->relative_path);
374 if (S_ISLNK(iter->st.st_mode))
375 die(_("symlink '%s' exists, refusing to clone with --local"),
376 iter->relative_path);
378 if (S_ISDIR(iter->st.st_mode)) {
379 mkdir_if_missing(dest->buf, 0777);
380 continue;
383 /* Files that cannot be copied bit-for-bit... */
384 if (!fspathcmp(iter->relative_path, "info/alternates")) {
385 copy_alternates(src, src_repo);
386 continue;
389 if (unlink(dest->buf) && errno != ENOENT)
390 die_errno(_("failed to unlink '%s'"), dest->buf);
391 if (!option_no_hardlinks) {
392 if (!link(src->buf, dest->buf)) {
393 struct stat st;
396 * Sanity-check whether the created hardlink
397 * actually links to the expected file now. This
398 * catches time-of-check-time-of-use bugs in
399 * case the source file was meanwhile swapped.
401 if (lstat(dest->buf, &st))
402 die(_("hardlink cannot be checked at '%s'"), dest->buf);
403 if (st.st_mode != iter->st.st_mode ||
404 st.st_ino != iter->st.st_ino ||
405 st.st_dev != iter->st.st_dev ||
406 st.st_size != iter->st.st_size ||
407 st.st_uid != iter->st.st_uid ||
408 st.st_gid != iter->st.st_gid)
409 die(_("hardlink different from source at '%s'"), dest->buf);
411 continue;
413 if (option_local > 0)
414 die_errno(_("failed to create link '%s'"), dest->buf);
415 option_no_hardlinks = 1;
417 if (copy_file_with_time(dest->buf, src->buf, 0666))
418 die_errno(_("failed to copy file to '%s'"), dest->buf);
421 if (iter_status != ITER_DONE) {
422 strbuf_setlen(src, src_len);
423 die(_("failed to iterate over '%s'"), src->buf);
427 static void clone_local(const char *src_repo, const char *dest_repo)
429 if (option_shared) {
430 struct strbuf alt = STRBUF_INIT;
431 get_common_dir(&alt, src_repo);
432 strbuf_addstr(&alt, "/objects");
433 add_to_alternates_file(alt.buf);
434 strbuf_release(&alt);
435 } else {
436 struct strbuf src = STRBUF_INIT;
437 struct strbuf dest = STRBUF_INIT;
438 get_common_dir(&src, src_repo);
439 get_common_dir(&dest, dest_repo);
440 strbuf_addstr(&src, "/objects");
441 strbuf_addstr(&dest, "/objects");
442 copy_or_link_directory(&src, &dest, src_repo);
443 strbuf_release(&src);
444 strbuf_release(&dest);
447 if (0 <= option_verbosity)
448 fprintf(stderr, _("done.\n"));
451 static const char *junk_work_tree;
452 static int junk_work_tree_flags;
453 static const char *junk_git_dir;
454 static int junk_git_dir_flags;
455 static enum {
456 JUNK_LEAVE_NONE,
457 JUNK_LEAVE_REPO,
458 JUNK_LEAVE_ALL
459 } junk_mode = JUNK_LEAVE_NONE;
461 static const char junk_leave_repo_msg[] =
462 N_("Clone succeeded, but checkout failed.\n"
463 "You can inspect what was checked out with 'git status'\n"
464 "and retry with 'git restore --source=HEAD :/'\n");
466 static void remove_junk(void)
468 struct strbuf sb = STRBUF_INIT;
470 switch (junk_mode) {
471 case JUNK_LEAVE_REPO:
472 warning("%s", _(junk_leave_repo_msg));
473 /* fall-through */
474 case JUNK_LEAVE_ALL:
475 return;
476 default:
477 /* proceed to removal */
478 break;
481 if (junk_git_dir) {
482 strbuf_addstr(&sb, junk_git_dir);
483 remove_dir_recursively(&sb, junk_git_dir_flags);
484 strbuf_reset(&sb);
486 if (junk_work_tree) {
487 strbuf_addstr(&sb, junk_work_tree);
488 remove_dir_recursively(&sb, junk_work_tree_flags);
490 strbuf_release(&sb);
493 static void remove_junk_on_signal(int signo)
495 remove_junk();
496 sigchain_pop(signo);
497 raise(signo);
500 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
502 struct ref *ref;
503 struct strbuf head = STRBUF_INIT;
504 strbuf_addstr(&head, "refs/heads/");
505 strbuf_addstr(&head, branch);
506 ref = find_ref_by_name(refs, head.buf);
507 strbuf_release(&head);
509 if (ref)
510 return ref;
512 strbuf_addstr(&head, "refs/tags/");
513 strbuf_addstr(&head, branch);
514 ref = find_ref_by_name(refs, head.buf);
515 strbuf_release(&head);
517 return ref;
520 static struct ref *wanted_peer_refs(const struct ref *refs,
521 struct refspec *refspec)
523 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
524 struct ref *local_refs = head;
525 struct ref **tail = head ? &head->next : &local_refs;
526 struct refspec_item tag_refspec;
528 refspec_item_init(&tag_refspec, TAG_REFSPEC, 0);
530 if (option_single_branch) {
531 struct ref *remote_head = NULL;
533 if (!option_branch)
534 remote_head = guess_remote_head(head, refs, 0);
535 else {
536 local_refs = NULL;
537 tail = &local_refs;
538 remote_head = copy_ref(find_remote_branch(refs, option_branch));
541 if (!remote_head && option_branch)
542 warning(_("Could not find remote branch %s to clone."),
543 option_branch);
544 else {
545 int i;
546 for (i = 0; i < refspec->nr; i++)
547 get_fetch_map(remote_head, &refspec->items[i],
548 &tail, 0);
550 /* if --branch=tag, pull the requested tag explicitly */
551 get_fetch_map(remote_head, &tag_refspec, &tail, 0);
553 free_refs(remote_head);
554 } else {
555 int i;
556 for (i = 0; i < refspec->nr; i++)
557 get_fetch_map(refs, &refspec->items[i], &tail, 0);
560 if (!option_mirror && !option_single_branch && !option_no_tags)
561 get_fetch_map(refs, &tag_refspec, &tail, 0);
563 refspec_item_clear(&tag_refspec);
564 return local_refs;
567 static void write_remote_refs(const struct ref *local_refs)
569 const struct ref *r;
571 struct ref_transaction *t;
572 struct strbuf err = STRBUF_INIT;
574 t = ref_store_transaction_begin(get_main_ref_store(the_repository),
575 &err);
576 if (!t)
577 die("%s", err.buf);
579 for (r = local_refs; r; r = r->next) {
580 if (!r->peer_ref)
581 continue;
582 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
583 0, NULL, &err))
584 die("%s", err.buf);
587 if (initial_ref_transaction_commit(t, &err))
588 die("%s", err.buf);
590 strbuf_release(&err);
591 ref_transaction_free(t);
594 static void write_followtags(const struct ref *refs, const char *msg)
596 const struct ref *ref;
597 for (ref = refs; ref; ref = ref->next) {
598 if (!starts_with(ref->name, "refs/tags/"))
599 continue;
600 if (ends_with(ref->name, "^{}"))
601 continue;
602 if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid,
603 OBJECT_INFO_QUICK |
604 OBJECT_INFO_SKIP_FETCH_OBJECT))
605 continue;
606 refs_update_ref(get_main_ref_store(the_repository), msg,
607 ref->name, &ref->old_oid, NULL, 0,
608 UPDATE_REFS_DIE_ON_ERR);
612 static const struct object_id *iterate_ref_map(void *cb_data)
614 struct ref **rm = cb_data;
615 struct ref *ref = *rm;
618 * Skip anything missing a peer_ref, which we are not
619 * actually going to write a ref for.
621 while (ref && !ref->peer_ref)
622 ref = ref->next;
623 if (!ref)
624 return NULL;
626 *rm = ref->next;
627 return &ref->old_oid;
630 static void update_remote_refs(const struct ref *refs,
631 const struct ref *mapped_refs,
632 const struct ref *remote_head_points_at,
633 const char *branch_top,
634 const char *msg,
635 struct transport *transport,
636 int check_connectivity)
638 const struct ref *rm = mapped_refs;
640 if (check_connectivity) {
641 struct check_connected_options opt = CHECK_CONNECTED_INIT;
643 opt.transport = transport;
644 opt.progress = transport->progress;
646 if (check_connected(iterate_ref_map, &rm, &opt))
647 die(_("remote did not send all necessary objects"));
650 if (refs) {
651 write_remote_refs(mapped_refs);
652 if (option_single_branch && !option_no_tags)
653 write_followtags(refs, msg);
656 if (remote_head_points_at && !option_bare) {
657 struct strbuf head_ref = STRBUF_INIT;
658 strbuf_addstr(&head_ref, branch_top);
659 strbuf_addstr(&head_ref, "HEAD");
660 if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
661 remote_head_points_at->peer_ref->name,
662 msg) < 0)
663 die(_("unable to update %s"), head_ref.buf);
664 strbuf_release(&head_ref);
668 static void update_head(const struct ref *our, const struct ref *remote,
669 const char *unborn, const char *msg)
671 const char *head;
672 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
673 /* Local default branch link */
674 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
675 die(_("unable to update HEAD"));
676 if (!option_bare) {
677 refs_update_ref(get_main_ref_store(the_repository),
678 msg, "HEAD", &our->old_oid, NULL, 0,
679 UPDATE_REFS_DIE_ON_ERR);
680 install_branch_config(0, head, remote_name, our->name);
682 } else if (our) {
683 struct commit *c = lookup_commit_reference(the_repository,
684 &our->old_oid);
685 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
686 refs_update_ref(get_main_ref_store(the_repository), msg,
687 "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
688 UPDATE_REFS_DIE_ON_ERR);
689 } else if (remote) {
691 * We know remote HEAD points to a non-branch, or
692 * HEAD points to a branch but we don't know which one.
693 * Detach HEAD in all these cases.
695 refs_update_ref(get_main_ref_store(the_repository), msg,
696 "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
697 UPDATE_REFS_DIE_ON_ERR);
698 } else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
700 * Unborn head from remote; same as "our" case above except
701 * that we have no ref to update.
703 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
704 die(_("unable to update HEAD"));
705 if (!option_bare)
706 install_branch_config(0, head, remote_name, unborn);
710 static int git_sparse_checkout_init(const char *repo)
712 struct child_process cmd = CHILD_PROCESS_INIT;
713 int result = 0;
714 strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
717 * We must apply the setting in the current process
718 * for the later checkout to use the sparse-checkout file.
720 core_apply_sparse_checkout = 1;
722 cmd.git_cmd = 1;
723 if (run_command(&cmd)) {
724 error(_("failed to initialize sparse-checkout"));
725 result = 1;
728 return result;
731 static int checkout(int submodule_progress, int filter_submodules)
733 struct object_id oid;
734 char *head;
735 struct lock_file lock_file = LOCK_INIT;
736 struct unpack_trees_options opts;
737 struct tree *tree;
738 struct tree_desc t;
739 int err = 0;
741 if (option_no_checkout)
742 return 0;
744 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
745 RESOLVE_REF_READING, &oid, NULL);
746 if (!head) {
747 warning(_("remote HEAD refers to nonexistent ref, "
748 "unable to checkout"));
749 return 0;
751 if (!strcmp(head, "HEAD")) {
752 if (advice_enabled(ADVICE_DETACHED_HEAD))
753 detach_advice(oid_to_hex(&oid));
754 FREE_AND_NULL(head);
755 } else {
756 if (!starts_with(head, "refs/heads/"))
757 die(_("HEAD not found below refs/heads!"));
760 /* We need to be in the new work tree for the checkout */
761 setup_work_tree();
763 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
765 memset(&opts, 0, sizeof opts);
766 opts.update = 1;
767 opts.merge = 1;
768 opts.clone = 1;
769 opts.preserve_ignored = 0;
770 opts.fn = oneway_merge;
771 opts.verbose_update = (option_verbosity >= 0);
772 opts.src_index = the_repository->index;
773 opts.dst_index = the_repository->index;
774 init_checkout_metadata(&opts.meta, head, &oid, NULL);
776 tree = parse_tree_indirect(&oid);
777 if (!tree)
778 die(_("unable to parse commit %s"), oid_to_hex(&oid));
779 if (parse_tree(tree) < 0)
780 exit(128);
781 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
782 if (unpack_trees(1, &t, &opts) < 0)
783 die(_("unable to checkout working tree"));
785 free(head);
787 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
788 die(_("unable to write new index file"));
790 err |= run_hooks_l("post-checkout", oid_to_hex(null_oid()),
791 oid_to_hex(&oid), "1", NULL);
793 if (!err && (option_recurse_submodules.nr > 0)) {
794 struct child_process cmd = CHILD_PROCESS_INIT;
795 strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
796 "--recursive", NULL);
798 if (option_shallow_submodules == 1)
799 strvec_push(&cmd.args, "--depth=1");
801 if (max_jobs != -1)
802 strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
804 if (submodule_progress)
805 strvec_push(&cmd.args, "--progress");
807 if (option_verbosity < 0)
808 strvec_push(&cmd.args, "--quiet");
810 if (option_remote_submodules) {
811 strvec_push(&cmd.args, "--remote");
812 strvec_push(&cmd.args, "--no-fetch");
815 if (filter_submodules && filter_options.choice)
816 strvec_pushf(&cmd.args, "--filter=%s",
817 expand_list_objects_filter_spec(&filter_options));
819 if (option_single_branch >= 0)
820 strvec_push(&cmd.args, option_single_branch ?
821 "--single-branch" :
822 "--no-single-branch");
824 cmd.git_cmd = 1;
825 err = run_command(&cmd);
828 return err;
831 static int git_clone_config(const char *k, const char *v,
832 const struct config_context *ctx, void *cb)
834 if (!strcmp(k, "clone.defaultremotename")) {
835 if (!v)
836 return config_error_nonbool(k);
837 free(remote_name);
838 remote_name = xstrdup(v);
840 if (!strcmp(k, "clone.rejectshallow"))
841 config_reject_shallow = git_config_bool(k, v);
842 if (!strcmp(k, "clone.filtersubmodules"))
843 config_filter_submodules = git_config_bool(k, v);
845 return git_default_config(k, v, ctx, cb);
848 static int write_one_config(const char *key, const char *value,
849 const struct config_context *ctx,
850 void *data)
853 * give git_clone_config a chance to write config values back to the
854 * environment, since git_config_set_multivar_gently only deals with
855 * config-file writes
857 int apply_failed = git_clone_config(key, value, ctx, data);
858 if (apply_failed)
859 return apply_failed;
861 return git_config_set_multivar_gently(key,
862 value ? value : "true",
863 CONFIG_REGEX_NONE, 0);
866 static void write_config(struct string_list *config)
868 int i;
870 for (i = 0; i < config->nr; i++) {
871 if (git_config_parse_parameter(config->items[i].string,
872 write_one_config, NULL) < 0)
873 die(_("unable to write parameters to config file"));
877 static void write_refspec_config(const char *src_ref_prefix,
878 const struct ref *our_head_points_at,
879 const struct ref *remote_head_points_at,
880 struct strbuf *branch_top)
882 struct strbuf key = STRBUF_INIT;
883 struct strbuf value = STRBUF_INIT;
885 if (option_mirror || !option_bare) {
886 if (option_single_branch && !option_mirror) {
887 if (option_branch) {
888 if (starts_with(our_head_points_at->name, "refs/tags/"))
889 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
890 our_head_points_at->name);
891 else
892 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
893 branch_top->buf, option_branch);
894 } else if (remote_head_points_at) {
895 const char *head = remote_head_points_at->name;
896 if (!skip_prefix(head, "refs/heads/", &head))
897 BUG("remote HEAD points at non-head?");
899 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
900 branch_top->buf, head);
903 * otherwise, the next "git fetch" will
904 * simply fetch from HEAD without updating
905 * any remote-tracking branch, which is what
906 * we want.
908 } else {
909 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
911 /* Configure the remote */
912 if (value.len) {
913 strbuf_addf(&key, "remote.%s.fetch", remote_name);
914 git_config_set_multivar(key.buf, value.buf, "^$", 0);
915 strbuf_reset(&key);
917 if (option_mirror) {
918 strbuf_addf(&key, "remote.%s.mirror", remote_name);
919 git_config_set(key.buf, "true");
920 strbuf_reset(&key);
925 strbuf_release(&key);
926 strbuf_release(&value);
929 static void dissociate_from_references(void)
931 char *alternates = git_pathdup("objects/info/alternates");
933 if (!access(alternates, F_OK)) {
934 struct child_process cmd = CHILD_PROCESS_INIT;
936 cmd.git_cmd = 1;
937 cmd.no_stdin = 1;
938 strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
939 if (run_command(&cmd))
940 die(_("cannot repack to clean up"));
941 if (unlink(alternates) && errno != ENOENT)
942 die_errno(_("cannot unlink temporary alternates file"));
944 free(alternates);
947 static int path_exists(const char *path)
949 struct stat sb;
950 return !stat(path, &sb);
953 int cmd_clone(int argc, const char **argv, const char *prefix)
955 int is_bundle = 0, is_local;
956 int reject_shallow = 0;
957 const char *repo_name, *repo, *work_tree, *git_dir;
958 char *repo_to_free = NULL;
959 char *path = NULL, *dir, *display_repo = NULL;
960 int dest_exists, real_dest_exists = 0;
961 const struct ref *refs, *remote_head;
962 struct ref *remote_head_points_at = NULL;
963 const struct ref *our_head_points_at;
964 char *unborn_head = NULL;
965 struct ref *mapped_refs = NULL;
966 const struct ref *ref;
967 struct strbuf key = STRBUF_INIT;
968 struct strbuf buf = STRBUF_INIT;
969 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
970 struct transport *transport = NULL;
971 const char *src_ref_prefix = "refs/heads/";
972 struct remote *remote;
973 int err = 0, complete_refs_before_fetch = 1;
974 int submodule_progress;
975 int filter_submodules = 0;
976 int hash_algo;
977 enum ref_storage_format ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
978 const int do_not_override_repo_unix_permissions = -1;
980 struct transport_ls_refs_options transport_ls_refs_options =
981 TRANSPORT_LS_REFS_OPTIONS_INIT;
983 packet_trace_identity("clone");
985 git_config(git_clone_config, NULL);
987 argc = parse_options(argc, argv, prefix, builtin_clone_options,
988 builtin_clone_usage, 0);
990 if (argc > 2)
991 usage_msg_opt(_("Too many arguments."),
992 builtin_clone_usage, builtin_clone_options);
994 if (argc == 0)
995 usage_msg_opt(_("You must specify a repository to clone."),
996 builtin_clone_usage, builtin_clone_options);
998 if (option_depth || option_since || option_not.nr)
999 deepen = 1;
1000 if (option_single_branch == -1)
1001 option_single_branch = deepen ? 1 : 0;
1003 if (ref_format) {
1004 ref_storage_format = ref_storage_format_by_name(ref_format);
1005 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1006 die(_("unknown ref storage format '%s'"), ref_format);
1009 if (option_mirror)
1010 option_bare = 1;
1012 if (option_bare) {
1013 if (real_git_dir)
1014 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1015 option_no_checkout = 1;
1018 if (bundle_uri && deepen)
1019 die(_("options '%s' and '%s' cannot be used together"),
1020 "--bundle-uri",
1021 "--depth/--shallow-since/--shallow-exclude");
1023 repo_name = argv[0];
1025 path = get_repo_path(repo_name, &is_bundle);
1026 if (path) {
1027 FREE_AND_NULL(path);
1028 repo = repo_to_free = absolute_pathdup(repo_name);
1029 } else if (strchr(repo_name, ':')) {
1030 repo = repo_name;
1031 display_repo = transport_anonymize_url(repo);
1032 } else
1033 die(_("repository '%s' does not exist"), repo_name);
1035 /* no need to be strict, transport_set_option() will validate it again */
1036 if (option_depth && atoi(option_depth) < 1)
1037 die(_("depth %s is not a positive number"), option_depth);
1039 if (argc == 2)
1040 dir = xstrdup(argv[1]);
1041 else
1042 dir = git_url_basename(repo_name, is_bundle, option_bare);
1043 strip_dir_trailing_slashes(dir);
1045 dest_exists = path_exists(dir);
1046 if (dest_exists && !is_empty_dir(dir))
1047 die(_("destination path '%s' already exists and is not "
1048 "an empty directory."), dir);
1050 if (real_git_dir) {
1051 real_dest_exists = path_exists(real_git_dir);
1052 if (real_dest_exists && !is_empty_dir(real_git_dir))
1053 die(_("repository path '%s' already exists and is not "
1054 "an empty directory."), real_git_dir);
1058 strbuf_addf(&reflog_msg, "clone: from %s",
1059 display_repo ? display_repo : repo);
1060 free(display_repo);
1062 if (option_bare)
1063 work_tree = NULL;
1064 else {
1065 work_tree = getenv("GIT_WORK_TREE");
1066 if (work_tree && path_exists(work_tree))
1067 die(_("working tree '%s' already exists."), work_tree);
1070 if (option_bare || work_tree)
1071 git_dir = xstrdup(dir);
1072 else {
1073 work_tree = dir;
1074 git_dir = mkpathdup("%s/.git", dir);
1077 atexit(remove_junk);
1078 sigchain_push_common(remove_junk_on_signal);
1080 if (!option_bare) {
1081 if (safe_create_leading_directories_const(work_tree) < 0)
1082 die_errno(_("could not create leading directories of '%s'"),
1083 work_tree);
1084 if (dest_exists)
1085 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1086 else if (mkdir(work_tree, 0777))
1087 die_errno(_("could not create work tree dir '%s'"),
1088 work_tree);
1089 junk_work_tree = work_tree;
1090 set_git_work_tree(work_tree);
1093 if (real_git_dir) {
1094 if (real_dest_exists)
1095 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1096 junk_git_dir = real_git_dir;
1097 } else {
1098 if (dest_exists)
1099 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1100 junk_git_dir = git_dir;
1102 if (safe_create_leading_directories_const(git_dir) < 0)
1103 die(_("could not create leading directories of '%s'"), git_dir);
1105 if (0 <= option_verbosity) {
1106 if (option_bare)
1107 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1108 else
1109 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1112 if (option_recurse_submodules.nr > 0) {
1113 struct string_list_item *item;
1114 struct strbuf sb = STRBUF_INIT;
1115 int val;
1117 /* remove duplicates */
1118 string_list_sort(&option_recurse_submodules);
1119 string_list_remove_duplicates(&option_recurse_submodules, 0);
1122 * NEEDSWORK: In a multi-working-tree world, this needs to be
1123 * set in the per-worktree config.
1125 for_each_string_list_item(item, &option_recurse_submodules) {
1126 strbuf_addf(&sb, "submodule.active=%s",
1127 item->string);
1128 string_list_append(&option_config,
1129 strbuf_detach(&sb, NULL));
1132 if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1133 val)
1134 string_list_append(&option_config, "submodule.recurse=true");
1136 if (option_required_reference.nr &&
1137 option_optional_reference.nr)
1138 die(_("clone --recursive is not compatible with "
1139 "both --reference and --reference-if-able"));
1140 else if (option_required_reference.nr) {
1141 string_list_append(&option_config,
1142 "submodule.alternateLocation=superproject");
1143 string_list_append(&option_config,
1144 "submodule.alternateErrorStrategy=die");
1145 } else if (option_optional_reference.nr) {
1146 string_list_append(&option_config,
1147 "submodule.alternateLocation=superproject");
1148 string_list_append(&option_config,
1149 "submodule.alternateErrorStrategy=info");
1154 * Initialize the repository, but skip initializing the reference
1155 * database. We do not yet know about the object format of the
1156 * repository, and reference backends may persist that information into
1157 * their on-disk data structures.
1159 init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN,
1160 ref_storage_format, NULL,
1161 do_not_override_repo_unix_permissions, INIT_DB_QUIET | INIT_DB_SKIP_REFDB);
1163 if (real_git_dir) {
1164 free((char *)git_dir);
1165 git_dir = real_git_dir;
1169 * We have a chicken-and-egg situation between initializing the refdb
1170 * and spawning transport helpers:
1172 * - Initializing the refdb requires us to know about the object
1173 * format. We thus have to spawn the transport helper to learn
1174 * about it.
1176 * - The transport helper may want to access the Git repository. But
1177 * because the refdb has not been initialized, we don't have "HEAD"
1178 * or "refs/". Thus, the helper cannot find the Git repository.
1180 * Ideally, we would have structured the helper protocol such that it's
1181 * mandatory for the helper to first announce its capabilities without
1182 * yet assuming a fully initialized repository. Like that, we could
1183 * have added a "lazy-refdb-init" capability that announces whether the
1184 * helper is ready to handle not-yet-initialized refdbs. If any helper
1185 * didn't support them, we would have fully initialized the refdb with
1186 * the SHA1 object format, but later on bailed out if we found out that
1187 * the remote repository used a different object format.
1189 * But we didn't, and thus we use the following workaround to partially
1190 * initialize the repository's refdb such that it can be discovered by
1191 * Git commands. To do so, we:
1193 * - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1195 * - Create the "refs/" directory.
1197 * - Set up the ref storage format and repository version as
1198 * required.
1200 * This is sufficient for Git commands to discover the Git directory.
1202 initialize_repository_version(GIT_HASH_UNKNOWN,
1203 the_repository->ref_storage_format, 1);
1205 strbuf_addf(&buf, "%s/HEAD", git_dir);
1206 write_file(buf.buf, "ref: refs/heads/.invalid");
1208 strbuf_reset(&buf);
1209 strbuf_addf(&buf, "%s/refs", git_dir);
1210 safe_create_dir(buf.buf, 1);
1213 * additional config can be injected with -c, make sure it's included
1214 * after init_db, which clears the entire config environment.
1216 write_config(&option_config);
1219 * re-read config after init_db and write_config to pick up any config
1220 * injected by --template and --config, respectively.
1222 git_config(git_clone_config, NULL);
1225 * If option_reject_shallow is specified from CLI option,
1226 * ignore config_reject_shallow from git_clone_config.
1228 if (config_reject_shallow != -1)
1229 reject_shallow = config_reject_shallow;
1230 if (option_reject_shallow != -1)
1231 reject_shallow = option_reject_shallow;
1234 * If option_filter_submodules is specified from CLI option,
1235 * ignore config_filter_submodules from git_clone_config.
1237 if (config_filter_submodules != -1)
1238 filter_submodules = config_filter_submodules;
1239 if (option_filter_submodules != -1)
1240 filter_submodules = option_filter_submodules;
1243 * Exit if the user seems to be doing something silly with submodule
1244 * filter flags (but not with filter configs, as those should be
1245 * set-and-forget).
1247 if (option_filter_submodules > 0 && !filter_options.choice)
1248 die(_("the option '%s' requires '%s'"),
1249 "--also-filter-submodules", "--filter");
1250 if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1251 die(_("the option '%s' requires '%s'"),
1252 "--also-filter-submodules", "--recurse-submodules");
1255 * apply the remote name provided by --origin only after this second
1256 * call to git_config, to ensure it overrides all config-based values.
1258 if (option_origin) {
1259 free(remote_name);
1260 remote_name = xstrdup(option_origin);
1263 if (!remote_name)
1264 remote_name = xstrdup("origin");
1266 if (!valid_remote_name(remote_name))
1267 die(_("'%s' is not a valid remote name"), remote_name);
1269 if (option_bare) {
1270 if (option_mirror)
1271 src_ref_prefix = "refs/";
1272 strbuf_addstr(&branch_top, src_ref_prefix);
1274 git_config_set("core.bare", "true");
1275 } else {
1276 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1279 strbuf_addf(&key, "remote.%s.url", remote_name);
1280 git_config_set(key.buf, repo);
1281 strbuf_reset(&key);
1283 if (option_no_tags) {
1284 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1285 git_config_set(key.buf, "--no-tags");
1286 strbuf_reset(&key);
1289 if (option_required_reference.nr || option_optional_reference.nr)
1290 setup_reference();
1292 remote = remote_get_early(remote_name);
1294 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1295 branch_top.buf);
1297 path = get_repo_path(remote->url[0], &is_bundle);
1298 is_local = option_local != 0 && path && !is_bundle;
1299 if (is_local) {
1300 if (option_depth)
1301 warning(_("--depth is ignored in local clones; use file:// instead."));
1302 if (option_since)
1303 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1304 if (option_not.nr)
1305 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1306 if (filter_options.choice)
1307 warning(_("--filter is ignored in local clones; use file:// instead."));
1308 if (!access(mkpath("%s/shallow", path), F_OK)) {
1309 if (reject_shallow)
1310 die(_("source repository is shallow, reject to clone."));
1311 if (option_local > 0)
1312 warning(_("source repository is shallow, ignoring --local"));
1313 is_local = 0;
1316 if (option_local > 0 && !is_local)
1317 warning(_("--local is ignored"));
1319 transport = transport_get(remote, path ? path : remote->url[0]);
1320 transport_set_verbosity(transport, option_verbosity, option_progress);
1321 transport->family = family;
1322 transport->cloning = 1;
1324 if (is_bundle) {
1325 struct bundle_header header = BUNDLE_HEADER_INIT;
1326 int fd = read_bundle_header(path, &header);
1327 int has_filter = header.filter.choice != LOFC_DISABLED;
1329 if (fd > 0)
1330 close(fd);
1331 bundle_header_release(&header);
1332 if (has_filter)
1333 die(_("cannot clone from filtered bundle"));
1336 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1338 if (reject_shallow)
1339 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1340 if (option_depth)
1341 transport_set_option(transport, TRANS_OPT_DEPTH,
1342 option_depth);
1343 if (option_since)
1344 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1345 option_since);
1346 if (option_not.nr)
1347 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1348 (const char *)&option_not);
1349 if (option_single_branch)
1350 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1352 if (option_upload_pack)
1353 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1354 option_upload_pack);
1356 if (server_options.nr)
1357 transport->server_options = &server_options;
1359 if (filter_options.choice) {
1360 const char *spec =
1361 expand_list_objects_filter_spec(&filter_options);
1362 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1363 spec);
1364 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1367 if (transport->smart_options && !deepen && !filter_options.choice)
1368 transport->smart_options->check_self_contained_and_connected = 1;
1370 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1371 refspec_ref_prefixes(&remote->fetch,
1372 &transport_ls_refs_options.ref_prefixes);
1373 if (option_branch)
1374 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1375 option_branch);
1376 if (!option_no_tags)
1377 strvec_push(&transport_ls_refs_options.ref_prefixes,
1378 "refs/tags/");
1380 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1383 * Now that we know what algorithm the remote side is using, let's set
1384 * ours to the same thing.
1386 hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1387 initialize_repository_version(hash_algo, the_repository->ref_storage_format, 1);
1388 repo_set_hash_algo(the_repository, hash_algo);
1389 create_reference_database(the_repository->ref_storage_format, NULL, 1);
1392 * Before fetching from the remote, download and install bundle
1393 * data from the --bundle-uri option.
1395 if (bundle_uri) {
1396 int has_heuristic = 0;
1398 /* At this point, we need the_repository to match the cloned repo. */
1399 if (repo_init(the_repository, git_dir, work_tree))
1400 warning(_("failed to initialize the repo, skipping bundle URI"));
1401 else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1402 warning(_("failed to fetch objects from bundle URI '%s'"),
1403 bundle_uri);
1404 else if (has_heuristic)
1405 git_config_set_gently("fetch.bundleuri", bundle_uri);
1406 } else {
1408 * Populate transport->got_remote_bundle_uri and
1409 * transport->bundle_uri. We might get nothing.
1411 transport_get_remote_bundle_uri(transport);
1413 if (transport->bundles &&
1414 hashmap_get_size(&transport->bundles->bundles)) {
1415 /* At this point, we need the_repository to match the cloned repo. */
1416 if (repo_init(the_repository, git_dir, work_tree))
1417 warning(_("failed to initialize the repo, skipping bundle URI"));
1418 else if (fetch_bundle_list(the_repository,
1419 transport->bundles))
1420 warning(_("failed to fetch advertised bundles"));
1421 } else {
1422 clear_bundle_list(transport->bundles);
1423 FREE_AND_NULL(transport->bundles);
1427 if (refs)
1428 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1430 if (mapped_refs) {
1432 * transport_get_remote_refs() may return refs with null sha-1
1433 * in mapped_refs (see struct transport->get_refs_list
1434 * comment). In that case we need fetch it early because
1435 * remote_head code below relies on it.
1437 * for normal clones, transport_get_remote_refs() should
1438 * return reliable ref set, we can delay cloning until after
1439 * remote HEAD check.
1441 for (ref = refs; ref; ref = ref->next)
1442 if (is_null_oid(&ref->old_oid)) {
1443 complete_refs_before_fetch = 0;
1444 break;
1447 if (!is_local && !complete_refs_before_fetch) {
1448 if (transport_fetch_refs(transport, mapped_refs))
1449 die(_("remote transport reported error"));
1453 remote_head = find_ref_by_name(refs, "HEAD");
1454 remote_head_points_at = guess_remote_head(remote_head, mapped_refs, 0);
1456 if (option_branch) {
1457 our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1458 if (!our_head_points_at)
1459 die(_("Remote branch %s not found in upstream %s"),
1460 option_branch, remote_name);
1461 } else if (remote_head_points_at) {
1462 our_head_points_at = remote_head_points_at;
1463 } else if (remote_head) {
1464 our_head_points_at = NULL;
1465 } else {
1466 char *to_free = NULL;
1467 const char *branch;
1469 if (!mapped_refs) {
1470 warning(_("You appear to have cloned an empty repository."));
1471 option_no_checkout = 1;
1474 if (transport_ls_refs_options.unborn_head_target &&
1475 skip_prefix(transport_ls_refs_options.unborn_head_target,
1476 "refs/heads/", &branch)) {
1477 unborn_head = xstrdup(transport_ls_refs_options.unborn_head_target);
1478 } else {
1479 branch = to_free = repo_default_branch_name(the_repository, 0);
1480 unborn_head = xstrfmt("refs/heads/%s", branch);
1484 * We may have selected a local default branch name "foo",
1485 * and even though the remote's HEAD does not point there,
1486 * it may still have a "foo" branch. If so, set it up so
1487 * that we can follow the usual checkout code later.
1489 * Note that for an empty repo we'll already have set
1490 * option_no_checkout above, which would work against us here.
1491 * But for an empty repo, find_remote_branch() can never find
1492 * a match.
1494 our_head_points_at = find_remote_branch(mapped_refs, branch);
1496 free(to_free);
1499 write_refspec_config(src_ref_prefix, our_head_points_at,
1500 remote_head_points_at, &branch_top);
1502 if (filter_options.choice)
1503 partial_clone_register(remote_name, &filter_options);
1505 if (is_local)
1506 clone_local(path, git_dir);
1507 else if (mapped_refs && complete_refs_before_fetch) {
1508 if (transport_fetch_refs(transport, mapped_refs))
1509 die(_("remote transport reported error"));
1512 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1513 branch_top.buf, reflog_msg.buf, transport,
1514 !is_local);
1516 update_head(our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1519 * We want to show progress for recursive submodule clones iff
1520 * we did so for the main clone. But only the transport knows
1521 * the final decision for this flag, so we need to rescue the value
1522 * before we free the transport.
1524 submodule_progress = transport->progress;
1526 transport_unlock_pack(transport, 0);
1527 transport_disconnect(transport);
1529 if (option_dissociate) {
1530 close_object_store(the_repository->objects);
1531 dissociate_from_references();
1534 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1535 return 1;
1537 junk_mode = JUNK_LEAVE_REPO;
1538 err = checkout(submodule_progress, filter_submodules);
1540 free(remote_name);
1541 strbuf_release(&reflog_msg);
1542 strbuf_release(&branch_top);
1543 strbuf_release(&buf);
1544 strbuf_release(&key);
1545 free_refs(mapped_refs);
1546 free_refs(remote_head_points_at);
1547 free(unborn_head);
1548 free(dir);
1549 free(path);
1550 free(repo_to_free);
1551 UNLEAK(repo);
1552 junk_mode = JUNK_LEAVE_ALL;
1554 transport_ls_refs_options_release(&transport_ls_refs_options);
1555 return err;