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.
12 #include "parse-options.h"
13 #include "fetch-pack.h"
16 #include "tree-walk.h"
17 #include "unpack-trees.h"
18 #include "transport.h"
21 #include "pack-refs.h"
25 #include "run-command.h"
29 * - respect DB_ENVIRONMENT for .git/objects.
31 * Implementation notes:
32 * - dropping use-separate-remote and no-separate-remote compatibility
35 static const char * const builtin_clone_usage[] = {
36 "git clone [options] [--] <repo> [<dir>]",
40 static int option_no_checkout, option_bare, option_mirror;
41 static int option_local, option_no_hardlinks, option_shared, option_recursive;
42 static char *option_template, *option_depth;
43 static char *option_origin = NULL;
44 static char *option_branch = NULL;
45 static const char *real_git_dir;
46 static char *option_upload_pack = "git-upload-pack";
47 static int option_verbosity;
48 static int option_progress;
49 static struct string_list option_reference;
51 static int opt_parse_reference(const struct option *opt, const char *arg, int unset)
53 struct string_list *option_reference = opt->value;
56 string_list_append(option_reference, arg);
60 static struct option builtin_clone_options[] = {
61 OPT__VERBOSITY(&option_verbosity),
62 OPT_BOOLEAN(0, "progress", &option_progress,
63 "force progress reporting"),
64 OPT_BOOLEAN('n', "no-checkout", &option_no_checkout,
65 "don't create a checkout"),
66 OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"),
67 { OPTION_BOOLEAN, 0, "naked", &option_bare, NULL,
68 "create a bare repository",
69 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
70 OPT_BOOLEAN(0, "mirror", &option_mirror,
71 "create a mirror repository (implies bare)"),
72 OPT_BOOLEAN('l', "local", &option_local,
73 "to clone from a local repository"),
74 OPT_BOOLEAN(0, "no-hardlinks", &option_no_hardlinks,
75 "don't use local hardlinks, always copy"),
76 OPT_BOOLEAN('s', "shared", &option_shared,
77 "setup as shared repository"),
78 OPT_BOOLEAN(0, "recursive", &option_recursive,
79 "initialize submodules in the clone"),
80 OPT_BOOLEAN(0, "recurse-submodules", &option_recursive,
81 "initialize submodules in the clone"),
82 OPT_STRING(0, "template", &option_template, "template-directory",
83 "directory from which templates will be used"),
84 OPT_CALLBACK(0 , "reference", &option_reference, "repo",
85 "reference repository", &opt_parse_reference),
86 OPT_STRING('o', "origin", &option_origin, "branch",
87 "use <branch> instead of 'origin' to track upstream"),
88 OPT_STRING('b', "branch", &option_branch, "branch",
89 "checkout <branch> instead of the remote's HEAD"),
90 OPT_STRING('u', "upload-pack", &option_upload_pack, "path",
91 "path to git-upload-pack on the remote"),
92 OPT_STRING(0, "depth", &option_depth, "depth",
93 "create a shallow clone of that depth"),
94 OPT_STRING(0, "separate-git-dir", &real_git_dir, "gitdir",
95 "separate git dir from working tree"),
100 static const char *argv_submodule[] = {
101 "submodule", "update", "--init", "--recursive", NULL
104 static char *get_repo_path(const char *repo, int *is_bundle)
106 static char *suffix[] = { "/.git", ".git", "" };
107 static char *bundle_suffix[] = { ".bundle", "" };
111 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
113 path = mkpath("%s%s", repo, suffix[i]);
116 if (S_ISDIR(st.st_mode)) {
118 return xstrdup(absolute_path(path));
119 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
120 /* Is it a "gitfile"? */
122 int len, fd = open(path, O_RDONLY);
125 len = read_in_full(fd, signature, 8);
127 if (len != 8 || strncmp(signature, "gitdir: ", 8))
129 path = read_gitfile(path);
132 return xstrdup(absolute_path(path));
137 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
139 path = mkpath("%s%s", repo, bundle_suffix[i]);
140 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
142 return xstrdup(absolute_path(path));
149 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
151 const char *end = repo + strlen(repo), *start;
155 * Strip trailing spaces, slashes and /.git
157 while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
159 if (end - repo > 5 && is_dir_sep(end[-5]) &&
160 !strncmp(end - 4, ".git", 4)) {
162 while (repo < end && is_dir_sep(end[-1]))
167 * Find last component, but be prepared that repo could have
168 * the form "remote.example.com:foo.git", i.e. no slash
169 * in the directory part.
172 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
176 * Strip .{bundle,git}.
179 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
182 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
187 struct strbuf result = STRBUF_INIT;
188 strbuf_addf(&result, "%.*s.git", (int)(end - start), start);
189 dir = strbuf_detach(&result, NULL);
191 dir = xstrndup(start, end - start);
193 * Replace sequences of 'control' characters and whitespace
194 * with one ascii space, remove leading and trailing spaces.
198 int prev_space = 1 /* strip leading whitespace */;
199 for (end = dir; *end; ++end) {
201 if ((unsigned char)ch < '\x20')
212 if (out > dir && prev_space)
218 static void strip_trailing_slashes(char *dir)
220 char *end = dir + strlen(dir);
222 while (dir < end - 1 && is_dir_sep(end[-1]))
227 static int add_one_reference(struct string_list_item *item, void *cb_data)
230 struct strbuf alternate = STRBUF_INIT;
231 struct remote *remote;
232 struct transport *transport;
233 const struct ref *extra;
235 /* Beware: real_path() and mkpath() return static buffer */
236 ref_git = xstrdup(real_path(item->string));
237 if (is_directory(mkpath("%s/.git/objects", ref_git))) {
238 char *ref_git_git = xstrdup(mkpath("%s/.git", ref_git));
240 ref_git = ref_git_git;
241 } else if (!is_directory(mkpath("%s/objects", ref_git)))
242 die(_("reference repository '%s' is not a local directory."),
245 strbuf_addf(&alternate, "%s/objects", ref_git);
246 add_to_alternates_file(alternate.buf);
247 strbuf_release(&alternate);
249 remote = remote_get(ref_git);
250 transport = transport_get(remote, ref_git);
251 for (extra = transport_get_remote_refs(transport); extra;
253 add_extra_ref(extra->name, extra->old_sha1, 0);
255 transport_disconnect(transport);
260 static void setup_reference(void)
262 for_each_string_list(&option_reference, add_one_reference, NULL);
265 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
266 const char *src_repo)
269 * Read from the source objects/info/alternates file
270 * and copy the entries to corresponding file in the
271 * destination repository with add_to_alternates_file().
272 * Both src and dst have "$path/objects/info/alternates".
274 * Instead of copying bit-for-bit from the original,
275 * we need to append to existing one so that the already
276 * created entry via "clone -s" is not lost, and also
277 * to turn entries with paths relative to the original
278 * absolute, so that they can be used in the new repository.
280 FILE *in = fopen(src->buf, "r");
281 struct strbuf line = STRBUF_INIT;
283 while (strbuf_getline(&line, in, '\n') != EOF) {
284 char *abs_path, abs_buf[PATH_MAX];
285 if (!line.len || line.buf[0] == '#')
287 if (is_absolute_path(line.buf)) {
288 add_to_alternates_file(line.buf);
291 abs_path = mkpath("%s/objects/%s", src_repo, line.buf);
292 normalize_path_copy(abs_buf, abs_path);
293 add_to_alternates_file(abs_buf);
295 strbuf_release(&line);
299 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
300 const char *src_repo, int src_baselen)
304 int src_len, dest_len;
307 dir = opendir(src->buf);
309 die_errno(_("failed to open '%s'"), src->buf);
311 if (mkdir(dest->buf, 0777)) {
313 die_errno(_("failed to create directory '%s'"), dest->buf);
314 else if (stat(dest->buf, &buf))
315 die_errno(_("failed to stat '%s'"), dest->buf);
316 else if (!S_ISDIR(buf.st_mode))
317 die(_("%s exists and is not a directory"), dest->buf);
320 strbuf_addch(src, '/');
322 strbuf_addch(dest, '/');
323 dest_len = dest->len;
325 while ((de = readdir(dir)) != NULL) {
326 strbuf_setlen(src, src_len);
327 strbuf_addstr(src, de->d_name);
328 strbuf_setlen(dest, dest_len);
329 strbuf_addstr(dest, de->d_name);
330 if (stat(src->buf, &buf)) {
331 warning (_("failed to stat %s\n"), src->buf);
334 if (S_ISDIR(buf.st_mode)) {
335 if (de->d_name[0] != '.')
336 copy_or_link_directory(src, dest,
337 src_repo, src_baselen);
341 /* Files that cannot be copied bit-for-bit... */
342 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
343 copy_alternates(src, dest, src_repo);
347 if (unlink(dest->buf) && errno != ENOENT)
348 die_errno(_("failed to unlink '%s'"), dest->buf);
349 if (!option_no_hardlinks) {
350 if (!link(src->buf, dest->buf))
353 die_errno(_("failed to create link '%s'"), dest->buf);
354 option_no_hardlinks = 1;
356 if (copy_file_with_time(dest->buf, src->buf, 0666))
357 die_errno(_("failed to copy file to '%s'"), dest->buf);
362 static const struct ref *clone_local(const char *src_repo,
363 const char *dest_repo)
365 const struct ref *ret;
366 struct remote *remote;
367 struct transport *transport;
370 struct strbuf alt = STRBUF_INIT;
371 strbuf_addf(&alt, "%s/objects", src_repo);
372 add_to_alternates_file(alt.buf);
373 strbuf_release(&alt);
375 struct strbuf src = STRBUF_INIT;
376 struct strbuf dest = STRBUF_INIT;
377 strbuf_addf(&src, "%s/objects", src_repo);
378 strbuf_addf(&dest, "%s/objects", dest_repo);
379 copy_or_link_directory(&src, &dest, src_repo, src.len);
380 strbuf_release(&src);
381 strbuf_release(&dest);
384 remote = remote_get(src_repo);
385 transport = transport_get(remote, src_repo);
386 ret = transport_get_remote_refs(transport);
387 transport_disconnect(transport);
388 if (0 <= option_verbosity)
389 printf(_("done.\n"));
393 static const char *junk_work_tree;
394 static const char *junk_git_dir;
395 static pid_t junk_pid;
397 static void remove_junk(void)
399 struct strbuf sb = STRBUF_INIT;
400 if (getpid() != junk_pid)
403 strbuf_addstr(&sb, junk_git_dir);
404 remove_dir_recursively(&sb, 0);
407 if (junk_work_tree) {
408 strbuf_addstr(&sb, junk_work_tree);
409 remove_dir_recursively(&sb, 0);
414 static void remove_junk_on_signal(int signo)
421 static struct ref *wanted_peer_refs(const struct ref *refs,
422 struct refspec *refspec)
424 struct ref *local_refs = NULL;
425 struct ref **tail = &local_refs;
427 get_fetch_map(refs, refspec, &tail, 0);
429 get_fetch_map(refs, tag_refspec, &tail, 0);
434 static void write_remote_refs(const struct ref *local_refs)
438 for (r = local_refs; r; r = r->next)
439 add_extra_ref(r->peer_ref->name, r->old_sha1, 0);
441 pack_refs(PACK_REFS_ALL);
445 int cmd_clone(int argc, const char **argv, const char *prefix)
447 int is_bundle = 0, is_local;
449 const char *repo_name, *repo, *work_tree, *git_dir;
452 const struct ref *refs, *remote_head;
453 const struct ref *remote_head_points_at;
454 const struct ref *our_head_points_at;
455 struct ref *mapped_refs;
456 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
457 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
458 struct transport *transport = NULL;
459 char *src_ref_prefix = "refs/heads/";
462 struct refspec *refspec;
463 const char *fetch_pattern;
467 packet_trace_identity("clone");
468 argc = parse_options(argc, argv, prefix, builtin_clone_options,
469 builtin_clone_usage, 0);
472 usage_msg_opt(_("Too many arguments."),
473 builtin_clone_usage, builtin_clone_options);
476 usage_msg_opt(_("You must specify a repository to clone."),
477 builtin_clone_usage, builtin_clone_options);
484 die(_("--bare and --origin %s options are incompatible."),
486 option_no_checkout = 1;
490 option_origin = "origin";
494 path = get_repo_path(repo_name, &is_bundle);
496 repo = xstrdup(absolute_path(repo_name));
497 else if (!strchr(repo_name, ':'))
498 die(_("repository '%s' does not exist"), repo_name);
501 is_local = path && !is_bundle;
502 if (is_local && option_depth)
503 warning(_("--depth is ignored in local clones; use file:// instead."));
506 dir = xstrdup(argv[1]);
508 dir = guess_dir_name(repo_name, is_bundle, option_bare);
509 strip_trailing_slashes(dir);
511 dest_exists = !stat(dir, &buf);
512 if (dest_exists && !is_empty_dir(dir))
513 die(_("destination path '%s' already exists and is not "
514 "an empty directory."), dir);
516 strbuf_addf(&reflog_msg, "clone: from %s", repo);
521 work_tree = getenv("GIT_WORK_TREE");
522 if (work_tree && !stat(work_tree, &buf))
523 die(_("working tree '%s' already exists."), work_tree);
526 if (option_bare || work_tree)
527 git_dir = xstrdup(dir);
530 git_dir = xstrdup(mkpath("%s/.git", dir));
534 junk_work_tree = work_tree;
535 if (safe_create_leading_directories_const(work_tree) < 0)
536 die_errno(_("could not create leading directories of '%s'"),
538 if (!dest_exists && mkdir(work_tree, 0755))
539 die_errno(_("could not create work tree dir '%s'."),
541 set_git_work_tree(work_tree);
543 junk_git_dir = git_dir;
545 sigchain_push_common(remove_junk_on_signal);
547 setenv(CONFIG_ENVIRONMENT, mkpath("%s/config", git_dir), 1);
549 if (safe_create_leading_directories_const(git_dir) < 0)
550 die(_("could not create leading directories of '%s'"), git_dir);
552 set_git_dir_init(git_dir, real_git_dir, 0);
554 git_dir = real_git_dir;
556 if (0 <= option_verbosity) {
558 printf(_("Cloning into bare repository %s...\n"), dir);
560 printf(_("Cloning into %s...\n"), dir);
562 init_db(option_template, INIT_DB_QUIET);
565 * At this point, the config exists, so we do not need the
566 * environment variable. We actually need to unset it, too, to
567 * re-enable parsing of the global configs.
569 unsetenv(CONFIG_ENVIRONMENT);
571 git_config(git_default_config, NULL);
575 src_ref_prefix = "refs/";
576 strbuf_addstr(&branch_top, src_ref_prefix);
578 git_config_set("core.bare", "true");
580 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
583 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
585 if (option_mirror || !option_bare) {
586 /* Configure the remote */
587 strbuf_addf(&key, "remote.%s.fetch", option_origin);
588 git_config_set_multivar(key.buf, value.buf, "^$", 0);
592 strbuf_addf(&key, "remote.%s.mirror", option_origin);
593 git_config_set(key.buf, "true");
598 strbuf_addf(&key, "remote.%s.url", option_origin);
599 git_config_set(key.buf, repo);
602 if (option_reference.nr)
605 fetch_pattern = value.buf;
606 refspec = parse_fetch_refspec(1, &fetch_pattern);
608 strbuf_reset(&value);
611 refs = clone_local(path, git_dir);
612 mapped_refs = wanted_peer_refs(refs, refspec);
614 struct remote *remote = remote_get(option_origin);
615 transport = transport_get(remote, remote->url[0]);
617 if (!transport->get_refs_list || !transport->fetch)
618 die(_("Don't know how to clone %s"), transport->url);
620 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
623 transport_set_option(transport, TRANS_OPT_DEPTH,
626 transport_set_verbosity(transport, option_verbosity, option_progress);
628 if (option_upload_pack)
629 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
632 refs = transport_get_remote_refs(transport);
634 mapped_refs = wanted_peer_refs(refs, refspec);
635 transport_fetch_refs(transport, mapped_refs);
642 write_remote_refs(mapped_refs);
644 remote_head = find_ref_by_name(refs, "HEAD");
645 remote_head_points_at =
646 guess_remote_head(remote_head, mapped_refs, 0);
649 struct strbuf head = STRBUF_INIT;
650 strbuf_addstr(&head, src_ref_prefix);
651 strbuf_addstr(&head, option_branch);
653 find_ref_by_name(mapped_refs, head.buf);
654 strbuf_release(&head);
656 if (!our_head_points_at) {
657 warning(_("Remote branch %s not found in "
658 "upstream %s, using HEAD instead"),
659 option_branch, option_origin);
660 our_head_points_at = remote_head_points_at;
664 our_head_points_at = remote_head_points_at;
667 warning(_("You appear to have cloned an empty repository."));
668 our_head_points_at = NULL;
669 remote_head_points_at = NULL;
671 option_no_checkout = 1;
673 install_branch_config(0, "master", option_origin,
674 "refs/heads/master");
677 if (remote_head_points_at && !option_bare) {
678 struct strbuf head_ref = STRBUF_INIT;
679 strbuf_addstr(&head_ref, branch_top.buf);
680 strbuf_addstr(&head_ref, "HEAD");
681 create_symref(head_ref.buf,
682 remote_head_points_at->peer_ref->name,
686 if (our_head_points_at) {
687 /* Local default branch link */
688 create_symref("HEAD", our_head_points_at->name, NULL);
690 const char *head = skip_prefix(our_head_points_at->name,
692 update_ref(reflog_msg.buf, "HEAD",
693 our_head_points_at->old_sha1,
694 NULL, 0, DIE_ON_ERR);
695 install_branch_config(0, head, option_origin,
696 our_head_points_at->name);
698 } else if (remote_head) {
699 /* Source had detached HEAD pointing somewhere. */
701 update_ref(reflog_msg.buf, "HEAD",
702 remote_head->old_sha1,
703 NULL, REF_NODEREF, DIE_ON_ERR);
704 our_head_points_at = remote_head;
707 /* Nothing to checkout out */
708 if (!option_no_checkout)
709 warning(_("remote HEAD refers to nonexistent ref, "
710 "unable to checkout.\n"));
711 option_no_checkout = 1;
715 transport_unlock_pack(transport);
716 transport_disconnect(transport);
719 if (!option_no_checkout) {
720 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
721 struct unpack_trees_options opts;
726 /* We need to be in the new work tree for the checkout */
729 fd = hold_locked_index(lock_file, 1);
731 memset(&opts, 0, sizeof opts);
734 opts.fn = oneway_merge;
735 opts.verbose_update = (option_verbosity > 0);
736 opts.src_index = &the_index;
737 opts.dst_index = &the_index;
739 tree = parse_tree_indirect(our_head_points_at->old_sha1);
741 init_tree_desc(&t, tree->buffer, tree->size);
742 unpack_trees(1, &t, &opts);
744 if (write_cache(fd, active_cache, active_nr) ||
745 commit_locked_index(lock_file))
746 die(_("unable to write new index file"));
748 err |= run_hook(NULL, "post-checkout", sha1_to_hex(null_sha1),
749 sha1_to_hex(our_head_points_at->old_sha1), "1",
752 if (!err && option_recursive)
753 err = run_command_v_opt(argv_submodule, RUN_GIT_CMD);
756 strbuf_release(&reflog_msg);
757 strbuf_release(&branch_top);
758 strbuf_release(&key);
759 strbuf_release(&value);