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.
11 #define USE_THE_INDEX_COMPATIBILITY_MACROS
15 #include "parse-options.h"
16 #include "fetch-pack.h"
19 #include "object-store.h"
21 #include "tree-walk.h"
22 #include "unpack-trees.h"
23 #include "transport.h"
26 #include "dir-iterator.h"
31 #include "run-command.h"
32 #include "connected.h"
34 #include "list-objects-filter-options.h"
39 * - respect DB_ENVIRONMENT for .git/objects.
41 * Implementation notes:
42 * - dropping use-separate-remote and no-separate-remote compatibility
45 static const char * const builtin_clone_usage[] = {
46 N_("git clone [<options>] [--] <repo> [<dir>]"),
50 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
51 static int option_local = -1, option_no_hardlinks, option_shared;
52 static int option_no_tags;
53 static int option_shallow_submodules;
54 static int option_reject_shallow = -1; /* unspecified */
55 static int config_reject_shallow = -1; /* unspecified */
57 static char *option_template, *option_depth, *option_since;
58 static char *option_origin = NULL;
59 static char *remote_name = NULL;
60 static char *option_branch = NULL;
61 static struct string_list option_not = STRING_LIST_INIT_NODUP;
62 static const char *real_git_dir;
63 static char *option_upload_pack = "git-upload-pack";
64 static int option_verbosity;
65 static int option_progress = -1;
66 static int option_sparse_checkout;
67 static enum transport_family family;
68 static struct string_list option_config = STRING_LIST_INIT_NODUP;
69 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
70 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
71 static int option_dissociate;
72 static int max_jobs = -1;
73 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
74 static struct list_objects_filter_options filter_options;
75 static struct string_list server_options = STRING_LIST_INIT_NODUP;
76 static int option_remote_submodules;
78 static int recurse_submodules_cb(const struct option *opt,
79 const char *arg, int unset)
82 string_list_clear((struct string_list *)opt->value, 0);
84 string_list_append((struct string_list *)opt->value, arg);
86 string_list_append((struct string_list *)opt->value,
87 (const char *)opt->defval);
92 static struct option builtin_clone_options[] = {
93 OPT__VERBOSITY(&option_verbosity),
94 OPT_BOOL(0, "progress", &option_progress,
95 N_("force progress reporting")),
96 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
97 N_("don't clone shallow repository")),
98 OPT_BOOL('n', "no-checkout", &option_no_checkout,
99 N_("don't create a checkout")),
100 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
101 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
102 N_("create a bare repository")),
103 OPT_BOOL(0, "mirror", &option_mirror,
104 N_("create a mirror repository (implies bare)")),
105 OPT_BOOL('l', "local", &option_local,
106 N_("to clone from a local repository")),
107 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
108 N_("don't use local hardlinks, always copy")),
109 OPT_BOOL('s', "shared", &option_shared,
110 N_("setup as shared repository")),
111 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
112 N_("pathspec"), N_("initialize submodules in the clone"),
113 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
114 OPT_ALIAS(0, "recursive", "recurse-submodules"),
115 OPT_INTEGER('j', "jobs", &max_jobs,
116 N_("number of submodules cloned in parallel")),
117 OPT_STRING(0, "template", &option_template, N_("template-directory"),
118 N_("directory from which templates will be used")),
119 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
120 N_("reference repository")),
121 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
122 N_("repo"), N_("reference repository")),
123 OPT_BOOL(0, "dissociate", &option_dissociate,
124 N_("use --reference only while cloning")),
125 OPT_STRING('o', "origin", &option_origin, N_("name"),
126 N_("use <name> instead of 'origin' to track upstream")),
127 OPT_STRING('b', "branch", &option_branch, N_("branch"),
128 N_("checkout <branch> instead of the remote's HEAD")),
129 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
130 N_("path to git-upload-pack on the remote")),
131 OPT_STRING(0, "depth", &option_depth, N_("depth"),
132 N_("create a shallow clone of that depth")),
133 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
134 N_("create a shallow clone since a specific time")),
135 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
136 N_("deepen history of shallow clone, excluding rev")),
137 OPT_BOOL(0, "single-branch", &option_single_branch,
138 N_("clone only one branch, HEAD or --branch")),
139 OPT_BOOL(0, "no-tags", &option_no_tags,
140 N_("don't clone any tags, and make later fetches not to follow them")),
141 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
142 N_("any cloned submodules will be shallow")),
143 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
144 N_("separate git dir from working tree")),
145 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
146 N_("set config inside the new repository")),
147 OPT_STRING_LIST(0, "server-option", &server_options,
148 N_("server-specific"), N_("option to transmit")),
149 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
150 TRANSPORT_FAMILY_IPV4),
151 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
152 TRANSPORT_FAMILY_IPV6),
153 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
154 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
155 N_("any cloned submodules will use their remote-tracking branch")),
156 OPT_BOOL(0, "sparse", &option_sparse_checkout,
157 N_("initialize sparse-checkout file to include only files at root")),
161 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
163 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
164 static char *bundle_suffix[] = { ".bundle", "" };
165 size_t baselen = path->len;
169 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
170 strbuf_setlen(path, baselen);
171 strbuf_addstr(path, suffix[i]);
172 if (stat(path->buf, &st))
174 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
177 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
178 /* Is it a "gitfile"? */
181 int len, fd = open(path->buf, O_RDONLY);
184 len = read_in_full(fd, signature, 8);
186 if (len != 8 || strncmp(signature, "gitdir: ", 8))
188 dst = read_gitfile(path->buf);
196 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
197 strbuf_setlen(path, baselen);
198 strbuf_addstr(path, bundle_suffix[i]);
199 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
208 static char *get_repo_path(const char *repo, int *is_bundle)
210 struct strbuf path = STRBUF_INIT;
214 strbuf_addstr(&path, repo);
215 raw = get_repo_path_1(&path, is_bundle);
216 canon = raw ? absolute_pathdup(raw) : NULL;
217 strbuf_release(&path);
221 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
223 const char *end = repo + strlen(repo), *start, *ptr;
230 start = strstr(repo, "://");
237 * Skip authentication data. The stripping does happen
238 * greedily, such that we strip up to the last '@' inside
241 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
247 * Strip trailing spaces, slashes and /.git
249 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
251 if (end - start > 5 && is_dir_sep(end[-5]) &&
252 !strncmp(end - 4, ".git", 4)) {
254 while (start < end && is_dir_sep(end[-1]))
259 * Strip trailing port number if we've got only a
260 * hostname (that is, there is no dir separator but a
261 * colon). This check is required such that we do not
262 * strip URI's like '/foo/bar:2222.git', which should
263 * result in a dir '2222' being guessed due to backwards
266 if (memchr(start, '/', end - start) == NULL
267 && memchr(start, ':', end - start) != NULL) {
269 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
271 if (start < ptr && ptr[-1] == ':')
276 * Find last component. To remain backwards compatible we
277 * also regard colons as path separators, such that
278 * cloning a repository 'foo:bar.git' would result in a
279 * directory 'bar' being guessed.
282 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
287 * Strip .{bundle,git}.
290 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
292 if (!len || (len == 1 && *start == '/'))
293 die(_("No directory name could be guessed.\n"
294 "Please specify a directory on the command line"));
297 dir = xstrfmt("%.*s.git", (int)len, start);
299 dir = xstrndup(start, len);
301 * Replace sequences of 'control' characters and whitespace
302 * with one ascii space, remove leading and trailing spaces.
306 int prev_space = 1 /* strip leading whitespace */;
307 for (end = dir; *end; ++end) {
309 if ((unsigned char)ch < '\x20')
320 if (out > dir && prev_space)
326 static void strip_trailing_slashes(char *dir)
328 char *end = dir + strlen(dir);
330 while (dir < end - 1 && is_dir_sep(end[-1]))
335 static int add_one_reference(struct string_list_item *item, void *cb_data)
337 struct strbuf err = STRBUF_INIT;
338 int *required = cb_data;
339 char *ref_git = compute_alternate_path(item->string, &err);
346 _("info: Could not add alternate for '%s': %s\n"),
347 item->string, err.buf);
349 struct strbuf sb = STRBUF_INIT;
350 strbuf_addf(&sb, "%s/objects", ref_git);
351 add_to_alternates_file(sb.buf);
355 strbuf_release(&err);
360 static void setup_reference(void)
363 for_each_string_list(&option_required_reference,
364 add_one_reference, &required);
366 for_each_string_list(&option_optional_reference,
367 add_one_reference, &required);
370 static void copy_alternates(struct strbuf *src, const char *src_repo)
373 * Read from the source objects/info/alternates file
374 * and copy the entries to corresponding file in the
375 * destination repository with add_to_alternates_file().
376 * Both src and dst have "$path/objects/info/alternates".
378 * Instead of copying bit-for-bit from the original,
379 * we need to append to existing one so that the already
380 * created entry via "clone -s" is not lost, and also
381 * to turn entries with paths relative to the original
382 * absolute, so that they can be used in the new repository.
384 FILE *in = xfopen(src->buf, "r");
385 struct strbuf line = STRBUF_INIT;
387 while (strbuf_getline(&line, in) != EOF) {
389 if (!line.len || line.buf[0] == '#')
391 if (is_absolute_path(line.buf)) {
392 add_to_alternates_file(line.buf);
395 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
396 if (!normalize_path_copy(abs_path, abs_path))
397 add_to_alternates_file(abs_path);
399 warning("skipping invalid relative alternate: %s/%s",
403 strbuf_release(&line);
407 static void mkdir_if_missing(const char *pathname, mode_t mode)
411 if (!mkdir(pathname, mode))
415 die_errno(_("failed to create directory '%s'"), pathname);
416 else if (stat(pathname, &st))
417 die_errno(_("failed to stat '%s'"), pathname);
418 else if (!S_ISDIR(st.st_mode))
419 die(_("%s exists and is not a directory"), pathname);
422 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
423 const char *src_repo)
425 int src_len, dest_len;
426 struct dir_iterator *iter;
429 struct strbuf realpath = STRBUF_INIT;
431 mkdir_if_missing(dest->buf, 0777);
433 flags = DIR_ITERATOR_PEDANTIC | DIR_ITERATOR_FOLLOW_SYMLINKS;
434 iter = dir_iterator_begin(src->buf, flags);
437 die_errno(_("failed to start iterator over '%s'"), src->buf);
439 strbuf_addch(src, '/');
441 strbuf_addch(dest, '/');
442 dest_len = dest->len;
444 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
445 strbuf_setlen(src, src_len);
446 strbuf_addstr(src, iter->relative_path);
447 strbuf_setlen(dest, dest_len);
448 strbuf_addstr(dest, iter->relative_path);
450 if (S_ISDIR(iter->st.st_mode)) {
451 mkdir_if_missing(dest->buf, 0777);
455 /* Files that cannot be copied bit-for-bit... */
456 if (!fspathcmp(iter->relative_path, "info/alternates")) {
457 copy_alternates(src, src_repo);
461 if (unlink(dest->buf) && errno != ENOENT)
462 die_errno(_("failed to unlink '%s'"), dest->buf);
463 if (!option_no_hardlinks) {
464 strbuf_realpath(&realpath, src->buf, 1);
465 if (!link(realpath.buf, dest->buf))
467 if (option_local > 0)
468 die_errno(_("failed to create link '%s'"), dest->buf);
469 option_no_hardlinks = 1;
471 if (copy_file_with_time(dest->buf, src->buf, 0666))
472 die_errno(_("failed to copy file to '%s'"), dest->buf);
475 if (iter_status != ITER_DONE) {
476 strbuf_setlen(src, src_len);
477 die(_("failed to iterate over '%s'"), src->buf);
480 strbuf_release(&realpath);
483 static void clone_local(const char *src_repo, const char *dest_repo)
486 struct strbuf alt = STRBUF_INIT;
487 get_common_dir(&alt, src_repo);
488 strbuf_addstr(&alt, "/objects");
489 add_to_alternates_file(alt.buf);
490 strbuf_release(&alt);
492 struct strbuf src = STRBUF_INIT;
493 struct strbuf dest = STRBUF_INIT;
494 get_common_dir(&src, src_repo);
495 get_common_dir(&dest, dest_repo);
496 strbuf_addstr(&src, "/objects");
497 strbuf_addstr(&dest, "/objects");
498 copy_or_link_directory(&src, &dest, src_repo);
499 strbuf_release(&src);
500 strbuf_release(&dest);
503 if (0 <= option_verbosity)
504 fprintf(stderr, _("done.\n"));
507 static const char *junk_work_tree;
508 static int junk_work_tree_flags;
509 static const char *junk_git_dir;
510 static int junk_git_dir_flags;
515 } junk_mode = JUNK_LEAVE_NONE;
517 static const char junk_leave_repo_msg[] =
518 N_("Clone succeeded, but checkout failed.\n"
519 "You can inspect what was checked out with 'git status'\n"
520 "and retry with 'git restore --source=HEAD :/'\n");
522 static void remove_junk(void)
524 struct strbuf sb = STRBUF_INIT;
527 case JUNK_LEAVE_REPO:
528 warning("%s", _(junk_leave_repo_msg));
533 /* proceed to removal */
538 strbuf_addstr(&sb, junk_git_dir);
539 remove_dir_recursively(&sb, junk_git_dir_flags);
542 if (junk_work_tree) {
543 strbuf_addstr(&sb, junk_work_tree);
544 remove_dir_recursively(&sb, junk_work_tree_flags);
549 static void remove_junk_on_signal(int signo)
556 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
559 struct strbuf head = STRBUF_INIT;
560 strbuf_addstr(&head, "refs/heads/");
561 strbuf_addstr(&head, branch);
562 ref = find_ref_by_name(refs, head.buf);
563 strbuf_release(&head);
568 strbuf_addstr(&head, "refs/tags/");
569 strbuf_addstr(&head, branch);
570 ref = find_ref_by_name(refs, head.buf);
571 strbuf_release(&head);
576 static struct ref *wanted_peer_refs(const struct ref *refs,
577 struct refspec *refspec)
579 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
580 struct ref *local_refs = head;
581 struct ref **tail = head ? &head->next : &local_refs;
583 if (option_single_branch) {
584 struct ref *remote_head = NULL;
587 remote_head = guess_remote_head(head, refs, 0);
591 remote_head = copy_ref(find_remote_branch(refs, option_branch));
594 if (!remote_head && option_branch)
595 warning(_("Could not find remote branch %s to clone."),
599 for (i = 0; i < refspec->nr; i++)
600 get_fetch_map(remote_head, &refspec->items[i],
603 /* if --branch=tag, pull the requested tag explicitly */
604 get_fetch_map(remote_head, tag_refspec, &tail, 0);
608 for (i = 0; i < refspec->nr; i++)
609 get_fetch_map(refs, &refspec->items[i], &tail, 0);
612 if (!option_mirror && !option_single_branch && !option_no_tags)
613 get_fetch_map(refs, tag_refspec, &tail, 0);
618 static void write_remote_refs(const struct ref *local_refs)
622 struct ref_transaction *t;
623 struct strbuf err = STRBUF_INIT;
625 t = ref_transaction_begin(&err);
629 for (r = local_refs; r; r = r->next) {
632 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
637 if (initial_ref_transaction_commit(t, &err))
640 strbuf_release(&err);
641 ref_transaction_free(t);
644 static void write_followtags(const struct ref *refs, const char *msg)
646 const struct ref *ref;
647 for (ref = refs; ref; ref = ref->next) {
648 if (!starts_with(ref->name, "refs/tags/"))
650 if (ends_with(ref->name, "^{}"))
652 if (!has_object_file_with_flags(&ref->old_oid,
654 OBJECT_INFO_SKIP_FETCH_OBJECT))
656 update_ref(msg, ref->name, &ref->old_oid, NULL, 0,
657 UPDATE_REFS_DIE_ON_ERR);
661 static int iterate_ref_map(void *cb_data, struct object_id *oid)
663 struct ref **rm = cb_data;
664 struct ref *ref = *rm;
667 * Skip anything missing a peer_ref, which we are not
668 * actually going to write a ref for.
670 while (ref && !ref->peer_ref)
672 /* Returning -1 notes "end of list" to the caller. */
676 oidcpy(oid, &ref->old_oid);
681 static void update_remote_refs(const struct ref *refs,
682 const struct ref *mapped_refs,
683 const struct ref *remote_head_points_at,
684 const char *branch_top,
686 struct transport *transport,
687 int check_connectivity)
689 const struct ref *rm = mapped_refs;
691 if (check_connectivity) {
692 struct check_connected_options opt = CHECK_CONNECTED_INIT;
694 opt.transport = transport;
695 opt.progress = transport->progress;
697 if (check_connected(iterate_ref_map, &rm, &opt))
698 die(_("remote did not send all necessary objects"));
702 write_remote_refs(mapped_refs);
703 if (option_single_branch && !option_no_tags)
704 write_followtags(refs, msg);
707 if (remote_head_points_at && !option_bare) {
708 struct strbuf head_ref = STRBUF_INIT;
709 strbuf_addstr(&head_ref, branch_top);
710 strbuf_addstr(&head_ref, "HEAD");
711 if (create_symref(head_ref.buf,
712 remote_head_points_at->peer_ref->name,
714 die(_("unable to update %s"), head_ref.buf);
715 strbuf_release(&head_ref);
719 static void update_head(const struct ref *our, const struct ref *remote,
723 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
724 /* Local default branch link */
725 if (create_symref("HEAD", our->name, NULL) < 0)
726 die(_("unable to update HEAD"));
728 update_ref(msg, "HEAD", &our->old_oid, NULL, 0,
729 UPDATE_REFS_DIE_ON_ERR);
730 install_branch_config(0, head, remote_name, our->name);
733 struct commit *c = lookup_commit_reference(the_repository,
735 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
736 update_ref(msg, "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
737 UPDATE_REFS_DIE_ON_ERR);
740 * We know remote HEAD points to a non-branch, or
741 * HEAD points to a branch but we don't know which one.
742 * Detach HEAD in all these cases.
744 update_ref(msg, "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
745 UPDATE_REFS_DIE_ON_ERR);
749 static int git_sparse_checkout_init(const char *repo)
751 struct strvec argv = STRVEC_INIT;
753 strvec_pushl(&argv, "-C", repo, "sparse-checkout", "init", NULL);
756 * We must apply the setting in the current process
757 * for the later checkout to use the sparse-checkout file.
759 core_apply_sparse_checkout = 1;
761 if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
762 error(_("failed to initialize sparse-checkout"));
770 static int checkout(int submodule_progress)
772 struct object_id oid;
774 struct lock_file lock_file = LOCK_INIT;
775 struct unpack_trees_options opts;
779 struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
781 if (option_no_checkout)
784 head = resolve_refdup("HEAD", RESOLVE_REF_READING, &oid, NULL);
786 warning(_("remote HEAD refers to nonexistent ref, "
787 "unable to checkout.\n"));
790 if (!strcmp(head, "HEAD")) {
791 if (advice_detached_head)
792 detach_advice(oid_to_hex(&oid));
795 if (!starts_with(head, "refs/heads/"))
796 die(_("HEAD not found below refs/heads!"));
799 /* We need to be in the new work tree for the checkout */
802 hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
804 memset(&opts, 0, sizeof opts);
808 opts.fn = oneway_merge;
809 opts.verbose_update = (option_verbosity >= 0);
810 opts.src_index = &the_index;
811 opts.dst_index = &the_index;
812 init_checkout_metadata(&opts.meta, head, &oid, NULL);
814 tree = parse_tree_indirect(&oid);
816 init_tree_desc(&t, tree->buffer, tree->size);
817 if (unpack_trees(1, &t, &opts) < 0)
818 die(_("unable to checkout working tree"));
822 if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
823 die(_("unable to write new index file"));
825 strvec_pushl(&hook_opt.args, oid_to_hex(null_oid()), oid_to_hex(&oid), "1", NULL);
826 err |= run_hooks("post-checkout", &hook_opt);
827 run_hooks_opt_clear(&hook_opt);
829 if (!err && (option_recurse_submodules.nr > 0)) {
830 struct strvec args = STRVEC_INIT;
831 strvec_pushl(&args, "submodule", "update", "--require-init", "--recursive", NULL);
833 if (option_shallow_submodules == 1)
834 strvec_push(&args, "--depth=1");
837 strvec_pushf(&args, "--jobs=%d", max_jobs);
839 if (submodule_progress)
840 strvec_push(&args, "--progress");
842 if (option_verbosity < 0)
843 strvec_push(&args, "--quiet");
845 if (option_remote_submodules) {
846 strvec_push(&args, "--remote");
847 strvec_push(&args, "--no-fetch");
850 if (option_single_branch >= 0)
851 strvec_push(&args, option_single_branch ?
853 "--no-single-branch");
855 err = run_command_v_opt(args.v, RUN_GIT_CMD);
862 static int git_clone_config(const char *k, const char *v, void *cb)
864 if (!strcmp(k, "clone.defaultremotename")) {
866 remote_name = xstrdup(v);
868 if (!strcmp(k, "clone.rejectshallow"))
869 config_reject_shallow = git_config_bool(k, v);
871 return git_default_config(k, v, cb);
874 static int write_one_config(const char *key, const char *value, void *data)
877 * give git_clone_config a chance to write config values back to the
878 * environment, since git_config_set_multivar_gently only deals with
881 int apply_failed = git_clone_config(key, value, data);
885 return git_config_set_multivar_gently(key,
886 value ? value : "true",
887 CONFIG_REGEX_NONE, 0);
890 static void write_config(struct string_list *config)
894 for (i = 0; i < config->nr; i++) {
895 if (git_config_parse_parameter(config->items[i].string,
896 write_one_config, NULL) < 0)
897 die(_("unable to write parameters to config file"));
901 static void write_refspec_config(const char *src_ref_prefix,
902 const struct ref *our_head_points_at,
903 const struct ref *remote_head_points_at,
904 struct strbuf *branch_top)
906 struct strbuf key = STRBUF_INIT;
907 struct strbuf value = STRBUF_INIT;
909 if (option_mirror || !option_bare) {
910 if (option_single_branch && !option_mirror) {
912 if (starts_with(our_head_points_at->name, "refs/tags/"))
913 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
914 our_head_points_at->name);
916 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
917 branch_top->buf, option_branch);
918 } else if (remote_head_points_at) {
919 const char *head = remote_head_points_at->name;
920 if (!skip_prefix(head, "refs/heads/", &head))
921 BUG("remote HEAD points at non-head?");
923 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
924 branch_top->buf, head);
927 * otherwise, the next "git fetch" will
928 * simply fetch from HEAD without updating
929 * any remote-tracking branch, which is what
933 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
935 /* Configure the remote */
937 strbuf_addf(&key, "remote.%s.fetch", remote_name);
938 git_config_set_multivar(key.buf, value.buf, "^$", 0);
942 strbuf_addf(&key, "remote.%s.mirror", remote_name);
943 git_config_set(key.buf, "true");
949 strbuf_release(&key);
950 strbuf_release(&value);
953 static void dissociate_from_references(void)
955 static const char* argv[] = { "repack", "-a", "-d", NULL };
956 char *alternates = git_pathdup("objects/info/alternates");
958 if (!access(alternates, F_OK)) {
959 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
960 die(_("cannot repack to clean up"));
961 if (unlink(alternates) && errno != ENOENT)
962 die_errno(_("cannot unlink temporary alternates file"));
967 static int path_exists(const char *path)
970 return !stat(path, &sb);
973 int cmd_clone(int argc, const char **argv, const char *prefix)
975 int is_bundle = 0, is_local;
976 int reject_shallow = 0;
977 const char *repo_name, *repo, *work_tree, *git_dir;
978 char *path = NULL, *dir, *display_repo = NULL;
979 int dest_exists, real_dest_exists = 0;
980 const struct ref *refs, *remote_head;
981 struct ref *remote_head_points_at = NULL;
982 const struct ref *our_head_points_at;
983 struct ref *mapped_refs;
984 const struct ref *ref;
985 struct strbuf key = STRBUF_INIT;
986 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
987 struct transport *transport = NULL;
988 const char *src_ref_prefix = "refs/heads/";
989 struct remote *remote;
990 int err = 0, complete_refs_before_fetch = 1;
991 int submodule_progress;
993 struct transport_ls_refs_options transport_ls_refs_options =
994 TRANSPORT_LS_REFS_OPTIONS_INIT;
996 packet_trace_identity("clone");
998 git_config(git_clone_config, NULL);
1000 argc = parse_options(argc, argv, prefix, builtin_clone_options,
1001 builtin_clone_usage, 0);
1004 usage_msg_opt(_("Too many arguments."),
1005 builtin_clone_usage, builtin_clone_options);
1008 usage_msg_opt(_("You must specify a repository to clone."),
1009 builtin_clone_usage, builtin_clone_options);
1011 if (option_depth || option_since || option_not.nr)
1013 if (option_single_branch == -1)
1014 option_single_branch = deepen ? 1 : 0;
1021 die(_("--bare and --origin %s options are incompatible."),
1024 die(_("--bare and --separate-git-dir are incompatible."));
1025 option_no_checkout = 1;
1028 repo_name = argv[0];
1030 path = get_repo_path(repo_name, &is_bundle);
1032 FREE_AND_NULL(path);
1033 repo = absolute_pathdup(repo_name);
1034 } else if (strchr(repo_name, ':')) {
1036 display_repo = transport_anonymize_url(repo);
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);
1045 dir = xstrdup(argv[1]);
1047 dir = guess_dir_name(repo_name, is_bundle, option_bare);
1048 strip_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);
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);
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);
1079 git_dir = mkpathdup("%s/.git", dir);
1082 atexit(remove_junk);
1083 sigchain_push_common(remove_junk_on_signal);
1086 if (safe_create_leading_directories_const(work_tree) < 0)
1087 die_errno(_("could not create leading directories of '%s'"),
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'"),
1094 junk_work_tree = work_tree;
1095 set_git_work_tree(work_tree);
1099 if (real_dest_exists)
1100 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1101 junk_git_dir = real_git_dir;
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) {
1112 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
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;
1121 /* remove duplicates */
1122 string_list_sort(&option_recurse_submodules);
1123 string_list_remove_duplicates(&option_recurse_submodules, 0);
1126 * NEEDSWORK: In a multi-working-tree world, this needs to be
1127 * set in the per-worktree config.
1129 for_each_string_list_item(item, &option_recurse_submodules) {
1130 strbuf_addf(&sb, "submodule.active=%s",
1132 string_list_append(&option_config,
1133 strbuf_detach(&sb, NULL));
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");
1153 init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN, NULL,
1157 git_dir = real_git_dir;
1160 * additional config can be injected with -c, make sure it's included
1161 * after init_db, which clears the entire config environment.
1163 write_config(&option_config);
1166 * re-read config after init_db and write_config to pick up any config
1167 * injected by --template and --config, respectively.
1169 git_config(git_clone_config, NULL);
1172 * If option_reject_shallow is specified from CLI option,
1173 * ignore config_reject_shallow from git_clone_config.
1175 if (config_reject_shallow != -1)
1176 reject_shallow = config_reject_shallow;
1177 if (option_reject_shallow != -1)
1178 reject_shallow = option_reject_shallow;
1181 * apply the remote name provided by --origin only after this second
1182 * call to git_config, to ensure it overrides all config-based values.
1184 if (option_origin != NULL)
1185 remote_name = xstrdup(option_origin);
1187 if (remote_name == NULL)
1188 remote_name = xstrdup("origin");
1190 if (!valid_remote_name(remote_name))
1191 die(_("'%s' is not a valid remote name"), remote_name);
1195 src_ref_prefix = "refs/";
1196 strbuf_addstr(&branch_top, src_ref_prefix);
1198 git_config_set("core.bare", "true");
1200 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1203 strbuf_addf(&key, "remote.%s.url", remote_name);
1204 git_config_set(key.buf, repo);
1207 if (option_no_tags) {
1208 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1209 git_config_set(key.buf, "--no-tags");
1213 if (option_required_reference.nr || option_optional_reference.nr)
1216 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1219 remote = remote_get(remote_name);
1221 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1224 transport = transport_get(remote, remote->url[0]);
1225 transport_set_verbosity(transport, option_verbosity, option_progress);
1226 transport->family = family;
1228 path = get_repo_path(remote->url[0], &is_bundle);
1229 is_local = option_local != 0 && path && !is_bundle;
1232 warning(_("--depth is ignored in local clones; use file:// instead."));
1234 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1236 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1237 if (filter_options.choice)
1238 warning(_("--filter is ignored in local clones; use file:// instead."));
1239 if (!access(mkpath("%s/shallow", path), F_OK)) {
1241 die(_("source repository is shallow, reject to clone."));
1242 if (option_local > 0)
1243 warning(_("source repository is shallow, ignoring --local"));
1247 if (option_local > 0 && !is_local)
1248 warning(_("--local is ignored"));
1249 transport->cloning = 1;
1251 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1254 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1256 transport_set_option(transport, TRANS_OPT_DEPTH,
1259 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1262 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1263 (const char *)&option_not);
1264 if (option_single_branch)
1265 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1267 if (option_upload_pack)
1268 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1269 option_upload_pack);
1271 if (server_options.nr)
1272 transport->server_options = &server_options;
1274 if (filter_options.choice) {
1276 expand_list_objects_filter_spec(&filter_options);
1277 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1279 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1282 if (transport->smart_options && !deepen && !filter_options.choice)
1283 transport->smart_options->check_self_contained_and_connected = 1;
1286 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1287 refspec_ref_prefixes(&remote->fetch,
1288 &transport_ls_refs_options.ref_prefixes);
1290 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1292 if (!option_no_tags)
1293 strvec_push(&transport_ls_refs_options.ref_prefixes,
1296 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1299 int hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1302 * Now that we know what algorithm the remote side is using,
1303 * let's set ours to the same thing.
1305 initialize_repository_version(hash_algo, 1);
1306 repo_set_hash_algo(the_repository, hash_algo);
1308 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1310 * transport_get_remote_refs() may return refs with null sha-1
1311 * in mapped_refs (see struct transport->get_refs_list
1312 * comment). In that case we need fetch it early because
1313 * remote_head code below relies on it.
1315 * for normal clones, transport_get_remote_refs() should
1316 * return reliable ref set, we can delay cloning until after
1317 * remote HEAD check.
1319 for (ref = refs; ref; ref = ref->next)
1320 if (is_null_oid(&ref->old_oid)) {
1321 complete_refs_before_fetch = 0;
1325 if (!is_local && !complete_refs_before_fetch) {
1326 if (transport_fetch_refs(transport, mapped_refs))
1327 die(_("remote transport reported error"));
1330 remote_head = find_ref_by_name(refs, "HEAD");
1331 remote_head_points_at =
1332 guess_remote_head(remote_head, mapped_refs, 0);
1334 if (option_branch) {
1335 our_head_points_at =
1336 find_remote_branch(mapped_refs, option_branch);
1338 if (!our_head_points_at)
1339 die(_("Remote branch %s not found in upstream %s"),
1340 option_branch, remote_name);
1343 our_head_points_at = remote_head_points_at;
1347 die(_("Remote branch %s not found in upstream %s"),
1348 option_branch, remote_name);
1350 warning(_("You appear to have cloned an empty repository."));
1352 our_head_points_at = NULL;
1353 remote_head_points_at = NULL;
1355 option_no_checkout = 1;
1360 if (transport_ls_refs_options.unborn_head_target &&
1361 skip_prefix(transport_ls_refs_options.unborn_head_target,
1362 "refs/heads/", &branch)) {
1363 ref = transport_ls_refs_options.unborn_head_target;
1364 transport_ls_refs_options.unborn_head_target = NULL;
1365 create_symref("HEAD", ref, reflog_msg.buf);
1367 branch = git_default_branch_name(0);
1368 ref = xstrfmt("refs/heads/%s", branch);
1371 install_branch_config(0, branch, remote_name, ref);
1376 write_refspec_config(src_ref_prefix, our_head_points_at,
1377 remote_head_points_at, &branch_top);
1379 if (filter_options.choice)
1380 partial_clone_register(remote_name, &filter_options);
1383 clone_local(path, git_dir);
1384 else if (refs && complete_refs_before_fetch) {
1385 if (transport_fetch_refs(transport, mapped_refs))
1386 die(_("remote transport reported error"));
1389 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1390 branch_top.buf, reflog_msg.buf, transport,
1393 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1396 * We want to show progress for recursive submodule clones iff
1397 * we did so for the main clone. But only the transport knows
1398 * the final decision for this flag, so we need to rescue the value
1399 * before we free the transport.
1401 submodule_progress = transport->progress;
1403 transport_unlock_pack(transport);
1404 transport_disconnect(transport);
1406 if (option_dissociate) {
1407 close_object_store(the_repository->objects);
1408 dissociate_from_references();
1411 junk_mode = JUNK_LEAVE_REPO;
1412 err = checkout(submodule_progress);
1415 strbuf_release(&reflog_msg);
1416 strbuf_release(&branch_top);
1417 strbuf_release(&key);
1418 free_refs(mapped_refs);
1419 free_refs(remote_head_points_at);
1423 junk_mode = JUNK_LEAVE_ALL;
1425 strvec_clear(&transport_ls_refs_options.ref_prefixes);
1426 free(transport_ls_refs_options.unborn_head_target);