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.
13 #include "parse-options.h"
14 #include "fetch-pack.h"
17 #include "tree-walk.h"
18 #include "unpack-trees.h"
19 #include "transport.h"
25 #include "run-command.h"
26 #include "connected.h"
30 * - respect DB_ENVIRONMENT for .git/objects.
32 * Implementation notes:
33 * - dropping use-separate-remote and no-separate-remote compatibility
36 static const char * const builtin_clone_usage[] = {
37 N_("git clone [<options>] [--] <repo> [<dir>]"),
41 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
42 static int option_local = -1, option_no_hardlinks, option_shared;
43 static int option_no_tags;
44 static int option_shallow_submodules;
46 static char *option_template, *option_depth, *option_since;
47 static char *option_origin = NULL;
48 static char *option_branch = NULL;
49 static struct string_list option_not = STRING_LIST_INIT_NODUP;
50 static const char *real_git_dir;
51 static char *option_upload_pack = "git-upload-pack";
52 static int option_verbosity;
53 static int option_progress = -1;
54 static enum transport_family family;
55 static struct string_list option_config = STRING_LIST_INIT_NODUP;
56 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
57 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
58 static int option_dissociate;
59 static int max_jobs = -1;
60 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
62 static int recurse_submodules_cb(const struct option *opt,
63 const char *arg, int unset)
66 string_list_clear((struct string_list *)opt->value, 0);
68 string_list_append((struct string_list *)opt->value, arg);
70 string_list_append((struct string_list *)opt->value,
71 (const char *)opt->defval);
76 static struct option builtin_clone_options[] = {
77 OPT__VERBOSITY(&option_verbosity),
78 OPT_BOOL(0, "progress", &option_progress,
79 N_("force progress reporting")),
80 OPT_BOOL('n', "no-checkout", &option_no_checkout,
81 N_("don't create a checkout")),
82 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
83 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
84 N_("create a bare repository")),
85 OPT_BOOL(0, "mirror", &option_mirror,
86 N_("create a mirror repository (implies bare)")),
87 OPT_BOOL('l', "local", &option_local,
88 N_("to clone from a local repository")),
89 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
90 N_("don't use local hardlinks, always copy")),
91 OPT_BOOL('s', "shared", &option_shared,
92 N_("setup as shared repository")),
93 { OPTION_CALLBACK, 0, "recursive", &option_recurse_submodules,
94 N_("pathspec"), N_("initialize submodules in the clone"),
95 PARSE_OPT_OPTARG | PARSE_OPT_HIDDEN, recurse_submodules_cb,
97 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
98 N_("pathspec"), N_("initialize submodules in the clone"),
99 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
100 OPT_INTEGER('j', "jobs", &max_jobs,
101 N_("number of submodules cloned in parallel")),
102 OPT_STRING(0, "template", &option_template, N_("template-directory"),
103 N_("directory from which templates will be used")),
104 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
105 N_("reference repository")),
106 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
107 N_("repo"), N_("reference repository")),
108 OPT_BOOL(0, "dissociate", &option_dissociate,
109 N_("use --reference only while cloning")),
110 OPT_STRING('o', "origin", &option_origin, N_("name"),
111 N_("use <name> instead of 'origin' to track upstream")),
112 OPT_STRING('b', "branch", &option_branch, N_("branch"),
113 N_("checkout <branch> instead of the remote's HEAD")),
114 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
115 N_("path to git-upload-pack on the remote")),
116 OPT_STRING(0, "depth", &option_depth, N_("depth"),
117 N_("create a shallow clone of that depth")),
118 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
119 N_("create a shallow clone since a specific time")),
120 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
121 N_("deepen history of shallow clone, excluding rev")),
122 OPT_BOOL(0, "single-branch", &option_single_branch,
123 N_("clone only one branch, HEAD or --branch")),
124 OPT_BOOL(0, "no-tags", &option_no_tags,
125 N_("don't clone any tags, and make later fetches not to follow them")),
126 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
127 N_("any cloned submodules will be shallow")),
128 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
129 N_("separate git dir from working tree")),
130 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
131 N_("set config inside the new repository")),
132 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
133 TRANSPORT_FAMILY_IPV4),
134 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
135 TRANSPORT_FAMILY_IPV6),
139 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
141 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
142 static char *bundle_suffix[] = { ".bundle", "" };
143 size_t baselen = path->len;
147 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
148 strbuf_setlen(path, baselen);
149 strbuf_addstr(path, suffix[i]);
150 if (stat(path->buf, &st))
152 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
155 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
156 /* Is it a "gitfile"? */
159 int len, fd = open(path->buf, O_RDONLY);
162 len = read_in_full(fd, signature, 8);
164 if (len != 8 || strncmp(signature, "gitdir: ", 8))
166 dst = read_gitfile(path->buf);
174 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
175 strbuf_setlen(path, baselen);
176 strbuf_addstr(path, bundle_suffix[i]);
177 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
186 static char *get_repo_path(const char *repo, int *is_bundle)
188 struct strbuf path = STRBUF_INIT;
192 strbuf_addstr(&path, repo);
193 raw = get_repo_path_1(&path, is_bundle);
194 canon = raw ? absolute_pathdup(raw) : NULL;
195 strbuf_release(&path);
199 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
201 const char *end = repo + strlen(repo), *start, *ptr;
208 start = strstr(repo, "://");
215 * Skip authentication data. The stripping does happen
216 * greedily, such that we strip up to the last '@' inside
219 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
225 * Strip trailing spaces, slashes and /.git
227 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
229 if (end - start > 5 && is_dir_sep(end[-5]) &&
230 !strncmp(end - 4, ".git", 4)) {
232 while (start < end && is_dir_sep(end[-1]))
237 * Strip trailing port number if we've got only a
238 * hostname (that is, there is no dir separator but a
239 * colon). This check is required such that we do not
240 * strip URI's like '/foo/bar:2222.git', which should
241 * result in a dir '2222' being guessed due to backwards
244 if (memchr(start, '/', end - start) == NULL
245 && memchr(start, ':', end - start) != NULL) {
247 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
249 if (start < ptr && ptr[-1] == ':')
254 * Find last component. To remain backwards compatible we
255 * also regard colons as path separators, such that
256 * cloning a repository 'foo:bar.git' would result in a
257 * directory 'bar' being guessed.
260 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
265 * Strip .{bundle,git}.
268 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
270 if (!len || (len == 1 && *start == '/'))
271 die(_("No directory name could be guessed.\n"
272 "Please specify a directory on the command line"));
275 dir = xstrfmt("%.*s.git", (int)len, start);
277 dir = xstrndup(start, len);
279 * Replace sequences of 'control' characters and whitespace
280 * with one ascii space, remove leading and trailing spaces.
284 int prev_space = 1 /* strip leading whitespace */;
285 for (end = dir; *end; ++end) {
287 if ((unsigned char)ch < '\x20')
298 if (out > dir && prev_space)
304 static void strip_trailing_slashes(char *dir)
306 char *end = dir + strlen(dir);
308 while (dir < end - 1 && is_dir_sep(end[-1]))
313 static int add_one_reference(struct string_list_item *item, void *cb_data)
315 struct strbuf err = STRBUF_INIT;
316 int *required = cb_data;
317 char *ref_git = compute_alternate_path(item->string, &err);
324 _("info: Could not add alternate for '%s': %s\n"),
325 item->string, err.buf);
327 struct strbuf sb = STRBUF_INIT;
328 strbuf_addf(&sb, "%s/objects", ref_git);
329 add_to_alternates_file(sb.buf);
333 strbuf_release(&err);
338 static void setup_reference(void)
341 for_each_string_list(&option_required_reference,
342 add_one_reference, &required);
344 for_each_string_list(&option_optional_reference,
345 add_one_reference, &required);
348 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
349 const char *src_repo)
352 * Read from the source objects/info/alternates file
353 * and copy the entries to corresponding file in the
354 * destination repository with add_to_alternates_file().
355 * Both src and dst have "$path/objects/info/alternates".
357 * Instead of copying bit-for-bit from the original,
358 * we need to append to existing one so that the already
359 * created entry via "clone -s" is not lost, and also
360 * to turn entries with paths relative to the original
361 * absolute, so that they can be used in the new repository.
363 FILE *in = xfopen(src->buf, "r");
364 struct strbuf line = STRBUF_INIT;
366 while (strbuf_getline(&line, in) != EOF) {
368 if (!line.len || line.buf[0] == '#')
370 if (is_absolute_path(line.buf)) {
371 add_to_alternates_file(line.buf);
374 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
375 if (!normalize_path_copy(abs_path, abs_path))
376 add_to_alternates_file(abs_path);
378 warning("skipping invalid relative alternate: %s/%s",
382 strbuf_release(&line);
386 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
387 const char *src_repo, int src_baselen)
391 int src_len, dest_len;
394 dir = opendir(src->buf);
396 die_errno(_("failed to open '%s'"), src->buf);
398 if (mkdir(dest->buf, 0777)) {
400 die_errno(_("failed to create directory '%s'"), dest->buf);
401 else if (stat(dest->buf, &buf))
402 die_errno(_("failed to stat '%s'"), dest->buf);
403 else if (!S_ISDIR(buf.st_mode))
404 die(_("%s exists and is not a directory"), dest->buf);
407 strbuf_addch(src, '/');
409 strbuf_addch(dest, '/');
410 dest_len = dest->len;
412 while ((de = readdir(dir)) != NULL) {
413 strbuf_setlen(src, src_len);
414 strbuf_addstr(src, de->d_name);
415 strbuf_setlen(dest, dest_len);
416 strbuf_addstr(dest, de->d_name);
417 if (stat(src->buf, &buf)) {
418 warning (_("failed to stat %s\n"), src->buf);
421 if (S_ISDIR(buf.st_mode)) {
422 if (de->d_name[0] != '.')
423 copy_or_link_directory(src, dest,
424 src_repo, src_baselen);
428 /* Files that cannot be copied bit-for-bit... */
429 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
430 copy_alternates(src, dest, src_repo);
434 if (unlink(dest->buf) && errno != ENOENT)
435 die_errno(_("failed to unlink '%s'"), dest->buf);
436 if (!option_no_hardlinks) {
437 if (!link(src->buf, dest->buf))
439 if (option_local > 0)
440 die_errno(_("failed to create link '%s'"), dest->buf);
441 option_no_hardlinks = 1;
443 if (copy_file_with_time(dest->buf, src->buf, 0666))
444 die_errno(_("failed to copy file to '%s'"), dest->buf);
449 static void clone_local(const char *src_repo, const char *dest_repo)
452 struct strbuf alt = STRBUF_INIT;
453 strbuf_addf(&alt, "%s/objects", src_repo);
454 add_to_alternates_file(alt.buf);
455 strbuf_release(&alt);
457 struct strbuf src = STRBUF_INIT;
458 struct strbuf dest = STRBUF_INIT;
459 get_common_dir(&src, src_repo);
460 get_common_dir(&dest, dest_repo);
461 strbuf_addstr(&src, "/objects");
462 strbuf_addstr(&dest, "/objects");
463 copy_or_link_directory(&src, &dest, src_repo, src.len);
464 strbuf_release(&src);
465 strbuf_release(&dest);
468 if (0 <= option_verbosity)
469 fprintf(stderr, _("done.\n"));
472 static const char *junk_work_tree;
473 static const char *junk_git_dir;
478 } junk_mode = JUNK_LEAVE_NONE;
480 static const char junk_leave_repo_msg[] =
481 N_("Clone succeeded, but checkout failed.\n"
482 "You can inspect what was checked out with 'git status'\n"
483 "and retry the checkout with 'git checkout -f HEAD'\n");
485 static void remove_junk(void)
487 struct strbuf sb = STRBUF_INIT;
490 case JUNK_LEAVE_REPO:
491 warning("%s", _(junk_leave_repo_msg));
496 /* proceed to removal */
501 strbuf_addstr(&sb, junk_git_dir);
502 remove_dir_recursively(&sb, 0);
505 if (junk_work_tree) {
506 strbuf_addstr(&sb, junk_work_tree);
507 remove_dir_recursively(&sb, 0);
512 static void remove_junk_on_signal(int signo)
519 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
522 struct strbuf head = STRBUF_INIT;
523 strbuf_addstr(&head, "refs/heads/");
524 strbuf_addstr(&head, branch);
525 ref = find_ref_by_name(refs, head.buf);
526 strbuf_release(&head);
531 strbuf_addstr(&head, "refs/tags/");
532 strbuf_addstr(&head, branch);
533 ref = find_ref_by_name(refs, head.buf);
534 strbuf_release(&head);
539 static struct ref *wanted_peer_refs(const struct ref *refs,
540 struct refspec *refspec)
542 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
543 struct ref *local_refs = head;
544 struct ref **tail = head ? &head->next : &local_refs;
546 if (option_single_branch) {
547 struct ref *remote_head = NULL;
550 remote_head = guess_remote_head(head, refs, 0);
554 remote_head = copy_ref(find_remote_branch(refs, option_branch));
557 if (!remote_head && option_branch)
558 warning(_("Could not find remote branch %s to clone."),
561 get_fetch_map(remote_head, refspec, &tail, 0);
563 /* if --branch=tag, pull the requested tag explicitly */
564 get_fetch_map(remote_head, tag_refspec, &tail, 0);
567 get_fetch_map(refs, refspec, &tail, 0);
569 if (!option_mirror && !option_single_branch && !option_no_tags)
570 get_fetch_map(refs, tag_refspec, &tail, 0);
575 static void write_remote_refs(const struct ref *local_refs)
579 struct ref_transaction *t;
580 struct strbuf err = STRBUF_INIT;
582 t = ref_transaction_begin(&err);
586 for (r = local_refs; r; r = r->next) {
589 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
594 if (initial_ref_transaction_commit(t, &err))
597 strbuf_release(&err);
598 ref_transaction_free(t);
601 static void write_followtags(const struct ref *refs, const char *msg)
603 const struct ref *ref;
604 for (ref = refs; ref; ref = ref->next) {
605 if (!starts_with(ref->name, "refs/tags/"))
607 if (ends_with(ref->name, "^{}"))
609 if (!has_object_file(&ref->old_oid))
611 update_ref(msg, ref->name, ref->old_oid.hash,
612 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
616 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
618 struct ref **rm = cb_data;
619 struct ref *ref = *rm;
622 * Skip anything missing a peer_ref, which we are not
623 * actually going to write a ref for.
625 while (ref && !ref->peer_ref)
627 /* Returning -1 notes "end of list" to the caller. */
631 hashcpy(sha1, ref->old_oid.hash);
636 static void update_remote_refs(const struct ref *refs,
637 const struct ref *mapped_refs,
638 const struct ref *remote_head_points_at,
639 const char *branch_top,
641 struct transport *transport,
642 int check_connectivity)
644 const struct ref *rm = mapped_refs;
646 if (check_connectivity) {
647 struct check_connected_options opt = CHECK_CONNECTED_INIT;
649 opt.transport = transport;
650 opt.progress = transport->progress;
652 if (check_connected(iterate_ref_map, &rm, &opt))
653 die(_("remote did not send all necessary objects"));
657 write_remote_refs(mapped_refs);
658 if (option_single_branch && !option_no_tags)
659 write_followtags(refs, msg);
662 if (remote_head_points_at && !option_bare) {
663 struct strbuf head_ref = STRBUF_INIT;
664 strbuf_addstr(&head_ref, branch_top);
665 strbuf_addstr(&head_ref, "HEAD");
666 if (create_symref(head_ref.buf,
667 remote_head_points_at->peer_ref->name,
669 die(_("unable to update %s"), head_ref.buf);
670 strbuf_release(&head_ref);
674 static void update_head(const struct ref *our, const struct ref *remote,
678 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
679 /* Local default branch link */
680 if (create_symref("HEAD", our->name, NULL) < 0)
681 die(_("unable to update HEAD"));
683 update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
684 UPDATE_REFS_DIE_ON_ERR);
685 install_branch_config(0, head, option_origin, our->name);
688 struct commit *c = lookup_commit_reference(&our->old_oid);
689 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
690 update_ref(msg, "HEAD", c->object.oid.hash,
691 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
694 * We know remote HEAD points to a non-branch, or
695 * HEAD points to a branch but we don't know which one.
696 * Detach HEAD in all these cases.
698 update_ref(msg, "HEAD", remote->old_oid.hash,
699 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
703 static int checkout(int submodule_progress)
705 struct object_id oid;
707 struct lock_file *lock_file;
708 struct unpack_trees_options opts;
713 if (option_no_checkout)
716 head = resolve_refdup("HEAD", RESOLVE_REF_READING, oid.hash, NULL);
718 warning(_("remote HEAD refers to nonexistent ref, "
719 "unable to checkout.\n"));
722 if (!strcmp(head, "HEAD")) {
723 if (advice_detached_head)
724 detach_advice(oid_to_hex(&oid));
726 if (!starts_with(head, "refs/heads/"))
727 die(_("HEAD not found below refs/heads!"));
731 /* We need to be in the new work tree for the checkout */
734 lock_file = xcalloc(1, sizeof(struct lock_file));
735 hold_locked_index(lock_file, LOCK_DIE_ON_ERROR);
737 memset(&opts, 0, sizeof opts);
740 opts.fn = oneway_merge;
741 opts.verbose_update = (option_verbosity >= 0);
742 opts.src_index = &the_index;
743 opts.dst_index = &the_index;
745 tree = parse_tree_indirect(&oid);
747 init_tree_desc(&t, tree->buffer, tree->size);
748 if (unpack_trees(1, &t, &opts) < 0)
749 die(_("unable to checkout working tree"));
751 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
752 die(_("unable to write new index file"));
754 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
755 oid_to_hex(&oid), "1", NULL);
757 if (!err && (option_recurse_submodules.nr > 0)) {
758 struct argv_array args = ARGV_ARRAY_INIT;
759 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
761 if (option_shallow_submodules == 1)
762 argv_array_push(&args, "--depth=1");
765 argv_array_pushf(&args, "--jobs=%d", max_jobs);
767 if (submodule_progress)
768 argv_array_push(&args, "--progress");
770 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
771 argv_array_clear(&args);
777 static int write_one_config(const char *key, const char *value, void *data)
779 return git_config_set_multivar_gently(key,
780 value ? value : "true",
781 CONFIG_REGEX_NONE, 0);
784 static void write_config(struct string_list *config)
788 for (i = 0; i < config->nr; i++) {
789 if (git_config_parse_parameter(config->items[i].string,
790 write_one_config, NULL) < 0)
791 die(_("unable to write parameters to config file"));
795 static void write_refspec_config(const char *src_ref_prefix,
796 const struct ref *our_head_points_at,
797 const struct ref *remote_head_points_at,
798 struct strbuf *branch_top)
800 struct strbuf key = STRBUF_INIT;
801 struct strbuf value = STRBUF_INIT;
803 if (option_mirror || !option_bare) {
804 if (option_single_branch && !option_mirror) {
806 if (starts_with(our_head_points_at->name, "refs/tags/"))
807 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
808 our_head_points_at->name);
810 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
811 branch_top->buf, option_branch);
812 } else if (remote_head_points_at) {
813 const char *head = remote_head_points_at->name;
814 if (!skip_prefix(head, "refs/heads/", &head))
815 die("BUG: remote HEAD points at non-head?");
817 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
818 branch_top->buf, head);
821 * otherwise, the next "git fetch" will
822 * simply fetch from HEAD without updating
823 * any remote-tracking branch, which is what
827 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
829 /* Configure the remote */
831 strbuf_addf(&key, "remote.%s.fetch", option_origin);
832 git_config_set_multivar(key.buf, value.buf, "^$", 0);
836 strbuf_addf(&key, "remote.%s.mirror", option_origin);
837 git_config_set(key.buf, "true");
843 strbuf_release(&key);
844 strbuf_release(&value);
847 static void dissociate_from_references(void)
849 static const char* argv[] = { "repack", "-a", "-d", NULL };
850 char *alternates = git_pathdup("objects/info/alternates");
852 if (!access(alternates, F_OK)) {
853 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
854 die(_("cannot repack to clean up"));
855 if (unlink(alternates) && errno != ENOENT)
856 die_errno(_("cannot unlink temporary alternates file"));
861 int cmd_clone(int argc, const char **argv, const char *prefix)
863 int is_bundle = 0, is_local;
865 const char *repo_name, *repo, *work_tree, *git_dir;
868 const struct ref *refs, *remote_head;
869 const struct ref *remote_head_points_at;
870 const struct ref *our_head_points_at;
871 struct ref *mapped_refs;
872 const struct ref *ref;
873 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
874 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
875 struct transport *transport = NULL;
876 const char *src_ref_prefix = "refs/heads/";
877 struct remote *remote;
878 int err = 0, complete_refs_before_fetch = 1;
879 int submodule_progress;
881 struct refspec *refspec;
882 const char *fetch_pattern;
884 packet_trace_identity("clone");
885 argc = parse_options(argc, argv, prefix, builtin_clone_options,
886 builtin_clone_usage, 0);
889 usage_msg_opt(_("Too many arguments."),
890 builtin_clone_usage, builtin_clone_options);
893 usage_msg_opt(_("You must specify a repository to clone."),
894 builtin_clone_usage, builtin_clone_options);
896 if (option_depth || option_since || option_not.nr)
898 if (option_single_branch == -1)
899 option_single_branch = deepen ? 1 : 0;
906 die(_("--bare and --origin %s options are incompatible."),
909 die(_("--bare and --separate-git-dir are incompatible."));
910 option_no_checkout = 1;
914 option_origin = "origin";
918 path = get_repo_path(repo_name, &is_bundle);
920 repo = absolute_pathdup(repo_name);
921 else if (!strchr(repo_name, ':'))
922 die(_("repository '%s' does not exist"), repo_name);
926 /* no need to be strict, transport_set_option() will validate it again */
927 if (option_depth && atoi(option_depth) < 1)
928 die(_("depth %s is not a positive number"), option_depth);
931 dir = xstrdup(argv[1]);
933 dir = guess_dir_name(repo_name, is_bundle, option_bare);
934 strip_trailing_slashes(dir);
936 dest_exists = !stat(dir, &buf);
937 if (dest_exists && !is_empty_dir(dir))
938 die(_("destination path '%s' already exists and is not "
939 "an empty directory."), dir);
941 strbuf_addf(&reflog_msg, "clone: from %s", repo);
946 work_tree = getenv("GIT_WORK_TREE");
947 if (work_tree && !stat(work_tree, &buf))
948 die(_("working tree '%s' already exists."), work_tree);
951 if (option_bare || work_tree)
952 git_dir = xstrdup(dir);
955 git_dir = mkpathdup("%s/.git", dir);
959 sigchain_push_common(remove_junk_on_signal);
962 if (safe_create_leading_directories_const(work_tree) < 0)
963 die_errno(_("could not create leading directories of '%s'"),
965 if (!dest_exists && mkdir(work_tree, 0777))
966 die_errno(_("could not create work tree dir '%s'"),
968 junk_work_tree = work_tree;
969 set_git_work_tree(work_tree);
972 junk_git_dir = real_git_dir ? real_git_dir : git_dir;
973 if (safe_create_leading_directories_const(git_dir) < 0)
974 die(_("could not create leading directories of '%s'"), git_dir);
976 if (0 <= option_verbosity) {
978 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
980 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
983 if (option_recurse_submodules.nr > 0) {
984 struct string_list_item *item;
985 struct strbuf sb = STRBUF_INIT;
987 /* remove duplicates */
988 string_list_sort(&option_recurse_submodules);
989 string_list_remove_duplicates(&option_recurse_submodules, 0);
992 * NEEDSWORK: In a multi-working-tree world, this needs to be
993 * set in the per-worktree config.
995 for_each_string_list_item(item, &option_recurse_submodules) {
996 strbuf_addf(&sb, "submodule.active=%s",
998 string_list_append(&option_config,
999 strbuf_detach(&sb, NULL));
1002 if (option_required_reference.nr &&
1003 option_optional_reference.nr)
1004 die(_("clone --recursive is not compatible with "
1005 "both --reference and --reference-if-able"));
1006 else if (option_required_reference.nr) {
1007 string_list_append(&option_config,
1008 "submodule.alternateLocation=superproject");
1009 string_list_append(&option_config,
1010 "submodule.alternateErrorStrategy=die");
1011 } else if (option_optional_reference.nr) {
1012 string_list_append(&option_config,
1013 "submodule.alternateLocation=superproject");
1014 string_list_append(&option_config,
1015 "submodule.alternateErrorStrategy=info");
1019 init_db(git_dir, real_git_dir, option_template, INIT_DB_QUIET);
1022 git_dir = real_git_dir;
1024 write_config(&option_config);
1026 git_config(git_default_config, NULL);
1030 src_ref_prefix = "refs/";
1031 strbuf_addstr(&branch_top, src_ref_prefix);
1033 git_config_set("core.bare", "true");
1035 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
1038 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
1039 strbuf_addf(&key, "remote.%s.url", option_origin);
1040 git_config_set(key.buf, repo);
1043 if (option_no_tags) {
1044 strbuf_addf(&key, "remote.%s.tagOpt", option_origin);
1045 git_config_set(key.buf, "--no-tags");
1049 if (option_required_reference.nr || option_optional_reference.nr)
1052 fetch_pattern = value.buf;
1053 refspec = parse_fetch_refspec(1, &fetch_pattern);
1055 strbuf_reset(&value);
1057 remote = remote_get(option_origin);
1058 transport = transport_get(remote, remote->url[0]);
1059 transport_set_verbosity(transport, option_verbosity, option_progress);
1060 transport->family = family;
1062 path = get_repo_path(remote->url[0], &is_bundle);
1063 is_local = option_local != 0 && path && !is_bundle;
1066 warning(_("--depth is ignored in local clones; use file:// instead."));
1068 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1070 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1071 if (!access(mkpath("%s/shallow", path), F_OK)) {
1072 if (option_local > 0)
1073 warning(_("source repository is shallow, ignoring --local"));
1077 if (option_local > 0 && !is_local)
1078 warning(_("--local is ignored"));
1079 transport->cloning = 1;
1081 if (!transport->get_refs_list || (!is_local && !transport->fetch))
1082 die(_("Don't know how to clone %s"), transport->url);
1084 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1087 transport_set_option(transport, TRANS_OPT_DEPTH,
1090 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1093 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1094 (const char *)&option_not);
1095 if (option_single_branch)
1096 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1098 if (option_upload_pack)
1099 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1100 option_upload_pack);
1102 if (transport->smart_options && !deepen)
1103 transport->smart_options->check_self_contained_and_connected = 1;
1105 refs = transport_get_remote_refs(transport);
1108 mapped_refs = wanted_peer_refs(refs, refspec);
1110 * transport_get_remote_refs() may return refs with null sha-1
1111 * in mapped_refs (see struct transport->get_refs_list
1112 * comment). In that case we need fetch it early because
1113 * remote_head code below relies on it.
1115 * for normal clones, transport_get_remote_refs() should
1116 * return reliable ref set, we can delay cloning until after
1117 * remote HEAD check.
1119 for (ref = refs; ref; ref = ref->next)
1120 if (is_null_oid(&ref->old_oid)) {
1121 complete_refs_before_fetch = 0;
1125 if (!is_local && !complete_refs_before_fetch)
1126 transport_fetch_refs(transport, mapped_refs);
1128 remote_head = find_ref_by_name(refs, "HEAD");
1129 remote_head_points_at =
1130 guess_remote_head(remote_head, mapped_refs, 0);
1132 if (option_branch) {
1133 our_head_points_at =
1134 find_remote_branch(mapped_refs, option_branch);
1136 if (!our_head_points_at)
1137 die(_("Remote branch %s not found in upstream %s"),
1138 option_branch, option_origin);
1141 our_head_points_at = remote_head_points_at;
1145 die(_("Remote branch %s not found in upstream %s"),
1146 option_branch, option_origin);
1148 warning(_("You appear to have cloned an empty repository."));
1150 our_head_points_at = NULL;
1151 remote_head_points_at = NULL;
1153 option_no_checkout = 1;
1155 install_branch_config(0, "master", option_origin,
1156 "refs/heads/master");
1159 write_refspec_config(src_ref_prefix, our_head_points_at,
1160 remote_head_points_at, &branch_top);
1163 clone_local(path, git_dir);
1164 else if (refs && complete_refs_before_fetch)
1165 transport_fetch_refs(transport, mapped_refs);
1167 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1168 branch_top.buf, reflog_msg.buf, transport, !is_local);
1170 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1173 * We want to show progress for recursive submodule clones iff
1174 * we did so for the main clone. But only the transport knows
1175 * the final decision for this flag, so we need to rescue the value
1176 * before we free the transport.
1178 submodule_progress = transport->progress;
1180 transport_unlock_pack(transport);
1181 transport_disconnect(transport);
1183 if (option_dissociate) {
1185 dissociate_from_references();
1188 junk_mode = JUNK_LEAVE_REPO;
1189 err = checkout(submodule_progress);
1191 strbuf_release(&reflog_msg);
1192 strbuf_release(&branch_top);
1193 strbuf_release(&key);
1194 strbuf_release(&value);
1195 junk_mode = JUNK_LEAVE_ALL;