Merge branch 'jh/filter-empty-contents'
[git.git] / builtin / clone.c
blobb878252bc2e64bbe95adbae5554618f017c9ac85
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 "lockfile.h"
13 #include "parse-options.h"
14 #include "fetch-pack.h"
15 #include "refs.h"
16 #include "tree.h"
17 #include "tree-walk.h"
18 #include "unpack-trees.h"
19 #include "transport.h"
20 #include "strbuf.h"
21 #include "dir.h"
22 #include "sigchain.h"
23 #include "branch.h"
24 #include "remote.h"
25 #include "run-command.h"
26 #include "connected.h"
29 * Overall FIXMEs:
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>]"),
38 NULL
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, option_recursive;
43 static char *option_template, *option_depth;
44 static char *option_origin = NULL;
45 static char *option_branch = NULL;
46 static const char *real_git_dir;
47 static char *option_upload_pack = "git-upload-pack";
48 static int option_verbosity;
49 static int option_progress = -1;
50 static struct string_list option_config;
51 static struct string_list option_reference;
52 static int option_dissociate;
54 static int opt_parse_reference(const struct option *opt, const char *arg, int unset)
56 struct string_list *option_reference = opt->value;
57 if (!arg)
58 return -1;
59 string_list_append(option_reference, arg);
60 return 0;
63 static struct option builtin_clone_options[] = {
64 OPT__VERBOSITY(&option_verbosity),
65 OPT_BOOL(0, "progress", &option_progress,
66 N_("force progress reporting")),
67 OPT_BOOL('n', "no-checkout", &option_no_checkout,
68 N_("don't create a checkout")),
69 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
70 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
71 N_("create a bare repository")),
72 OPT_BOOL(0, "mirror", &option_mirror,
73 N_("create a mirror repository (implies bare)")),
74 OPT_BOOL('l', "local", &option_local,
75 N_("to clone from a local repository")),
76 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
77 N_("don't use local hardlinks, always copy")),
78 OPT_BOOL('s', "shared", &option_shared,
79 N_("setup as shared repository")),
80 OPT_BOOL(0, "recursive", &option_recursive,
81 N_("initialize submodules in the clone")),
82 OPT_BOOL(0, "recurse-submodules", &option_recursive,
83 N_("initialize submodules in the clone")),
84 OPT_STRING(0, "template", &option_template, N_("template-directory"),
85 N_("directory from which templates will be used")),
86 OPT_CALLBACK(0 , "reference", &option_reference, N_("repo"),
87 N_("reference repository"), &opt_parse_reference),
88 OPT_STRING('o', "origin", &option_origin, N_("name"),
89 N_("use <name> instead of 'origin' to track upstream")),
90 OPT_STRING('b', "branch", &option_branch, N_("branch"),
91 N_("checkout <branch> instead of the remote's HEAD")),
92 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
93 N_("path to git-upload-pack on the remote")),
94 OPT_STRING(0, "depth", &option_depth, N_("depth"),
95 N_("create a shallow clone of that depth")),
96 OPT_BOOL(0, "single-branch", &option_single_branch,
97 N_("clone only one branch, HEAD or --branch")),
98 OPT_BOOL(0, "dissociate", &option_dissociate,
99 N_("use --reference only while cloning")),
100 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
101 N_("separate git dir from working tree")),
102 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
103 N_("set config inside the new repository")),
104 OPT_END()
107 static const char *argv_submodule[] = {
108 "submodule", "update", "--init", "--recursive", NULL
111 static char *get_repo_path(const char *repo, int *is_bundle)
113 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
114 static char *bundle_suffix[] = { ".bundle", "" };
115 struct stat st;
116 int i;
118 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
119 const char *path;
120 path = mkpath("%s%s", repo, suffix[i]);
121 if (stat(path, &st))
122 continue;
123 if (S_ISDIR(st.st_mode) && is_git_directory(path)) {
124 *is_bundle = 0;
125 return xstrdup(absolute_path(path));
126 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
127 /* Is it a "gitfile"? */
128 char signature[8];
129 int len, fd = open(path, O_RDONLY);
130 if (fd < 0)
131 continue;
132 len = read_in_full(fd, signature, 8);
133 close(fd);
134 if (len != 8 || strncmp(signature, "gitdir: ", 8))
135 continue;
136 path = read_gitfile(path);
137 if (path) {
138 *is_bundle = 0;
139 return xstrdup(absolute_path(path));
144 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
145 const char *path;
146 path = mkpath("%s%s", repo, bundle_suffix[i]);
147 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
148 *is_bundle = 1;
149 return xstrdup(absolute_path(path));
153 return NULL;
156 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
158 const char *end = repo + strlen(repo), *start;
159 char *dir;
162 * Strip trailing spaces, slashes and /.git
164 while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
165 end--;
166 if (end - repo > 5 && is_dir_sep(end[-5]) &&
167 !strncmp(end - 4, ".git", 4)) {
168 end -= 5;
169 while (repo < end && is_dir_sep(end[-1]))
170 end--;
174 * Find last component, but be prepared that repo could have
175 * the form "remote.example.com:foo.git", i.e. no slash
176 * in the directory part.
178 start = end;
179 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
180 start--;
183 * Strip .{bundle,git}.
185 if (is_bundle) {
186 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
187 end -= 7;
188 } else {
189 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
190 end -= 4;
193 if (is_bare) {
194 struct strbuf result = STRBUF_INIT;
195 strbuf_addf(&result, "%.*s.git", (int)(end - start), start);
196 dir = strbuf_detach(&result, NULL);
197 } else
198 dir = xstrndup(start, end - start);
200 * Replace sequences of 'control' characters and whitespace
201 * with one ascii space, remove leading and trailing spaces.
203 if (*dir) {
204 char *out = dir;
205 int prev_space = 1 /* strip leading whitespace */;
206 for (end = dir; *end; ++end) {
207 char ch = *end;
208 if ((unsigned char)ch < '\x20')
209 ch = '\x20';
210 if (isspace(ch)) {
211 if (prev_space)
212 continue;
213 prev_space = 1;
214 } else
215 prev_space = 0;
216 *out++ = ch;
218 *out = '\0';
219 if (out > dir && prev_space)
220 out[-1] = '\0';
222 return dir;
225 static void strip_trailing_slashes(char *dir)
227 char *end = dir + strlen(dir);
229 while (dir < end - 1 && is_dir_sep(end[-1]))
230 end--;
231 *end = '\0';
234 static int add_one_reference(struct string_list_item *item, void *cb_data)
236 char *ref_git;
237 const char *repo;
238 struct strbuf alternate = STRBUF_INIT;
240 /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
241 ref_git = xstrdup(real_path(item->string));
243 repo = read_gitfile(ref_git);
244 if (!repo)
245 repo = read_gitfile(mkpath("%s/.git", ref_git));
246 if (repo) {
247 free(ref_git);
248 ref_git = xstrdup(repo);
251 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
252 char *ref_git_git = mkpathdup("%s/.git", ref_git);
253 free(ref_git);
254 ref_git = ref_git_git;
255 } else if (!is_directory(mkpath("%s/objects", ref_git)))
256 die(_("reference repository '%s' is not a local repository."),
257 item->string);
259 if (!access(mkpath("%s/shallow", ref_git), F_OK))
260 die(_("reference repository '%s' is shallow"), item->string);
262 if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
263 die(_("reference repository '%s' is grafted"), item->string);
265 strbuf_addf(&alternate, "%s/objects", ref_git);
266 add_to_alternates_file(alternate.buf);
267 strbuf_release(&alternate);
268 free(ref_git);
269 return 0;
272 static void setup_reference(void)
274 for_each_string_list(&option_reference, add_one_reference, NULL);
277 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
278 const char *src_repo)
281 * Read from the source objects/info/alternates file
282 * and copy the entries to corresponding file in the
283 * destination repository with add_to_alternates_file().
284 * Both src and dst have "$path/objects/info/alternates".
286 * Instead of copying bit-for-bit from the original,
287 * we need to append to existing one so that the already
288 * created entry via "clone -s" is not lost, and also
289 * to turn entries with paths relative to the original
290 * absolute, so that they can be used in the new repository.
292 FILE *in = fopen(src->buf, "r");
293 struct strbuf line = STRBUF_INIT;
295 while (strbuf_getline(&line, in, '\n') != EOF) {
296 char *abs_path;
297 if (!line.len || line.buf[0] == '#')
298 continue;
299 if (is_absolute_path(line.buf)) {
300 add_to_alternates_file(line.buf);
301 continue;
303 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
304 normalize_path_copy(abs_path, abs_path);
305 add_to_alternates_file(abs_path);
306 free(abs_path);
308 strbuf_release(&line);
309 fclose(in);
312 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
313 const char *src_repo, int src_baselen)
315 struct dirent *de;
316 struct stat buf;
317 int src_len, dest_len;
318 DIR *dir;
320 dir = opendir(src->buf);
321 if (!dir)
322 die_errno(_("failed to open '%s'"), src->buf);
324 if (mkdir(dest->buf, 0777)) {
325 if (errno != EEXIST)
326 die_errno(_("failed to create directory '%s'"), dest->buf);
327 else if (stat(dest->buf, &buf))
328 die_errno(_("failed to stat '%s'"), dest->buf);
329 else if (!S_ISDIR(buf.st_mode))
330 die(_("%s exists and is not a directory"), dest->buf);
333 strbuf_addch(src, '/');
334 src_len = src->len;
335 strbuf_addch(dest, '/');
336 dest_len = dest->len;
338 while ((de = readdir(dir)) != NULL) {
339 strbuf_setlen(src, src_len);
340 strbuf_addstr(src, de->d_name);
341 strbuf_setlen(dest, dest_len);
342 strbuf_addstr(dest, de->d_name);
343 if (stat(src->buf, &buf)) {
344 warning (_("failed to stat %s\n"), src->buf);
345 continue;
347 if (S_ISDIR(buf.st_mode)) {
348 if (de->d_name[0] != '.')
349 copy_or_link_directory(src, dest,
350 src_repo, src_baselen);
351 continue;
354 /* Files that cannot be copied bit-for-bit... */
355 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
356 copy_alternates(src, dest, src_repo);
357 continue;
360 if (unlink(dest->buf) && errno != ENOENT)
361 die_errno(_("failed to unlink '%s'"), dest->buf);
362 if (!option_no_hardlinks) {
363 if (!link(src->buf, dest->buf))
364 continue;
365 if (option_local > 0)
366 die_errno(_("failed to create link '%s'"), dest->buf);
367 option_no_hardlinks = 1;
369 if (copy_file_with_time(dest->buf, src->buf, 0666))
370 die_errno(_("failed to copy file to '%s'"), dest->buf);
372 closedir(dir);
375 static void clone_local(const char *src_repo, const char *dest_repo)
377 if (option_shared) {
378 struct strbuf alt = STRBUF_INIT;
379 strbuf_addf(&alt, "%s/objects", src_repo);
380 add_to_alternates_file(alt.buf);
381 strbuf_release(&alt);
382 } else {
383 struct strbuf src = STRBUF_INIT;
384 struct strbuf dest = STRBUF_INIT;
385 strbuf_addf(&src, "%s/objects", src_repo);
386 strbuf_addf(&dest, "%s/objects", dest_repo);
387 copy_or_link_directory(&src, &dest, src_repo, src.len);
388 strbuf_release(&src);
389 strbuf_release(&dest);
392 if (0 <= option_verbosity)
393 fprintf(stderr, _("done.\n"));
396 static const char *junk_work_tree;
397 static const char *junk_git_dir;
398 static enum {
399 JUNK_LEAVE_NONE,
400 JUNK_LEAVE_REPO,
401 JUNK_LEAVE_ALL
402 } junk_mode = JUNK_LEAVE_NONE;
404 static const char junk_leave_repo_msg[] =
405 N_("Clone succeeded, but checkout failed.\n"
406 "You can inspect what was checked out with 'git status'\n"
407 "and retry the checkout with 'git checkout -f HEAD'\n");
409 static void remove_junk(void)
411 struct strbuf sb = STRBUF_INIT;
413 switch (junk_mode) {
414 case JUNK_LEAVE_REPO:
415 warning("%s", _(junk_leave_repo_msg));
416 /* fall-through */
417 case JUNK_LEAVE_ALL:
418 return;
419 default:
420 /* proceed to removal */
421 break;
424 if (junk_git_dir) {
425 strbuf_addstr(&sb, junk_git_dir);
426 remove_dir_recursively(&sb, 0);
427 strbuf_reset(&sb);
429 if (junk_work_tree) {
430 strbuf_addstr(&sb, junk_work_tree);
431 remove_dir_recursively(&sb, 0);
432 strbuf_reset(&sb);
436 static void remove_junk_on_signal(int signo)
438 remove_junk();
439 sigchain_pop(signo);
440 raise(signo);
443 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
445 struct ref *ref;
446 struct strbuf head = STRBUF_INIT;
447 strbuf_addstr(&head, "refs/heads/");
448 strbuf_addstr(&head, branch);
449 ref = find_ref_by_name(refs, head.buf);
450 strbuf_release(&head);
452 if (ref)
453 return ref;
455 strbuf_addstr(&head, "refs/tags/");
456 strbuf_addstr(&head, branch);
457 ref = find_ref_by_name(refs, head.buf);
458 strbuf_release(&head);
460 return ref;
463 static struct ref *wanted_peer_refs(const struct ref *refs,
464 struct refspec *refspec)
466 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
467 struct ref *local_refs = head;
468 struct ref **tail = head ? &head->next : &local_refs;
470 if (option_single_branch) {
471 struct ref *remote_head = NULL;
473 if (!option_branch)
474 remote_head = guess_remote_head(head, refs, 0);
475 else {
476 local_refs = NULL;
477 tail = &local_refs;
478 remote_head = copy_ref(find_remote_branch(refs, option_branch));
481 if (!remote_head && option_branch)
482 warning(_("Could not find remote branch %s to clone."),
483 option_branch);
484 else {
485 get_fetch_map(remote_head, refspec, &tail, 0);
487 /* if --branch=tag, pull the requested tag explicitly */
488 get_fetch_map(remote_head, tag_refspec, &tail, 0);
490 } else
491 get_fetch_map(refs, refspec, &tail, 0);
493 if (!option_mirror && !option_single_branch)
494 get_fetch_map(refs, tag_refspec, &tail, 0);
496 return local_refs;
499 static void write_remote_refs(const struct ref *local_refs)
501 const struct ref *r;
503 lock_packed_refs(LOCK_DIE_ON_ERROR);
505 for (r = local_refs; r; r = r->next) {
506 if (!r->peer_ref)
507 continue;
508 add_packed_ref(r->peer_ref->name, r->old_sha1);
511 if (commit_packed_refs())
512 die_errno("unable to overwrite old ref-pack file");
515 static void write_followtags(const struct ref *refs, const char *msg)
517 const struct ref *ref;
518 for (ref = refs; ref; ref = ref->next) {
519 if (!starts_with(ref->name, "refs/tags/"))
520 continue;
521 if (ends_with(ref->name, "^{}"))
522 continue;
523 if (!has_sha1_file(ref->old_sha1))
524 continue;
525 update_ref(msg, ref->name, ref->old_sha1,
526 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
530 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
532 struct ref **rm = cb_data;
533 struct ref *ref = *rm;
536 * Skip anything missing a peer_ref, which we are not
537 * actually going to write a ref for.
539 while (ref && !ref->peer_ref)
540 ref = ref->next;
541 /* Returning -1 notes "end of list" to the caller. */
542 if (!ref)
543 return -1;
545 hashcpy(sha1, ref->old_sha1);
546 *rm = ref->next;
547 return 0;
550 static void update_remote_refs(const struct ref *refs,
551 const struct ref *mapped_refs,
552 const struct ref *remote_head_points_at,
553 const char *branch_top,
554 const char *msg,
555 struct transport *transport,
556 int check_connectivity)
558 const struct ref *rm = mapped_refs;
560 if (check_connectivity) {
561 if (transport->progress)
562 fprintf(stderr, _("Checking connectivity... "));
563 if (check_everything_connected_with_transport(iterate_ref_map,
564 0, &rm, transport))
565 die(_("remote did not send all necessary objects"));
566 if (transport->progress)
567 fprintf(stderr, _("done.\n"));
570 if (refs) {
571 write_remote_refs(mapped_refs);
572 if (option_single_branch)
573 write_followtags(refs, msg);
576 if (remote_head_points_at && !option_bare) {
577 struct strbuf head_ref = STRBUF_INIT;
578 strbuf_addstr(&head_ref, branch_top);
579 strbuf_addstr(&head_ref, "HEAD");
580 create_symref(head_ref.buf,
581 remote_head_points_at->peer_ref->name,
582 msg);
586 static void update_head(const struct ref *our, const struct ref *remote,
587 const char *msg)
589 const char *head;
590 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
591 /* Local default branch link */
592 create_symref("HEAD", our->name, NULL);
593 if (!option_bare) {
594 update_ref(msg, "HEAD", our->old_sha1, NULL, 0,
595 UPDATE_REFS_DIE_ON_ERR);
596 install_branch_config(0, head, option_origin, our->name);
598 } else if (our) {
599 struct commit *c = lookup_commit_reference(our->old_sha1);
600 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
601 update_ref(msg, "HEAD", c->object.sha1,
602 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
603 } else if (remote) {
605 * We know remote HEAD points to a non-branch, or
606 * HEAD points to a branch but we don't know which one.
607 * Detach HEAD in all these cases.
609 update_ref(msg, "HEAD", remote->old_sha1,
610 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
614 static int checkout(void)
616 unsigned char sha1[20];
617 char *head;
618 struct lock_file *lock_file;
619 struct unpack_trees_options opts;
620 struct tree *tree;
621 struct tree_desc t;
622 int err = 0;
624 if (option_no_checkout)
625 return 0;
627 head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
628 if (!head) {
629 warning(_("remote HEAD refers to nonexistent ref, "
630 "unable to checkout.\n"));
631 return 0;
633 if (!strcmp(head, "HEAD")) {
634 if (advice_detached_head)
635 detach_advice(sha1_to_hex(sha1));
636 } else {
637 if (!starts_with(head, "refs/heads/"))
638 die(_("HEAD not found below refs/heads!"));
640 free(head);
642 /* We need to be in the new work tree for the checkout */
643 setup_work_tree();
645 lock_file = xcalloc(1, sizeof(struct lock_file));
646 hold_locked_index(lock_file, 1);
648 memset(&opts, 0, sizeof opts);
649 opts.update = 1;
650 opts.merge = 1;
651 opts.fn = oneway_merge;
652 opts.verbose_update = (option_verbosity >= 0);
653 opts.src_index = &the_index;
654 opts.dst_index = &the_index;
656 tree = parse_tree_indirect(sha1);
657 parse_tree(tree);
658 init_tree_desc(&t, tree->buffer, tree->size);
659 if (unpack_trees(1, &t, &opts) < 0)
660 die(_("unable to checkout working tree"));
662 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
663 die(_("unable to write new index file"));
665 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
666 sha1_to_hex(sha1), "1", NULL);
668 if (!err && option_recursive)
669 err = run_command_v_opt(argv_submodule, RUN_GIT_CMD);
671 return err;
674 static int write_one_config(const char *key, const char *value, void *data)
676 return git_config_set_multivar(key, value ? value : "true", "^$", 0);
679 static void write_config(struct string_list *config)
681 int i;
683 for (i = 0; i < config->nr; i++) {
684 if (git_config_parse_parameter(config->items[i].string,
685 write_one_config, NULL) < 0)
686 die("unable to write parameters to config file");
690 static void write_refspec_config(const char *src_ref_prefix,
691 const struct ref *our_head_points_at,
692 const struct ref *remote_head_points_at,
693 struct strbuf *branch_top)
695 struct strbuf key = STRBUF_INIT;
696 struct strbuf value = STRBUF_INIT;
698 if (option_mirror || !option_bare) {
699 if (option_single_branch && !option_mirror) {
700 if (option_branch) {
701 if (starts_with(our_head_points_at->name, "refs/tags/"))
702 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
703 our_head_points_at->name);
704 else
705 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
706 branch_top->buf, option_branch);
707 } else if (remote_head_points_at) {
708 const char *head = remote_head_points_at->name;
709 if (!skip_prefix(head, "refs/heads/", &head))
710 die("BUG: remote HEAD points at non-head?");
712 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
713 branch_top->buf, head);
716 * otherwise, the next "git fetch" will
717 * simply fetch from HEAD without updating
718 * any remote-tracking branch, which is what
719 * we want.
721 } else {
722 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
724 /* Configure the remote */
725 if (value.len) {
726 strbuf_addf(&key, "remote.%s.fetch", option_origin);
727 git_config_set_multivar(key.buf, value.buf, "^$", 0);
728 strbuf_reset(&key);
730 if (option_mirror) {
731 strbuf_addf(&key, "remote.%s.mirror", option_origin);
732 git_config_set(key.buf, "true");
733 strbuf_reset(&key);
738 strbuf_release(&key);
739 strbuf_release(&value);
742 static void dissociate_from_references(void)
744 static const char* argv[] = { "repack", "-a", "-d", NULL };
746 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
747 die(_("cannot repack to clean up"));
748 if (unlink(git_path("objects/info/alternates")) && errno != ENOENT)
749 die_errno(_("cannot unlink temporary alternates file"));
752 int cmd_clone(int argc, const char **argv, const char *prefix)
754 int is_bundle = 0, is_local;
755 struct stat buf;
756 const char *repo_name, *repo, *work_tree, *git_dir;
757 char *path, *dir;
758 int dest_exists;
759 const struct ref *refs, *remote_head;
760 const struct ref *remote_head_points_at;
761 const struct ref *our_head_points_at;
762 struct ref *mapped_refs;
763 const struct ref *ref;
764 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
765 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
766 struct transport *transport = NULL;
767 const char *src_ref_prefix = "refs/heads/";
768 struct remote *remote;
769 int err = 0, complete_refs_before_fetch = 1;
771 struct refspec *refspec;
772 const char *fetch_pattern;
774 packet_trace_identity("clone");
775 argc = parse_options(argc, argv, prefix, builtin_clone_options,
776 builtin_clone_usage, 0);
778 if (argc > 2)
779 usage_msg_opt(_("Too many arguments."),
780 builtin_clone_usage, builtin_clone_options);
782 if (argc == 0)
783 usage_msg_opt(_("You must specify a repository to clone."),
784 builtin_clone_usage, builtin_clone_options);
786 if (option_single_branch == -1)
787 option_single_branch = option_depth ? 1 : 0;
789 if (option_mirror)
790 option_bare = 1;
792 if (option_bare) {
793 if (option_origin)
794 die(_("--bare and --origin %s options are incompatible."),
795 option_origin);
796 if (real_git_dir)
797 die(_("--bare and --separate-git-dir are incompatible."));
798 option_no_checkout = 1;
801 if (!option_origin)
802 option_origin = "origin";
804 repo_name = argv[0];
806 path = get_repo_path(repo_name, &is_bundle);
807 if (path)
808 repo = xstrdup(absolute_path(repo_name));
809 else if (!strchr(repo_name, ':'))
810 die(_("repository '%s' does not exist"), repo_name);
811 else
812 repo = repo_name;
814 /* no need to be strict, transport_set_option() will validate it again */
815 if (option_depth && atoi(option_depth) < 1)
816 die(_("depth %s is not a positive number"), option_depth);
818 if (argc == 2)
819 dir = xstrdup(argv[1]);
820 else
821 dir = guess_dir_name(repo_name, is_bundle, option_bare);
822 strip_trailing_slashes(dir);
824 dest_exists = !stat(dir, &buf);
825 if (dest_exists && !is_empty_dir(dir))
826 die(_("destination path '%s' already exists and is not "
827 "an empty directory."), dir);
829 strbuf_addf(&reflog_msg, "clone: from %s", repo);
831 if (option_bare)
832 work_tree = NULL;
833 else {
834 work_tree = getenv("GIT_WORK_TREE");
835 if (work_tree && !stat(work_tree, &buf))
836 die(_("working tree '%s' already exists."), work_tree);
839 if (option_bare || work_tree)
840 git_dir = xstrdup(dir);
841 else {
842 work_tree = dir;
843 git_dir = mkpathdup("%s/.git", dir);
846 atexit(remove_junk);
847 sigchain_push_common(remove_junk_on_signal);
849 if (!option_bare) {
850 if (safe_create_leading_directories_const(work_tree) < 0)
851 die_errno(_("could not create leading directories of '%s'"),
852 work_tree);
853 if (!dest_exists && mkdir(work_tree, 0777))
854 die_errno(_("could not create work tree dir '%s'"),
855 work_tree);
856 junk_work_tree = work_tree;
857 set_git_work_tree(work_tree);
860 junk_git_dir = git_dir;
861 if (safe_create_leading_directories_const(git_dir) < 0)
862 die(_("could not create leading directories of '%s'"), git_dir);
864 set_git_dir_init(git_dir, real_git_dir, 0);
865 if (real_git_dir) {
866 git_dir = real_git_dir;
867 junk_git_dir = real_git_dir;
870 if (0 <= option_verbosity) {
871 if (option_bare)
872 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
873 else
874 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
876 init_db(option_template, INIT_DB_QUIET);
877 write_config(&option_config);
879 git_config(git_default_config, NULL);
881 if (option_bare) {
882 if (option_mirror)
883 src_ref_prefix = "refs/";
884 strbuf_addstr(&branch_top, src_ref_prefix);
886 git_config_set("core.bare", "true");
887 } else {
888 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
891 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
892 strbuf_addf(&key, "remote.%s.url", option_origin);
893 git_config_set(key.buf, repo);
894 strbuf_reset(&key);
896 if (option_reference.nr)
897 setup_reference();
898 else if (option_dissociate) {
899 warning(_("--dissociate given, but there is no --reference"));
900 option_dissociate = 0;
903 fetch_pattern = value.buf;
904 refspec = parse_fetch_refspec(1, &fetch_pattern);
906 strbuf_reset(&value);
908 remote = remote_get(option_origin);
909 transport = transport_get(remote, remote->url[0]);
910 transport_set_verbosity(transport, option_verbosity, option_progress);
912 path = get_repo_path(remote->url[0], &is_bundle);
913 is_local = option_local != 0 && path && !is_bundle;
914 if (is_local) {
915 if (option_depth)
916 warning(_("--depth is ignored in local clones; use file:// instead."));
917 if (!access(mkpath("%s/shallow", path), F_OK)) {
918 if (option_local > 0)
919 warning(_("source repository is shallow, ignoring --local"));
920 is_local = 0;
923 if (option_local > 0 && !is_local)
924 warning(_("--local is ignored"));
925 transport->cloning = 1;
927 if (!transport->get_refs_list || (!is_local && !transport->fetch))
928 die(_("Don't know how to clone %s"), transport->url);
930 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
932 if (option_depth)
933 transport_set_option(transport, TRANS_OPT_DEPTH,
934 option_depth);
935 if (option_single_branch)
936 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
938 if (option_upload_pack)
939 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
940 option_upload_pack);
942 if (transport->smart_options && !option_depth)
943 transport->smart_options->check_self_contained_and_connected = 1;
945 refs = transport_get_remote_refs(transport);
947 if (refs) {
948 mapped_refs = wanted_peer_refs(refs, refspec);
950 * transport_get_remote_refs() may return refs with null sha-1
951 * in mapped_refs (see struct transport->get_refs_list
952 * comment). In that case we need fetch it early because
953 * remote_head code below relies on it.
955 * for normal clones, transport_get_remote_refs() should
956 * return reliable ref set, we can delay cloning until after
957 * remote HEAD check.
959 for (ref = refs; ref; ref = ref->next)
960 if (is_null_sha1(ref->old_sha1)) {
961 complete_refs_before_fetch = 0;
962 break;
965 if (!is_local && !complete_refs_before_fetch)
966 transport_fetch_refs(transport, mapped_refs);
968 remote_head = find_ref_by_name(refs, "HEAD");
969 remote_head_points_at =
970 guess_remote_head(remote_head, mapped_refs, 0);
972 if (option_branch) {
973 our_head_points_at =
974 find_remote_branch(mapped_refs, option_branch);
976 if (!our_head_points_at)
977 die(_("Remote branch %s not found in upstream %s"),
978 option_branch, option_origin);
980 else
981 our_head_points_at = remote_head_points_at;
983 else {
984 if (option_branch)
985 die(_("Remote branch %s not found in upstream %s"),
986 option_branch, option_origin);
988 warning(_("You appear to have cloned an empty repository."));
989 mapped_refs = NULL;
990 our_head_points_at = NULL;
991 remote_head_points_at = NULL;
992 remote_head = NULL;
993 option_no_checkout = 1;
994 if (!option_bare)
995 install_branch_config(0, "master", option_origin,
996 "refs/heads/master");
999 write_refspec_config(src_ref_prefix, our_head_points_at,
1000 remote_head_points_at, &branch_top);
1002 if (is_local)
1003 clone_local(path, git_dir);
1004 else if (refs && complete_refs_before_fetch)
1005 transport_fetch_refs(transport, mapped_refs);
1007 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1008 branch_top.buf, reflog_msg.buf, transport, !is_local);
1010 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1012 transport_unlock_pack(transport);
1013 transport_disconnect(transport);
1015 if (option_dissociate)
1016 dissociate_from_references();
1018 junk_mode = JUNK_LEAVE_REPO;
1019 err = checkout();
1021 strbuf_release(&reflog_msg);
1022 strbuf_release(&branch_top);
1023 strbuf_release(&key);
1024 strbuf_release(&value);
1025 junk_mode = JUNK_LEAVE_ALL;
1027 free(refspec);
1028 return err;