The eighth batch
[alt-git.git] / builtin / clone.c
blob23993b905b779671c7828876f918cfd1e04a92e0
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 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 char *suffix[] = { "/.git", "", ".git/.git", ".git" };
181 static 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;
527 if (option_single_branch) {
528 struct ref *remote_head = NULL;
530 if (!option_branch)
531 remote_head = guess_remote_head(head, refs, 0);
532 else {
533 local_refs = NULL;
534 tail = &local_refs;
535 remote_head = copy_ref(find_remote_branch(refs, option_branch));
538 if (!remote_head && option_branch)
539 warning(_("Could not find remote branch %s to clone."),
540 option_branch);
541 else {
542 int i;
543 for (i = 0; i < refspec->nr; i++)
544 get_fetch_map(remote_head, &refspec->items[i],
545 &tail, 0);
547 /* if --branch=tag, pull the requested tag explicitly */
548 get_fetch_map(remote_head, tag_refspec, &tail, 0);
550 free_refs(remote_head);
551 } else {
552 int i;
553 for (i = 0; i < refspec->nr; i++)
554 get_fetch_map(refs, &refspec->items[i], &tail, 0);
557 if (!option_mirror && !option_single_branch && !option_no_tags)
558 get_fetch_map(refs, tag_refspec, &tail, 0);
560 return local_refs;
563 static void write_remote_refs(const struct ref *local_refs)
565 const struct ref *r;
567 struct ref_transaction *t;
568 struct strbuf err = STRBUF_INIT;
570 t = ref_store_transaction_begin(get_main_ref_store(the_repository),
571 &err);
572 if (!t)
573 die("%s", err.buf);
575 for (r = local_refs; r; r = r->next) {
576 if (!r->peer_ref)
577 continue;
578 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
579 0, NULL, &err))
580 die("%s", err.buf);
583 if (initial_ref_transaction_commit(t, &err))
584 die("%s", err.buf);
586 strbuf_release(&err);
587 ref_transaction_free(t);
590 static void write_followtags(const struct ref *refs, const char *msg)
592 const struct ref *ref;
593 for (ref = refs; ref; ref = ref->next) {
594 if (!starts_with(ref->name, "refs/tags/"))
595 continue;
596 if (ends_with(ref->name, "^{}"))
597 continue;
598 if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid,
599 OBJECT_INFO_QUICK |
600 OBJECT_INFO_SKIP_FETCH_OBJECT))
601 continue;
602 refs_update_ref(get_main_ref_store(the_repository), msg,
603 ref->name, &ref->old_oid, NULL, 0,
604 UPDATE_REFS_DIE_ON_ERR);
608 static const struct object_id *iterate_ref_map(void *cb_data)
610 struct ref **rm = cb_data;
611 struct ref *ref = *rm;
614 * Skip anything missing a peer_ref, which we are not
615 * actually going to write a ref for.
617 while (ref && !ref->peer_ref)
618 ref = ref->next;
619 if (!ref)
620 return NULL;
622 *rm = ref->next;
623 return &ref->old_oid;
626 static void update_remote_refs(const struct ref *refs,
627 const struct ref *mapped_refs,
628 const struct ref *remote_head_points_at,
629 const char *branch_top,
630 const char *msg,
631 struct transport *transport,
632 int check_connectivity)
634 const struct ref *rm = mapped_refs;
636 if (check_connectivity) {
637 struct check_connected_options opt = CHECK_CONNECTED_INIT;
639 opt.transport = transport;
640 opt.progress = transport->progress;
642 if (check_connected(iterate_ref_map, &rm, &opt))
643 die(_("remote did not send all necessary objects"));
646 if (refs) {
647 write_remote_refs(mapped_refs);
648 if (option_single_branch && !option_no_tags)
649 write_followtags(refs, msg);
652 if (remote_head_points_at && !option_bare) {
653 struct strbuf head_ref = STRBUF_INIT;
654 strbuf_addstr(&head_ref, branch_top);
655 strbuf_addstr(&head_ref, "HEAD");
656 if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
657 remote_head_points_at->peer_ref->name,
658 msg) < 0)
659 die(_("unable to update %s"), head_ref.buf);
660 strbuf_release(&head_ref);
664 static void update_head(const struct ref *our, const struct ref *remote,
665 const char *unborn, const char *msg)
667 const char *head;
668 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
669 /* Local default branch link */
670 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
671 die(_("unable to update HEAD"));
672 if (!option_bare) {
673 refs_update_ref(get_main_ref_store(the_repository),
674 msg, "HEAD", &our->old_oid, NULL, 0,
675 UPDATE_REFS_DIE_ON_ERR);
676 install_branch_config(0, head, remote_name, our->name);
678 } else if (our) {
679 struct commit *c = lookup_commit_reference(the_repository,
680 &our->old_oid);
681 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
682 refs_update_ref(get_main_ref_store(the_repository), msg,
683 "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
684 UPDATE_REFS_DIE_ON_ERR);
685 } else if (remote) {
687 * We know remote HEAD points to a non-branch, or
688 * HEAD points to a branch but we don't know which one.
689 * Detach HEAD in all these cases.
691 refs_update_ref(get_main_ref_store(the_repository), msg,
692 "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
693 UPDATE_REFS_DIE_ON_ERR);
694 } else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
696 * Unborn head from remote; same as "our" case above except
697 * that we have no ref to update.
699 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
700 die(_("unable to update HEAD"));
701 if (!option_bare)
702 install_branch_config(0, head, remote_name, unborn);
706 static int git_sparse_checkout_init(const char *repo)
708 struct child_process cmd = CHILD_PROCESS_INIT;
709 int result = 0;
710 strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
713 * We must apply the setting in the current process
714 * for the later checkout to use the sparse-checkout file.
716 core_apply_sparse_checkout = 1;
718 cmd.git_cmd = 1;
719 if (run_command(&cmd)) {
720 error(_("failed to initialize sparse-checkout"));
721 result = 1;
724 return result;
727 static int checkout(int submodule_progress, int filter_submodules)
729 struct object_id oid;
730 char *head;
731 struct lock_file lock_file = LOCK_INIT;
732 struct unpack_trees_options opts;
733 struct tree *tree;
734 struct tree_desc t;
735 int err = 0;
737 if (option_no_checkout)
738 return 0;
740 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
741 RESOLVE_REF_READING, &oid, NULL);
742 if (!head) {
743 warning(_("remote HEAD refers to nonexistent ref, "
744 "unable to checkout"));
745 return 0;
747 if (!strcmp(head, "HEAD")) {
748 if (advice_enabled(ADVICE_DETACHED_HEAD))
749 detach_advice(oid_to_hex(&oid));
750 FREE_AND_NULL(head);
751 } else {
752 if (!starts_with(head, "refs/heads/"))
753 die(_("HEAD not found below refs/heads!"));
756 /* We need to be in the new work tree for the checkout */
757 setup_work_tree();
759 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
761 memset(&opts, 0, sizeof opts);
762 opts.update = 1;
763 opts.merge = 1;
764 opts.clone = 1;
765 opts.preserve_ignored = 0;
766 opts.fn = oneway_merge;
767 opts.verbose_update = (option_verbosity >= 0);
768 opts.src_index = the_repository->index;
769 opts.dst_index = the_repository->index;
770 init_checkout_metadata(&opts.meta, head, &oid, NULL);
772 tree = parse_tree_indirect(&oid);
773 if (!tree)
774 die(_("unable to parse commit %s"), oid_to_hex(&oid));
775 if (parse_tree(tree) < 0)
776 exit(128);
777 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
778 if (unpack_trees(1, &t, &opts) < 0)
779 die(_("unable to checkout working tree"));
781 free(head);
783 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
784 die(_("unable to write new index file"));
786 err |= run_hooks_l("post-checkout", oid_to_hex(null_oid()),
787 oid_to_hex(&oid), "1", NULL);
789 if (!err && (option_recurse_submodules.nr > 0)) {
790 struct child_process cmd = CHILD_PROCESS_INIT;
791 strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
792 "--recursive", NULL);
794 if (option_shallow_submodules == 1)
795 strvec_push(&cmd.args, "--depth=1");
797 if (max_jobs != -1)
798 strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
800 if (submodule_progress)
801 strvec_push(&cmd.args, "--progress");
803 if (option_verbosity < 0)
804 strvec_push(&cmd.args, "--quiet");
806 if (option_remote_submodules) {
807 strvec_push(&cmd.args, "--remote");
808 strvec_push(&cmd.args, "--no-fetch");
811 if (filter_submodules && filter_options.choice)
812 strvec_pushf(&cmd.args, "--filter=%s",
813 expand_list_objects_filter_spec(&filter_options));
815 if (option_single_branch >= 0)
816 strvec_push(&cmd.args, option_single_branch ?
817 "--single-branch" :
818 "--no-single-branch");
820 cmd.git_cmd = 1;
821 err = run_command(&cmd);
824 return err;
827 static int git_clone_config(const char *k, const char *v,
828 const struct config_context *ctx, void *cb)
830 if (!strcmp(k, "clone.defaultremotename")) {
831 if (!v)
832 return config_error_nonbool(k);
833 free(remote_name);
834 remote_name = xstrdup(v);
836 if (!strcmp(k, "clone.rejectshallow"))
837 config_reject_shallow = git_config_bool(k, v);
838 if (!strcmp(k, "clone.filtersubmodules"))
839 config_filter_submodules = git_config_bool(k, v);
841 return git_default_config(k, v, ctx, cb);
844 static int write_one_config(const char *key, const char *value,
845 const struct config_context *ctx,
846 void *data)
849 * give git_clone_config a chance to write config values back to the
850 * environment, since git_config_set_multivar_gently only deals with
851 * config-file writes
853 int apply_failed = git_clone_config(key, value, ctx, data);
854 if (apply_failed)
855 return apply_failed;
857 return git_config_set_multivar_gently(key,
858 value ? value : "true",
859 CONFIG_REGEX_NONE, 0);
862 static void write_config(struct string_list *config)
864 int i;
866 for (i = 0; i < config->nr; i++) {
867 if (git_config_parse_parameter(config->items[i].string,
868 write_one_config, NULL) < 0)
869 die(_("unable to write parameters to config file"));
873 static void write_refspec_config(const char *src_ref_prefix,
874 const struct ref *our_head_points_at,
875 const struct ref *remote_head_points_at,
876 struct strbuf *branch_top)
878 struct strbuf key = STRBUF_INIT;
879 struct strbuf value = STRBUF_INIT;
881 if (option_mirror || !option_bare) {
882 if (option_single_branch && !option_mirror) {
883 if (option_branch) {
884 if (starts_with(our_head_points_at->name, "refs/tags/"))
885 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
886 our_head_points_at->name);
887 else
888 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
889 branch_top->buf, option_branch);
890 } else if (remote_head_points_at) {
891 const char *head = remote_head_points_at->name;
892 if (!skip_prefix(head, "refs/heads/", &head))
893 BUG("remote HEAD points at non-head?");
895 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
896 branch_top->buf, head);
899 * otherwise, the next "git fetch" will
900 * simply fetch from HEAD without updating
901 * any remote-tracking branch, which is what
902 * we want.
904 } else {
905 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
907 /* Configure the remote */
908 if (value.len) {
909 strbuf_addf(&key, "remote.%s.fetch", remote_name);
910 git_config_set_multivar(key.buf, value.buf, "^$", 0);
911 strbuf_reset(&key);
913 if (option_mirror) {
914 strbuf_addf(&key, "remote.%s.mirror", remote_name);
915 git_config_set(key.buf, "true");
916 strbuf_reset(&key);
921 strbuf_release(&key);
922 strbuf_release(&value);
925 static void dissociate_from_references(void)
927 char *alternates = git_pathdup("objects/info/alternates");
929 if (!access(alternates, F_OK)) {
930 struct child_process cmd = CHILD_PROCESS_INIT;
932 cmd.git_cmd = 1;
933 cmd.no_stdin = 1;
934 strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
935 if (run_command(&cmd))
936 die(_("cannot repack to clean up"));
937 if (unlink(alternates) && errno != ENOENT)
938 die_errno(_("cannot unlink temporary alternates file"));
940 free(alternates);
943 static int path_exists(const char *path)
945 struct stat sb;
946 return !stat(path, &sb);
949 int cmd_clone(int argc, const char **argv, const char *prefix)
951 int is_bundle = 0, is_local;
952 int reject_shallow = 0;
953 const char *repo_name, *repo, *work_tree, *git_dir;
954 char *repo_to_free = NULL;
955 char *path = NULL, *dir, *display_repo = NULL;
956 int dest_exists, real_dest_exists = 0;
957 const struct ref *refs, *remote_head;
958 struct ref *remote_head_points_at = NULL;
959 const struct ref *our_head_points_at;
960 char *unborn_head = NULL;
961 struct ref *mapped_refs = NULL;
962 const struct ref *ref;
963 struct strbuf key = STRBUF_INIT;
964 struct strbuf buf = STRBUF_INIT;
965 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
966 struct transport *transport = NULL;
967 const char *src_ref_prefix = "refs/heads/";
968 struct remote *remote;
969 int err = 0, complete_refs_before_fetch = 1;
970 int submodule_progress;
971 int filter_submodules = 0;
972 int hash_algo;
973 unsigned int ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
974 const int do_not_override_repo_unix_permissions = -1;
975 const char *template_dir;
976 char *template_dir_dup = NULL;
978 struct transport_ls_refs_options transport_ls_refs_options =
979 TRANSPORT_LS_REFS_OPTIONS_INIT;
981 packet_trace_identity("clone");
983 git_config(git_clone_config, NULL);
985 argc = parse_options(argc, argv, prefix, builtin_clone_options,
986 builtin_clone_usage, 0);
988 if (argc > 2)
989 usage_msg_opt(_("Too many arguments."),
990 builtin_clone_usage, builtin_clone_options);
992 if (argc == 0)
993 usage_msg_opt(_("You must specify a repository to clone."),
994 builtin_clone_usage, builtin_clone_options);
996 xsetenv("GIT_CLONE_PROTECTION_ACTIVE", "true", 0 /* allow user override */);
997 template_dir = get_template_dir(option_template);
998 if (*template_dir && !is_absolute_path(template_dir))
999 template_dir = template_dir_dup =
1000 absolute_pathdup(template_dir);
1001 xsetenv("GIT_CLONE_TEMPLATE_DIR", template_dir, 1);
1003 if (option_depth || option_since || option_not.nr)
1004 deepen = 1;
1005 if (option_single_branch == -1)
1006 option_single_branch = deepen ? 1 : 0;
1008 if (ref_format) {
1009 ref_storage_format = ref_storage_format_by_name(ref_format);
1010 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1011 die(_("unknown ref storage format '%s'"), ref_format);
1014 if (option_mirror)
1015 option_bare = 1;
1017 if (option_bare) {
1018 if (real_git_dir)
1019 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1020 option_no_checkout = 1;
1023 if (bundle_uri && deepen)
1024 die(_("options '%s' and '%s' cannot be used together"),
1025 "--bundle-uri",
1026 "--depth/--shallow-since/--shallow-exclude");
1028 repo_name = argv[0];
1030 path = get_repo_path(repo_name, &is_bundle);
1031 if (path) {
1032 FREE_AND_NULL(path);
1033 repo = repo_to_free = absolute_pathdup(repo_name);
1034 } else if (strchr(repo_name, ':')) {
1035 repo = repo_name;
1036 display_repo = transport_anonymize_url(repo);
1037 } else
1038 die(_("repository '%s' does not exist"), repo_name);
1040 /* no need to be strict, transport_set_option() will validate it again */
1041 if (option_depth && atoi(option_depth) < 1)
1042 die(_("depth %s is not a positive number"), option_depth);
1044 if (argc == 2)
1045 dir = xstrdup(argv[1]);
1046 else
1047 dir = git_url_basename(repo_name, is_bundle, option_bare);
1048 strip_dir_trailing_slashes(dir);
1050 dest_exists = path_exists(dir);
1051 if (dest_exists && !is_empty_dir(dir))
1052 die(_("destination path '%s' already exists and is not "
1053 "an empty directory."), dir);
1055 if (real_git_dir) {
1056 real_dest_exists = path_exists(real_git_dir);
1057 if (real_dest_exists && !is_empty_dir(real_git_dir))
1058 die(_("repository path '%s' already exists and is not "
1059 "an empty directory."), real_git_dir);
1063 strbuf_addf(&reflog_msg, "clone: from %s",
1064 display_repo ? display_repo : repo);
1065 free(display_repo);
1067 if (option_bare)
1068 work_tree = NULL;
1069 else {
1070 work_tree = getenv("GIT_WORK_TREE");
1071 if (work_tree && path_exists(work_tree))
1072 die(_("working tree '%s' already exists."), work_tree);
1075 if (option_bare || work_tree)
1076 git_dir = xstrdup(dir);
1077 else {
1078 work_tree = dir;
1079 git_dir = mkpathdup("%s/.git", dir);
1082 atexit(remove_junk);
1083 sigchain_push_common(remove_junk_on_signal);
1085 if (!option_bare) {
1086 if (safe_create_leading_directories_const(work_tree) < 0)
1087 die_errno(_("could not create leading directories of '%s'"),
1088 work_tree);
1089 if (dest_exists)
1090 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1091 else if (mkdir(work_tree, 0777))
1092 die_errno(_("could not create work tree dir '%s'"),
1093 work_tree);
1094 junk_work_tree = work_tree;
1095 set_git_work_tree(work_tree);
1098 if (real_git_dir) {
1099 if (real_dest_exists)
1100 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1101 junk_git_dir = real_git_dir;
1102 } else {
1103 if (dest_exists)
1104 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1105 junk_git_dir = git_dir;
1107 if (safe_create_leading_directories_const(git_dir) < 0)
1108 die(_("could not create leading directories of '%s'"), git_dir);
1110 if (0 <= option_verbosity) {
1111 if (option_bare)
1112 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1113 else
1114 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1117 if (option_recurse_submodules.nr > 0) {
1118 struct string_list_item *item;
1119 struct strbuf sb = STRBUF_INIT;
1120 int val;
1122 /* remove duplicates */
1123 string_list_sort(&option_recurse_submodules);
1124 string_list_remove_duplicates(&option_recurse_submodules, 0);
1127 * NEEDSWORK: In a multi-working-tree world, this needs to be
1128 * set in the per-worktree config.
1130 for_each_string_list_item(item, &option_recurse_submodules) {
1131 strbuf_addf(&sb, "submodule.active=%s",
1132 item->string);
1133 string_list_append(&option_config,
1134 strbuf_detach(&sb, NULL));
1137 if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1138 val)
1139 string_list_append(&option_config, "submodule.recurse=true");
1141 if (option_required_reference.nr &&
1142 option_optional_reference.nr)
1143 die(_("clone --recursive is not compatible with "
1144 "both --reference and --reference-if-able"));
1145 else if (option_required_reference.nr) {
1146 string_list_append(&option_config,
1147 "submodule.alternateLocation=superproject");
1148 string_list_append(&option_config,
1149 "submodule.alternateErrorStrategy=die");
1150 } else if (option_optional_reference.nr) {
1151 string_list_append(&option_config,
1152 "submodule.alternateLocation=superproject");
1153 string_list_append(&option_config,
1154 "submodule.alternateErrorStrategy=info");
1159 * Initialize the repository, but skip initializing the reference
1160 * database. We do not yet know about the object format of the
1161 * repository, and reference backends may persist that information into
1162 * their on-disk data structures.
1164 init_db(git_dir, real_git_dir, template_dir, GIT_HASH_UNKNOWN,
1165 ref_storage_format, NULL,
1166 do_not_override_repo_unix_permissions, INIT_DB_QUIET | INIT_DB_SKIP_REFDB);
1168 if (real_git_dir) {
1169 free((char *)git_dir);
1170 git_dir = real_git_dir;
1174 * We have a chicken-and-egg situation between initializing the refdb
1175 * and spawning transport helpers:
1177 * - Initializing the refdb requires us to know about the object
1178 * format. We thus have to spawn the transport helper to learn
1179 * about it.
1181 * - The transport helper may want to access the Git repository. But
1182 * because the refdb has not been initialized, we don't have "HEAD"
1183 * or "refs/". Thus, the helper cannot find the Git repository.
1185 * Ideally, we would have structured the helper protocol such that it's
1186 * mandatory for the helper to first announce its capabilities without
1187 * yet assuming a fully initialized repository. Like that, we could
1188 * have added a "lazy-refdb-init" capability that announces whether the
1189 * helper is ready to handle not-yet-initialized refdbs. If any helper
1190 * didn't support them, we would have fully initialized the refdb with
1191 * the SHA1 object format, but later on bailed out if we found out that
1192 * the remote repository used a different object format.
1194 * But we didn't, and thus we use the following workaround to partially
1195 * initialize the repository's refdb such that it can be discovered by
1196 * Git commands. To do so, we:
1198 * - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1200 * - Create the "refs/" directory.
1202 * - Set up the ref storage format and repository version as
1203 * required.
1205 * This is sufficient for Git commands to discover the Git directory.
1207 initialize_repository_version(GIT_HASH_UNKNOWN,
1208 the_repository->ref_storage_format, 1);
1210 strbuf_addf(&buf, "%s/HEAD", git_dir);
1211 write_file(buf.buf, "ref: refs/heads/.invalid");
1213 strbuf_reset(&buf);
1214 strbuf_addf(&buf, "%s/refs", git_dir);
1215 safe_create_dir(buf.buf, 1);
1218 * additional config can be injected with -c, make sure it's included
1219 * after init_db, which clears the entire config environment.
1221 write_config(&option_config);
1224 * re-read config after init_db and write_config to pick up any config
1225 * injected by --template and --config, respectively.
1227 git_config(git_clone_config, NULL);
1230 * If option_reject_shallow is specified from CLI option,
1231 * ignore config_reject_shallow from git_clone_config.
1233 if (config_reject_shallow != -1)
1234 reject_shallow = config_reject_shallow;
1235 if (option_reject_shallow != -1)
1236 reject_shallow = option_reject_shallow;
1239 * If option_filter_submodules is specified from CLI option,
1240 * ignore config_filter_submodules from git_clone_config.
1242 if (config_filter_submodules != -1)
1243 filter_submodules = config_filter_submodules;
1244 if (option_filter_submodules != -1)
1245 filter_submodules = option_filter_submodules;
1248 * Exit if the user seems to be doing something silly with submodule
1249 * filter flags (but not with filter configs, as those should be
1250 * set-and-forget).
1252 if (option_filter_submodules > 0 && !filter_options.choice)
1253 die(_("the option '%s' requires '%s'"),
1254 "--also-filter-submodules", "--filter");
1255 if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1256 die(_("the option '%s' requires '%s'"),
1257 "--also-filter-submodules", "--recurse-submodules");
1260 * apply the remote name provided by --origin only after this second
1261 * call to git_config, to ensure it overrides all config-based values.
1263 if (option_origin) {
1264 free(remote_name);
1265 remote_name = xstrdup(option_origin);
1268 if (!remote_name)
1269 remote_name = xstrdup("origin");
1271 if (!valid_remote_name(remote_name))
1272 die(_("'%s' is not a valid remote name"), remote_name);
1274 if (option_bare) {
1275 if (option_mirror)
1276 src_ref_prefix = "refs/";
1277 strbuf_addstr(&branch_top, src_ref_prefix);
1279 git_config_set("core.bare", "true");
1280 } else {
1281 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1284 strbuf_addf(&key, "remote.%s.url", remote_name);
1285 git_config_set(key.buf, repo);
1286 strbuf_reset(&key);
1288 if (option_no_tags) {
1289 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1290 git_config_set(key.buf, "--no-tags");
1291 strbuf_reset(&key);
1294 if (option_required_reference.nr || option_optional_reference.nr)
1295 setup_reference();
1297 remote = remote_get_early(remote_name);
1299 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1300 branch_top.buf);
1302 path = get_repo_path(remote->url[0], &is_bundle);
1303 is_local = option_local != 0 && path && !is_bundle;
1304 if (is_local) {
1305 if (option_depth)
1306 warning(_("--depth is ignored in local clones; use file:// instead."));
1307 if (option_since)
1308 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1309 if (option_not.nr)
1310 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1311 if (filter_options.choice)
1312 warning(_("--filter is ignored in local clones; use file:// instead."));
1313 if (!access(mkpath("%s/shallow", path), F_OK)) {
1314 if (reject_shallow)
1315 die(_("source repository is shallow, reject to clone."));
1316 if (option_local > 0)
1317 warning(_("source repository is shallow, ignoring --local"));
1318 is_local = 0;
1321 if (option_local > 0 && !is_local)
1322 warning(_("--local is ignored"));
1324 transport = transport_get(remote, path ? path : remote->url[0]);
1325 transport_set_verbosity(transport, option_verbosity, option_progress);
1326 transport->family = family;
1327 transport->cloning = 1;
1329 if (is_bundle) {
1330 struct bundle_header header = BUNDLE_HEADER_INIT;
1331 int fd = read_bundle_header(path, &header);
1332 int has_filter = header.filter.choice != LOFC_DISABLED;
1334 if (fd > 0)
1335 close(fd);
1336 bundle_header_release(&header);
1337 if (has_filter)
1338 die(_("cannot clone from filtered bundle"));
1341 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1343 if (reject_shallow)
1344 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1345 if (option_depth)
1346 transport_set_option(transport, TRANS_OPT_DEPTH,
1347 option_depth);
1348 if (option_since)
1349 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1350 option_since);
1351 if (option_not.nr)
1352 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1353 (const char *)&option_not);
1354 if (option_single_branch)
1355 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1357 if (option_upload_pack)
1358 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1359 option_upload_pack);
1361 if (server_options.nr)
1362 transport->server_options = &server_options;
1364 if (filter_options.choice) {
1365 const char *spec =
1366 expand_list_objects_filter_spec(&filter_options);
1367 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1368 spec);
1369 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1372 if (transport->smart_options && !deepen && !filter_options.choice)
1373 transport->smart_options->check_self_contained_and_connected = 1;
1375 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1376 refspec_ref_prefixes(&remote->fetch,
1377 &transport_ls_refs_options.ref_prefixes);
1378 if (option_branch)
1379 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1380 option_branch);
1381 if (!option_no_tags)
1382 strvec_push(&transport_ls_refs_options.ref_prefixes,
1383 "refs/tags/");
1385 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1388 * Now that we know what algorithm the remote side is using, let's set
1389 * ours to the same thing.
1391 hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1392 initialize_repository_version(hash_algo, the_repository->ref_storage_format, 1);
1393 repo_set_hash_algo(the_repository, hash_algo);
1394 create_reference_database(the_repository->ref_storage_format, NULL, 1);
1397 * Before fetching from the remote, download and install bundle
1398 * data from the --bundle-uri option.
1400 if (bundle_uri) {
1401 int has_heuristic = 0;
1403 /* At this point, we need the_repository to match the cloned repo. */
1404 if (repo_init(the_repository, git_dir, work_tree))
1405 warning(_("failed to initialize the repo, skipping bundle URI"));
1406 else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1407 warning(_("failed to fetch objects from bundle URI '%s'"),
1408 bundle_uri);
1409 else if (has_heuristic)
1410 git_config_set_gently("fetch.bundleuri", bundle_uri);
1411 } else {
1413 * Populate transport->got_remote_bundle_uri and
1414 * transport->bundle_uri. We might get nothing.
1416 transport_get_remote_bundle_uri(transport);
1418 if (transport->bundles &&
1419 hashmap_get_size(&transport->bundles->bundles)) {
1420 /* At this point, we need the_repository to match the cloned repo. */
1421 if (repo_init(the_repository, git_dir, work_tree))
1422 warning(_("failed to initialize the repo, skipping bundle URI"));
1423 else if (fetch_bundle_list(the_repository,
1424 transport->bundles))
1425 warning(_("failed to fetch advertised bundles"));
1426 } else {
1427 clear_bundle_list(transport->bundles);
1428 FREE_AND_NULL(transport->bundles);
1432 if (refs)
1433 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1435 if (mapped_refs) {
1437 * transport_get_remote_refs() may return refs with null sha-1
1438 * in mapped_refs (see struct transport->get_refs_list
1439 * comment). In that case we need fetch it early because
1440 * remote_head code below relies on it.
1442 * for normal clones, transport_get_remote_refs() should
1443 * return reliable ref set, we can delay cloning until after
1444 * remote HEAD check.
1446 for (ref = refs; ref; ref = ref->next)
1447 if (is_null_oid(&ref->old_oid)) {
1448 complete_refs_before_fetch = 0;
1449 break;
1452 if (!is_local && !complete_refs_before_fetch) {
1453 if (transport_fetch_refs(transport, mapped_refs))
1454 die(_("remote transport reported error"));
1458 remote_head = find_ref_by_name(refs, "HEAD");
1459 remote_head_points_at = guess_remote_head(remote_head, mapped_refs, 0);
1461 if (option_branch) {
1462 our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1463 if (!our_head_points_at)
1464 die(_("Remote branch %s not found in upstream %s"),
1465 option_branch, remote_name);
1466 } else if (remote_head_points_at) {
1467 our_head_points_at = remote_head_points_at;
1468 } else if (remote_head) {
1469 our_head_points_at = NULL;
1470 } else {
1471 const char *branch;
1473 if (!mapped_refs) {
1474 warning(_("You appear to have cloned an empty repository."));
1475 option_no_checkout = 1;
1478 if (transport_ls_refs_options.unborn_head_target &&
1479 skip_prefix(transport_ls_refs_options.unborn_head_target,
1480 "refs/heads/", &branch)) {
1481 unborn_head = xstrdup(transport_ls_refs_options.unborn_head_target);
1482 } else {
1483 branch = git_default_branch_name(0);
1484 unborn_head = xstrfmt("refs/heads/%s", branch);
1488 * We may have selected a local default branch name "foo",
1489 * and even though the remote's HEAD does not point there,
1490 * it may still have a "foo" branch. If so, set it up so
1491 * that we can follow the usual checkout code later.
1493 * Note that for an empty repo we'll already have set
1494 * option_no_checkout above, which would work against us here.
1495 * But for an empty repo, find_remote_branch() can never find
1496 * a match.
1498 our_head_points_at = find_remote_branch(mapped_refs, branch);
1501 write_refspec_config(src_ref_prefix, our_head_points_at,
1502 remote_head_points_at, &branch_top);
1504 if (filter_options.choice)
1505 partial_clone_register(remote_name, &filter_options);
1507 if (is_local)
1508 clone_local(path, git_dir);
1509 else if (mapped_refs && complete_refs_before_fetch) {
1510 if (transport_fetch_refs(transport, mapped_refs))
1511 die(_("remote transport reported error"));
1514 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1515 branch_top.buf, reflog_msg.buf, transport,
1516 !is_local);
1518 update_head(our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1521 * We want to show progress for recursive submodule clones iff
1522 * we did so for the main clone. But only the transport knows
1523 * the final decision for this flag, so we need to rescue the value
1524 * before we free the transport.
1526 submodule_progress = transport->progress;
1528 transport_unlock_pack(transport, 0);
1529 transport_disconnect(transport);
1531 if (option_dissociate) {
1532 close_object_store(the_repository->objects);
1533 dissociate_from_references();
1536 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1537 return 1;
1539 junk_mode = JUNK_LEAVE_REPO;
1540 err = checkout(submodule_progress, filter_submodules);
1542 free(remote_name);
1543 strbuf_release(&reflog_msg);
1544 strbuf_release(&branch_top);
1545 strbuf_release(&buf);
1546 strbuf_release(&key);
1547 free_refs(mapped_refs);
1548 free_refs(remote_head_points_at);
1549 free(unborn_head);
1550 free(dir);
1551 free(path);
1552 free(repo_to_free);
1553 free(template_dir_dup);
1554 junk_mode = JUNK_LEAVE_ALL;
1556 transport_ls_refs_options_release(&transport_ls_refs_options);
1557 return err;