Merge branch 'sg/help-group' into maint
[git.git] / builtin / clone.c
blob53cf545c5ec20a97e8380979d304acad7ec0e965
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 struct option builtin_clone_options[] = {
55 OPT__VERBOSITY(&option_verbosity),
56 OPT_BOOL(0, "progress", &option_progress,
57 N_("force progress reporting")),
58 OPT_BOOL('n', "no-checkout", &option_no_checkout,
59 N_("don't create a checkout")),
60 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
61 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
62 N_("create a bare repository")),
63 OPT_BOOL(0, "mirror", &option_mirror,
64 N_("create a mirror repository (implies bare)")),
65 OPT_BOOL('l', "local", &option_local,
66 N_("to clone from a local repository")),
67 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
68 N_("don't use local hardlinks, always copy")),
69 OPT_BOOL('s', "shared", &option_shared,
70 N_("setup as shared repository")),
71 OPT_BOOL(0, "recursive", &option_recursive,
72 N_("initialize submodules in the clone")),
73 OPT_BOOL(0, "recurse-submodules", &option_recursive,
74 N_("initialize submodules in the clone")),
75 OPT_STRING(0, "template", &option_template, N_("template-directory"),
76 N_("directory from which templates will be used")),
77 OPT_STRING_LIST(0, "reference", &option_reference, N_("repo"),
78 N_("reference repository")),
79 OPT_BOOL(0, "dissociate", &option_dissociate,
80 N_("use --reference only while cloning")),
81 OPT_STRING('o', "origin", &option_origin, N_("name"),
82 N_("use <name> instead of 'origin' to track upstream")),
83 OPT_STRING('b', "branch", &option_branch, N_("branch"),
84 N_("checkout <branch> instead of the remote's HEAD")),
85 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
86 N_("path to git-upload-pack on the remote")),
87 OPT_STRING(0, "depth", &option_depth, N_("depth"),
88 N_("create a shallow clone of that depth")),
89 OPT_BOOL(0, "single-branch", &option_single_branch,
90 N_("clone only one branch, HEAD or --branch")),
91 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
92 N_("separate git dir from working tree")),
93 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
94 N_("set config inside the new repository")),
95 OPT_END()
98 static const char *argv_submodule[] = {
99 "submodule", "update", "--init", "--recursive", NULL
102 static char *get_repo_path(const char *repo, int *is_bundle)
104 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
105 static char *bundle_suffix[] = { ".bundle", "" };
106 struct stat st;
107 int i;
109 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
110 const char *path;
111 path = mkpath("%s%s", repo, suffix[i]);
112 if (stat(path, &st))
113 continue;
114 if (S_ISDIR(st.st_mode) && is_git_directory(path)) {
115 *is_bundle = 0;
116 return xstrdup(absolute_path(path));
117 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
118 /* Is it a "gitfile"? */
119 char signature[8];
120 int len, fd = open(path, O_RDONLY);
121 if (fd < 0)
122 continue;
123 len = read_in_full(fd, signature, 8);
124 close(fd);
125 if (len != 8 || strncmp(signature, "gitdir: ", 8))
126 continue;
127 path = read_gitfile(path);
128 if (path) {
129 *is_bundle = 0;
130 return xstrdup(absolute_path(path));
135 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
136 const char *path;
137 path = mkpath("%s%s", repo, bundle_suffix[i]);
138 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
139 *is_bundle = 1;
140 return xstrdup(absolute_path(path));
144 return NULL;
147 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
149 const char *end = repo + strlen(repo), *start;
150 size_t len;
151 char *dir;
154 * Strip trailing spaces, slashes and /.git
156 while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
157 end--;
158 if (end - repo > 5 && is_dir_sep(end[-5]) &&
159 !strncmp(end - 4, ".git", 4)) {
160 end -= 5;
161 while (repo < end && is_dir_sep(end[-1]))
162 end--;
166 * Find last component, but be prepared that repo could have
167 * the form "remote.example.com:foo.git", i.e. no slash
168 * in the directory part.
170 start = end;
171 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
172 start--;
175 * Strip .{bundle,git}.
177 len = end - start;
178 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
180 if (is_bare)
181 dir = xstrfmt("%.*s.git", (int)len, start);
182 else
183 dir = xstrndup(start, len);
185 * Replace sequences of 'control' characters and whitespace
186 * with one ascii space, remove leading and trailing spaces.
188 if (*dir) {
189 char *out = dir;
190 int prev_space = 1 /* strip leading whitespace */;
191 for (end = dir; *end; ++end) {
192 char ch = *end;
193 if ((unsigned char)ch < '\x20')
194 ch = '\x20';
195 if (isspace(ch)) {
196 if (prev_space)
197 continue;
198 prev_space = 1;
199 } else
200 prev_space = 0;
201 *out++ = ch;
203 *out = '\0';
204 if (out > dir && prev_space)
205 out[-1] = '\0';
207 return dir;
210 static void strip_trailing_slashes(char *dir)
212 char *end = dir + strlen(dir);
214 while (dir < end - 1 && is_dir_sep(end[-1]))
215 end--;
216 *end = '\0';
219 static int add_one_reference(struct string_list_item *item, void *cb_data)
221 char *ref_git;
222 const char *repo;
223 struct strbuf alternate = STRBUF_INIT;
225 /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
226 ref_git = xstrdup(real_path(item->string));
228 repo = read_gitfile(ref_git);
229 if (!repo)
230 repo = read_gitfile(mkpath("%s/.git", ref_git));
231 if (repo) {
232 free(ref_git);
233 ref_git = xstrdup(repo);
236 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
237 char *ref_git_git = mkpathdup("%s/.git", ref_git);
238 free(ref_git);
239 ref_git = ref_git_git;
240 } else if (!is_directory(mkpath("%s/objects", ref_git)))
241 die(_("reference repository '%s' is not a local repository."),
242 item->string);
244 if (!access(mkpath("%s/shallow", ref_git), F_OK))
245 die(_("reference repository '%s' is shallow"), item->string);
247 if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
248 die(_("reference repository '%s' is grafted"), item->string);
250 strbuf_addf(&alternate, "%s/objects", ref_git);
251 add_to_alternates_file(alternate.buf);
252 strbuf_release(&alternate);
253 free(ref_git);
254 return 0;
257 static void setup_reference(void)
259 for_each_string_list(&option_reference, add_one_reference, NULL);
262 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
263 const char *src_repo)
266 * Read from the source objects/info/alternates file
267 * and copy the entries to corresponding file in the
268 * destination repository with add_to_alternates_file().
269 * Both src and dst have "$path/objects/info/alternates".
271 * Instead of copying bit-for-bit from the original,
272 * we need to append to existing one so that the already
273 * created entry via "clone -s" is not lost, and also
274 * to turn entries with paths relative to the original
275 * absolute, so that they can be used in the new repository.
277 FILE *in = fopen(src->buf, "r");
278 struct strbuf line = STRBUF_INIT;
280 while (strbuf_getline(&line, in, '\n') != EOF) {
281 char *abs_path;
282 if (!line.len || line.buf[0] == '#')
283 continue;
284 if (is_absolute_path(line.buf)) {
285 add_to_alternates_file(line.buf);
286 continue;
288 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
289 normalize_path_copy(abs_path, abs_path);
290 add_to_alternates_file(abs_path);
291 free(abs_path);
293 strbuf_release(&line);
294 fclose(in);
297 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
298 const char *src_repo, int src_baselen)
300 struct dirent *de;
301 struct stat buf;
302 int src_len, dest_len;
303 DIR *dir;
305 dir = opendir(src->buf);
306 if (!dir)
307 die_errno(_("failed to open '%s'"), src->buf);
309 if (mkdir(dest->buf, 0777)) {
310 if (errno != EEXIST)
311 die_errno(_("failed to create directory '%s'"), dest->buf);
312 else if (stat(dest->buf, &buf))
313 die_errno(_("failed to stat '%s'"), dest->buf);
314 else if (!S_ISDIR(buf.st_mode))
315 die(_("%s exists and is not a directory"), dest->buf);
318 strbuf_addch(src, '/');
319 src_len = src->len;
320 strbuf_addch(dest, '/');
321 dest_len = dest->len;
323 while ((de = readdir(dir)) != NULL) {
324 strbuf_setlen(src, src_len);
325 strbuf_addstr(src, de->d_name);
326 strbuf_setlen(dest, dest_len);
327 strbuf_addstr(dest, de->d_name);
328 if (stat(src->buf, &buf)) {
329 warning (_("failed to stat %s\n"), src->buf);
330 continue;
332 if (S_ISDIR(buf.st_mode)) {
333 if (de->d_name[0] != '.')
334 copy_or_link_directory(src, dest,
335 src_repo, src_baselen);
336 continue;
339 /* Files that cannot be copied bit-for-bit... */
340 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
341 copy_alternates(src, dest, src_repo);
342 continue;
345 if (unlink(dest->buf) && errno != ENOENT)
346 die_errno(_("failed to unlink '%s'"), dest->buf);
347 if (!option_no_hardlinks) {
348 if (!link(src->buf, dest->buf))
349 continue;
350 if (option_local > 0)
351 die_errno(_("failed to create link '%s'"), dest->buf);
352 option_no_hardlinks = 1;
354 if (copy_file_with_time(dest->buf, src->buf, 0666))
355 die_errno(_("failed to copy file to '%s'"), dest->buf);
357 closedir(dir);
360 static void clone_local(const char *src_repo, const char *dest_repo)
362 if (option_shared) {
363 struct strbuf alt = STRBUF_INIT;
364 strbuf_addf(&alt, "%s/objects", src_repo);
365 add_to_alternates_file(alt.buf);
366 strbuf_release(&alt);
367 } else {
368 struct strbuf src = STRBUF_INIT;
369 struct strbuf dest = STRBUF_INIT;
370 strbuf_addf(&src, "%s/objects", src_repo);
371 strbuf_addf(&dest, "%s/objects", dest_repo);
372 copy_or_link_directory(&src, &dest, src_repo, src.len);
373 strbuf_release(&src);
374 strbuf_release(&dest);
377 if (0 <= option_verbosity)
378 fprintf(stderr, _("done.\n"));
381 static const char *junk_work_tree;
382 static const char *junk_git_dir;
383 static enum {
384 JUNK_LEAVE_NONE,
385 JUNK_LEAVE_REPO,
386 JUNK_LEAVE_ALL
387 } junk_mode = JUNK_LEAVE_NONE;
389 static const char junk_leave_repo_msg[] =
390 N_("Clone succeeded, but checkout failed.\n"
391 "You can inspect what was checked out with 'git status'\n"
392 "and retry the checkout with 'git checkout -f HEAD'\n");
394 static void remove_junk(void)
396 struct strbuf sb = STRBUF_INIT;
398 switch (junk_mode) {
399 case JUNK_LEAVE_REPO:
400 warning("%s", _(junk_leave_repo_msg));
401 /* fall-through */
402 case JUNK_LEAVE_ALL:
403 return;
404 default:
405 /* proceed to removal */
406 break;
409 if (junk_git_dir) {
410 strbuf_addstr(&sb, junk_git_dir);
411 remove_dir_recursively(&sb, 0);
412 strbuf_reset(&sb);
414 if (junk_work_tree) {
415 strbuf_addstr(&sb, junk_work_tree);
416 remove_dir_recursively(&sb, 0);
417 strbuf_reset(&sb);
421 static void remove_junk_on_signal(int signo)
423 remove_junk();
424 sigchain_pop(signo);
425 raise(signo);
428 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
430 struct ref *ref;
431 struct strbuf head = STRBUF_INIT;
432 strbuf_addstr(&head, "refs/heads/");
433 strbuf_addstr(&head, branch);
434 ref = find_ref_by_name(refs, head.buf);
435 strbuf_release(&head);
437 if (ref)
438 return ref;
440 strbuf_addstr(&head, "refs/tags/");
441 strbuf_addstr(&head, branch);
442 ref = find_ref_by_name(refs, head.buf);
443 strbuf_release(&head);
445 return ref;
448 static struct ref *wanted_peer_refs(const struct ref *refs,
449 struct refspec *refspec)
451 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
452 struct ref *local_refs = head;
453 struct ref **tail = head ? &head->next : &local_refs;
455 if (option_single_branch) {
456 struct ref *remote_head = NULL;
458 if (!option_branch)
459 remote_head = guess_remote_head(head, refs, 0);
460 else {
461 local_refs = NULL;
462 tail = &local_refs;
463 remote_head = copy_ref(find_remote_branch(refs, option_branch));
466 if (!remote_head && option_branch)
467 warning(_("Could not find remote branch %s to clone."),
468 option_branch);
469 else {
470 get_fetch_map(remote_head, refspec, &tail, 0);
472 /* if --branch=tag, pull the requested tag explicitly */
473 get_fetch_map(remote_head, tag_refspec, &tail, 0);
475 } else
476 get_fetch_map(refs, refspec, &tail, 0);
478 if (!option_mirror && !option_single_branch)
479 get_fetch_map(refs, tag_refspec, &tail, 0);
481 return local_refs;
484 static void write_remote_refs(const struct ref *local_refs)
486 const struct ref *r;
488 lock_packed_refs(LOCK_DIE_ON_ERROR);
490 for (r = local_refs; r; r = r->next) {
491 if (!r->peer_ref)
492 continue;
493 add_packed_ref(r->peer_ref->name, r->old_sha1);
496 if (commit_packed_refs())
497 die_errno("unable to overwrite old ref-pack file");
500 static void write_followtags(const struct ref *refs, const char *msg)
502 const struct ref *ref;
503 for (ref = refs; ref; ref = ref->next) {
504 if (!starts_with(ref->name, "refs/tags/"))
505 continue;
506 if (ends_with(ref->name, "^{}"))
507 continue;
508 if (!has_sha1_file(ref->old_sha1))
509 continue;
510 update_ref(msg, ref->name, ref->old_sha1,
511 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
515 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
517 struct ref **rm = cb_data;
518 struct ref *ref = *rm;
521 * Skip anything missing a peer_ref, which we are not
522 * actually going to write a ref for.
524 while (ref && !ref->peer_ref)
525 ref = ref->next;
526 /* Returning -1 notes "end of list" to the caller. */
527 if (!ref)
528 return -1;
530 hashcpy(sha1, ref->old_sha1);
531 *rm = ref->next;
532 return 0;
535 static void update_remote_refs(const struct ref *refs,
536 const struct ref *mapped_refs,
537 const struct ref *remote_head_points_at,
538 const char *branch_top,
539 const char *msg,
540 struct transport *transport,
541 int check_connectivity)
543 const struct ref *rm = mapped_refs;
545 if (check_connectivity) {
546 if (transport->progress)
547 fprintf(stderr, _("Checking connectivity... "));
548 if (check_everything_connected_with_transport(iterate_ref_map,
549 0, &rm, transport))
550 die(_("remote did not send all necessary objects"));
551 if (transport->progress)
552 fprintf(stderr, _("done.\n"));
555 if (refs) {
556 write_remote_refs(mapped_refs);
557 if (option_single_branch)
558 write_followtags(refs, msg);
561 if (remote_head_points_at && !option_bare) {
562 struct strbuf head_ref = STRBUF_INIT;
563 strbuf_addstr(&head_ref, branch_top);
564 strbuf_addstr(&head_ref, "HEAD");
565 create_symref(head_ref.buf,
566 remote_head_points_at->peer_ref->name,
567 msg);
571 static void update_head(const struct ref *our, const struct ref *remote,
572 const char *msg)
574 const char *head;
575 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
576 /* Local default branch link */
577 create_symref("HEAD", our->name, NULL);
578 if (!option_bare) {
579 update_ref(msg, "HEAD", our->old_sha1, NULL, 0,
580 UPDATE_REFS_DIE_ON_ERR);
581 install_branch_config(0, head, option_origin, our->name);
583 } else if (our) {
584 struct commit *c = lookup_commit_reference(our->old_sha1);
585 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
586 update_ref(msg, "HEAD", c->object.sha1,
587 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
588 } else if (remote) {
590 * We know remote HEAD points to a non-branch, or
591 * HEAD points to a branch but we don't know which one.
592 * Detach HEAD in all these cases.
594 update_ref(msg, "HEAD", remote->old_sha1,
595 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
599 static int checkout(void)
601 unsigned char sha1[20];
602 char *head;
603 struct lock_file *lock_file;
604 struct unpack_trees_options opts;
605 struct tree *tree;
606 struct tree_desc t;
607 int err = 0;
609 if (option_no_checkout)
610 return 0;
612 head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
613 if (!head) {
614 warning(_("remote HEAD refers to nonexistent ref, "
615 "unable to checkout.\n"));
616 return 0;
618 if (!strcmp(head, "HEAD")) {
619 if (advice_detached_head)
620 detach_advice(sha1_to_hex(sha1));
621 } else {
622 if (!starts_with(head, "refs/heads/"))
623 die(_("HEAD not found below refs/heads!"));
625 free(head);
627 /* We need to be in the new work tree for the checkout */
628 setup_work_tree();
630 lock_file = xcalloc(1, sizeof(struct lock_file));
631 hold_locked_index(lock_file, 1);
633 memset(&opts, 0, sizeof opts);
634 opts.update = 1;
635 opts.merge = 1;
636 opts.fn = oneway_merge;
637 opts.verbose_update = (option_verbosity >= 0);
638 opts.src_index = &the_index;
639 opts.dst_index = &the_index;
641 tree = parse_tree_indirect(sha1);
642 parse_tree(tree);
643 init_tree_desc(&t, tree->buffer, tree->size);
644 if (unpack_trees(1, &t, &opts) < 0)
645 die(_("unable to checkout working tree"));
647 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
648 die(_("unable to write new index file"));
650 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
651 sha1_to_hex(sha1), "1", NULL);
653 if (!err && option_recursive)
654 err = run_command_v_opt(argv_submodule, RUN_GIT_CMD);
656 return err;
659 static int write_one_config(const char *key, const char *value, void *data)
661 return git_config_set_multivar(key, value ? value : "true", "^$", 0);
664 static void write_config(struct string_list *config)
666 int i;
668 for (i = 0; i < config->nr; i++) {
669 if (git_config_parse_parameter(config->items[i].string,
670 write_one_config, NULL) < 0)
671 die("unable to write parameters to config file");
675 static void write_refspec_config(const char *src_ref_prefix,
676 const struct ref *our_head_points_at,
677 const struct ref *remote_head_points_at,
678 struct strbuf *branch_top)
680 struct strbuf key = STRBUF_INIT;
681 struct strbuf value = STRBUF_INIT;
683 if (option_mirror || !option_bare) {
684 if (option_single_branch && !option_mirror) {
685 if (option_branch) {
686 if (starts_with(our_head_points_at->name, "refs/tags/"))
687 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
688 our_head_points_at->name);
689 else
690 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
691 branch_top->buf, option_branch);
692 } else if (remote_head_points_at) {
693 const char *head = remote_head_points_at->name;
694 if (!skip_prefix(head, "refs/heads/", &head))
695 die("BUG: remote HEAD points at non-head?");
697 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
698 branch_top->buf, head);
701 * otherwise, the next "git fetch" will
702 * simply fetch from HEAD without updating
703 * any remote-tracking branch, which is what
704 * we want.
706 } else {
707 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
709 /* Configure the remote */
710 if (value.len) {
711 strbuf_addf(&key, "remote.%s.fetch", option_origin);
712 git_config_set_multivar(key.buf, value.buf, "^$", 0);
713 strbuf_reset(&key);
715 if (option_mirror) {
716 strbuf_addf(&key, "remote.%s.mirror", option_origin);
717 git_config_set(key.buf, "true");
718 strbuf_reset(&key);
723 strbuf_release(&key);
724 strbuf_release(&value);
727 static void dissociate_from_references(void)
729 static const char* argv[] = { "repack", "-a", "-d", NULL };
731 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
732 die(_("cannot repack to clean up"));
733 if (unlink(git_path("objects/info/alternates")) && errno != ENOENT)
734 die_errno(_("cannot unlink temporary alternates file"));
737 int cmd_clone(int argc, const char **argv, const char *prefix)
739 int is_bundle = 0, is_local;
740 struct stat buf;
741 const char *repo_name, *repo, *work_tree, *git_dir;
742 char *path, *dir;
743 int dest_exists;
744 const struct ref *refs, *remote_head;
745 const struct ref *remote_head_points_at;
746 const struct ref *our_head_points_at;
747 struct ref *mapped_refs;
748 const struct ref *ref;
749 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
750 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
751 struct transport *transport = NULL;
752 const char *src_ref_prefix = "refs/heads/";
753 struct remote *remote;
754 int err = 0, complete_refs_before_fetch = 1;
756 struct refspec *refspec;
757 const char *fetch_pattern;
759 packet_trace_identity("clone");
760 argc = parse_options(argc, argv, prefix, builtin_clone_options,
761 builtin_clone_usage, 0);
763 if (argc > 2)
764 usage_msg_opt(_("Too many arguments."),
765 builtin_clone_usage, builtin_clone_options);
767 if (argc == 0)
768 usage_msg_opt(_("You must specify a repository to clone."),
769 builtin_clone_usage, builtin_clone_options);
771 if (option_single_branch == -1)
772 option_single_branch = option_depth ? 1 : 0;
774 if (option_mirror)
775 option_bare = 1;
777 if (option_bare) {
778 if (option_origin)
779 die(_("--bare and --origin %s options are incompatible."),
780 option_origin);
781 if (real_git_dir)
782 die(_("--bare and --separate-git-dir are incompatible."));
783 option_no_checkout = 1;
786 if (!option_origin)
787 option_origin = "origin";
789 repo_name = argv[0];
791 path = get_repo_path(repo_name, &is_bundle);
792 if (path)
793 repo = xstrdup(absolute_path(repo_name));
794 else if (!strchr(repo_name, ':'))
795 die(_("repository '%s' does not exist"), repo_name);
796 else
797 repo = repo_name;
799 /* no need to be strict, transport_set_option() will validate it again */
800 if (option_depth && atoi(option_depth) < 1)
801 die(_("depth %s is not a positive number"), option_depth);
803 if (argc == 2)
804 dir = xstrdup(argv[1]);
805 else
806 dir = guess_dir_name(repo_name, is_bundle, option_bare);
807 strip_trailing_slashes(dir);
809 dest_exists = !stat(dir, &buf);
810 if (dest_exists && !is_empty_dir(dir))
811 die(_("destination path '%s' already exists and is not "
812 "an empty directory."), dir);
814 strbuf_addf(&reflog_msg, "clone: from %s", repo);
816 if (option_bare)
817 work_tree = NULL;
818 else {
819 work_tree = getenv("GIT_WORK_TREE");
820 if (work_tree && !stat(work_tree, &buf))
821 die(_("working tree '%s' already exists."), work_tree);
824 if (option_bare || work_tree)
825 git_dir = xstrdup(dir);
826 else {
827 work_tree = dir;
828 git_dir = mkpathdup("%s/.git", dir);
831 atexit(remove_junk);
832 sigchain_push_common(remove_junk_on_signal);
834 if (!option_bare) {
835 if (safe_create_leading_directories_const(work_tree) < 0)
836 die_errno(_("could not create leading directories of '%s'"),
837 work_tree);
838 if (!dest_exists && mkdir(work_tree, 0777))
839 die_errno(_("could not create work tree dir '%s'"),
840 work_tree);
841 junk_work_tree = work_tree;
842 set_git_work_tree(work_tree);
845 junk_git_dir = git_dir;
846 if (safe_create_leading_directories_const(git_dir) < 0)
847 die(_("could not create leading directories of '%s'"), git_dir);
849 set_git_dir_init(git_dir, real_git_dir, 0);
850 if (real_git_dir) {
851 git_dir = real_git_dir;
852 junk_git_dir = real_git_dir;
855 if (0 <= option_verbosity) {
856 if (option_bare)
857 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
858 else
859 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
861 init_db(option_template, INIT_DB_QUIET);
862 write_config(&option_config);
864 git_config(git_default_config, NULL);
866 if (option_bare) {
867 if (option_mirror)
868 src_ref_prefix = "refs/";
869 strbuf_addstr(&branch_top, src_ref_prefix);
871 git_config_set("core.bare", "true");
872 } else {
873 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
876 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
877 strbuf_addf(&key, "remote.%s.url", option_origin);
878 git_config_set(key.buf, repo);
879 strbuf_reset(&key);
881 if (option_reference.nr)
882 setup_reference();
883 else if (option_dissociate) {
884 warning(_("--dissociate given, but there is no --reference"));
885 option_dissociate = 0;
888 fetch_pattern = value.buf;
889 refspec = parse_fetch_refspec(1, &fetch_pattern);
891 strbuf_reset(&value);
893 remote = remote_get(option_origin);
894 transport = transport_get(remote, remote->url[0]);
895 transport_set_verbosity(transport, option_verbosity, option_progress);
897 path = get_repo_path(remote->url[0], &is_bundle);
898 is_local = option_local != 0 && path && !is_bundle;
899 if (is_local) {
900 if (option_depth)
901 warning(_("--depth is ignored in local clones; use file:// instead."));
902 if (!access(mkpath("%s/shallow", path), F_OK)) {
903 if (option_local > 0)
904 warning(_("source repository is shallow, ignoring --local"));
905 is_local = 0;
908 if (option_local > 0 && !is_local)
909 warning(_("--local is ignored"));
910 transport->cloning = 1;
912 if (!transport->get_refs_list || (!is_local && !transport->fetch))
913 die(_("Don't know how to clone %s"), transport->url);
915 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
917 if (option_depth)
918 transport_set_option(transport, TRANS_OPT_DEPTH,
919 option_depth);
920 if (option_single_branch)
921 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
923 if (option_upload_pack)
924 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
925 option_upload_pack);
927 if (transport->smart_options && !option_depth)
928 transport->smart_options->check_self_contained_and_connected = 1;
930 refs = transport_get_remote_refs(transport);
932 if (refs) {
933 mapped_refs = wanted_peer_refs(refs, refspec);
935 * transport_get_remote_refs() may return refs with null sha-1
936 * in mapped_refs (see struct transport->get_refs_list
937 * comment). In that case we need fetch it early because
938 * remote_head code below relies on it.
940 * for normal clones, transport_get_remote_refs() should
941 * return reliable ref set, we can delay cloning until after
942 * remote HEAD check.
944 for (ref = refs; ref; ref = ref->next)
945 if (is_null_sha1(ref->old_sha1)) {
946 complete_refs_before_fetch = 0;
947 break;
950 if (!is_local && !complete_refs_before_fetch)
951 transport_fetch_refs(transport, mapped_refs);
953 remote_head = find_ref_by_name(refs, "HEAD");
954 remote_head_points_at =
955 guess_remote_head(remote_head, mapped_refs, 0);
957 if (option_branch) {
958 our_head_points_at =
959 find_remote_branch(mapped_refs, option_branch);
961 if (!our_head_points_at)
962 die(_("Remote branch %s not found in upstream %s"),
963 option_branch, option_origin);
965 else
966 our_head_points_at = remote_head_points_at;
968 else {
969 if (option_branch)
970 die(_("Remote branch %s not found in upstream %s"),
971 option_branch, option_origin);
973 warning(_("You appear to have cloned an empty repository."));
974 mapped_refs = NULL;
975 our_head_points_at = NULL;
976 remote_head_points_at = NULL;
977 remote_head = NULL;
978 option_no_checkout = 1;
979 if (!option_bare)
980 install_branch_config(0, "master", option_origin,
981 "refs/heads/master");
984 write_refspec_config(src_ref_prefix, our_head_points_at,
985 remote_head_points_at, &branch_top);
987 if (is_local)
988 clone_local(path, git_dir);
989 else if (refs && complete_refs_before_fetch)
990 transport_fetch_refs(transport, mapped_refs);
992 update_remote_refs(refs, mapped_refs, remote_head_points_at,
993 branch_top.buf, reflog_msg.buf, transport, !is_local);
995 update_head(our_head_points_at, remote_head, reflog_msg.buf);
997 transport_unlock_pack(transport);
998 transport_disconnect(transport);
1000 if (option_dissociate)
1001 dissociate_from_references();
1003 junk_mode = JUNK_LEAVE_REPO;
1004 err = checkout();
1006 strbuf_release(&reflog_msg);
1007 strbuf_release(&branch_top);
1008 strbuf_release(&key);
1009 strbuf_release(&value);
1010 junk_mode = JUNK_LEAVE_ALL;
1012 free(refspec);
1013 return err;