Merge branch 'sb/submodule-doc'
[git/debian.git] / builtin / clone.c
blob08b5cc433c6fcad5eea2dfc3321aea28a599d51f
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 "config.h"
13 #include "lockfile.h"
14 #include "parse-options.h"
15 #include "fetch-pack.h"
16 #include "refs.h"
17 #include "tree.h"
18 #include "tree-walk.h"
19 #include "unpack-trees.h"
20 #include "transport.h"
21 #include "strbuf.h"
22 #include "dir.h"
23 #include "sigchain.h"
24 #include "branch.h"
25 #include "remote.h"
26 #include "run-command.h"
27 #include "connected.h"
30 * Overall FIXMEs:
31 * - respect DB_ENVIRONMENT for .git/objects.
33 * Implementation notes:
34 * - dropping use-separate-remote and no-separate-remote compatibility
37 static const char * const builtin_clone_usage[] = {
38 N_("git clone [<options>] [--] <repo> [<dir>]"),
39 NULL
42 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
43 static int option_local = -1, option_no_hardlinks, option_shared;
44 static int option_no_tags;
45 static int option_shallow_submodules;
46 static int deepen;
47 static char *option_template, *option_depth, *option_since;
48 static char *option_origin = NULL;
49 static char *option_branch = NULL;
50 static struct string_list option_not = STRING_LIST_INIT_NODUP;
51 static const char *real_git_dir;
52 static char *option_upload_pack = "git-upload-pack";
53 static int option_verbosity;
54 static int option_progress = -1;
55 static enum transport_family family;
56 static struct string_list option_config = STRING_LIST_INIT_NODUP;
57 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
58 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
59 static int option_dissociate;
60 static int max_jobs = -1;
61 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
63 static int recurse_submodules_cb(const struct option *opt,
64 const char *arg, int unset)
66 if (unset)
67 string_list_clear((struct string_list *)opt->value, 0);
68 else if (arg)
69 string_list_append((struct string_list *)opt->value, arg);
70 else
71 string_list_append((struct string_list *)opt->value,
72 (const char *)opt->defval);
74 return 0;
77 static struct option builtin_clone_options[] = {
78 OPT__VERBOSITY(&option_verbosity),
79 OPT_BOOL(0, "progress", &option_progress,
80 N_("force progress reporting")),
81 OPT_BOOL('n', "no-checkout", &option_no_checkout,
82 N_("don't create a checkout")),
83 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
84 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
85 N_("create a bare repository")),
86 OPT_BOOL(0, "mirror", &option_mirror,
87 N_("create a mirror repository (implies bare)")),
88 OPT_BOOL('l', "local", &option_local,
89 N_("to clone from a local repository")),
90 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
91 N_("don't use local hardlinks, always copy")),
92 OPT_BOOL('s', "shared", &option_shared,
93 N_("setup as shared repository")),
94 { OPTION_CALLBACK, 0, "recursive", &option_recurse_submodules,
95 N_("pathspec"), N_("initialize submodules in the clone"),
96 PARSE_OPT_OPTARG | PARSE_OPT_HIDDEN, recurse_submodules_cb,
97 (intptr_t)"." },
98 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
99 N_("pathspec"), N_("initialize submodules in the clone"),
100 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
101 OPT_INTEGER('j', "jobs", &max_jobs,
102 N_("number of submodules cloned in parallel")),
103 OPT_STRING(0, "template", &option_template, N_("template-directory"),
104 N_("directory from which templates will be used")),
105 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
106 N_("reference repository")),
107 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
108 N_("repo"), N_("reference repository")),
109 OPT_BOOL(0, "dissociate", &option_dissociate,
110 N_("use --reference only while cloning")),
111 OPT_STRING('o', "origin", &option_origin, N_("name"),
112 N_("use <name> instead of 'origin' to track upstream")),
113 OPT_STRING('b', "branch", &option_branch, N_("branch"),
114 N_("checkout <branch> instead of the remote's HEAD")),
115 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
116 N_("path to git-upload-pack on the remote")),
117 OPT_STRING(0, "depth", &option_depth, N_("depth"),
118 N_("create a shallow clone of that depth")),
119 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
120 N_("create a shallow clone since a specific time")),
121 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
122 N_("deepen history of shallow clone, excluding rev")),
123 OPT_BOOL(0, "single-branch", &option_single_branch,
124 N_("clone only one branch, HEAD or --branch")),
125 OPT_BOOL(0, "no-tags", &option_no_tags,
126 N_("don't clone any tags, and make later fetches not to follow them")),
127 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
128 N_("any cloned submodules will be shallow")),
129 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
130 N_("separate git dir from working tree")),
131 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
132 N_("set config inside the new repository")),
133 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
134 TRANSPORT_FAMILY_IPV4),
135 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
136 TRANSPORT_FAMILY_IPV6),
137 OPT_END()
140 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
142 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
143 static char *bundle_suffix[] = { ".bundle", "" };
144 size_t baselen = path->len;
145 struct stat st;
146 int i;
148 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
149 strbuf_setlen(path, baselen);
150 strbuf_addstr(path, suffix[i]);
151 if (stat(path->buf, &st))
152 continue;
153 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
154 *is_bundle = 0;
155 return path->buf;
156 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
157 /* Is it a "gitfile"? */
158 char signature[8];
159 const char *dst;
160 int len, fd = open(path->buf, O_RDONLY);
161 if (fd < 0)
162 continue;
163 len = read_in_full(fd, signature, 8);
164 close(fd);
165 if (len != 8 || strncmp(signature, "gitdir: ", 8))
166 continue;
167 dst = read_gitfile(path->buf);
168 if (dst) {
169 *is_bundle = 0;
170 return dst;
175 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
176 strbuf_setlen(path, baselen);
177 strbuf_addstr(path, bundle_suffix[i]);
178 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
179 *is_bundle = 1;
180 return path->buf;
184 return NULL;
187 static char *get_repo_path(const char *repo, int *is_bundle)
189 struct strbuf path = STRBUF_INIT;
190 const char *raw;
191 char *canon;
193 strbuf_addstr(&path, repo);
194 raw = get_repo_path_1(&path, is_bundle);
195 canon = raw ? absolute_pathdup(raw) : NULL;
196 strbuf_release(&path);
197 return canon;
200 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
202 const char *end = repo + strlen(repo), *start, *ptr;
203 size_t len;
204 char *dir;
207 * Skip scheme.
209 start = strstr(repo, "://");
210 if (start == NULL)
211 start = repo;
212 else
213 start += 3;
216 * Skip authentication data. The stripping does happen
217 * greedily, such that we strip up to the last '@' inside
218 * the host part.
220 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
221 if (*ptr == '@')
222 start = ptr + 1;
226 * Strip trailing spaces, slashes and /.git
228 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
229 end--;
230 if (end - start > 5 && is_dir_sep(end[-5]) &&
231 !strncmp(end - 4, ".git", 4)) {
232 end -= 5;
233 while (start < end && is_dir_sep(end[-1]))
234 end--;
238 * Strip trailing port number if we've got only a
239 * hostname (that is, there is no dir separator but a
240 * colon). This check is required such that we do not
241 * strip URI's like '/foo/bar:2222.git', which should
242 * result in a dir '2222' being guessed due to backwards
243 * compatibility.
245 if (memchr(start, '/', end - start) == NULL
246 && memchr(start, ':', end - start) != NULL) {
247 ptr = end;
248 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
249 ptr--;
250 if (start < ptr && ptr[-1] == ':')
251 end = ptr - 1;
255 * Find last component. To remain backwards compatible we
256 * also regard colons as path separators, such that
257 * cloning a repository 'foo:bar.git' would result in a
258 * directory 'bar' being guessed.
260 ptr = end;
261 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
262 ptr--;
263 start = ptr;
266 * Strip .{bundle,git}.
268 len = end - start;
269 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
271 if (!len || (len == 1 && *start == '/'))
272 die(_("No directory name could be guessed.\n"
273 "Please specify a directory on the command line"));
275 if (is_bare)
276 dir = xstrfmt("%.*s.git", (int)len, start);
277 else
278 dir = xstrndup(start, len);
280 * Replace sequences of 'control' characters and whitespace
281 * with one ascii space, remove leading and trailing spaces.
283 if (*dir) {
284 char *out = dir;
285 int prev_space = 1 /* strip leading whitespace */;
286 for (end = dir; *end; ++end) {
287 char ch = *end;
288 if ((unsigned char)ch < '\x20')
289 ch = '\x20';
290 if (isspace(ch)) {
291 if (prev_space)
292 continue;
293 prev_space = 1;
294 } else
295 prev_space = 0;
296 *out++ = ch;
298 *out = '\0';
299 if (out > dir && prev_space)
300 out[-1] = '\0';
302 return dir;
305 static void strip_trailing_slashes(char *dir)
307 char *end = dir + strlen(dir);
309 while (dir < end - 1 && is_dir_sep(end[-1]))
310 end--;
311 *end = '\0';
314 static int add_one_reference(struct string_list_item *item, void *cb_data)
316 struct strbuf err = STRBUF_INIT;
317 int *required = cb_data;
318 char *ref_git = compute_alternate_path(item->string, &err);
320 if (!ref_git) {
321 if (*required)
322 die("%s", err.buf);
323 else
324 fprintf(stderr,
325 _("info: Could not add alternate for '%s': %s\n"),
326 item->string, err.buf);
327 } else {
328 struct strbuf sb = STRBUF_INIT;
329 strbuf_addf(&sb, "%s/objects", ref_git);
330 add_to_alternates_file(sb.buf);
331 strbuf_release(&sb);
334 strbuf_release(&err);
335 free(ref_git);
336 return 0;
339 static void setup_reference(void)
341 int required = 1;
342 for_each_string_list(&option_required_reference,
343 add_one_reference, &required);
344 required = 0;
345 for_each_string_list(&option_optional_reference,
346 add_one_reference, &required);
349 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
350 const char *src_repo)
353 * Read from the source objects/info/alternates file
354 * and copy the entries to corresponding file in the
355 * destination repository with add_to_alternates_file().
356 * Both src and dst have "$path/objects/info/alternates".
358 * Instead of copying bit-for-bit from the original,
359 * we need to append to existing one so that the already
360 * created entry via "clone -s" is not lost, and also
361 * to turn entries with paths relative to the original
362 * absolute, so that they can be used in the new repository.
364 FILE *in = xfopen(src->buf, "r");
365 struct strbuf line = STRBUF_INIT;
367 while (strbuf_getline(&line, in) != EOF) {
368 char *abs_path;
369 if (!line.len || line.buf[0] == '#')
370 continue;
371 if (is_absolute_path(line.buf)) {
372 add_to_alternates_file(line.buf);
373 continue;
375 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
376 if (!normalize_path_copy(abs_path, abs_path))
377 add_to_alternates_file(abs_path);
378 else
379 warning("skipping invalid relative alternate: %s/%s",
380 src_repo, line.buf);
381 free(abs_path);
383 strbuf_release(&line);
384 fclose(in);
387 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
388 const char *src_repo, int src_baselen)
390 struct dirent *de;
391 struct stat buf;
392 int src_len, dest_len;
393 DIR *dir;
395 dir = opendir(src->buf);
396 if (!dir)
397 die_errno(_("failed to open '%s'"), src->buf);
399 if (mkdir(dest->buf, 0777)) {
400 if (errno != EEXIST)
401 die_errno(_("failed to create directory '%s'"), dest->buf);
402 else if (stat(dest->buf, &buf))
403 die_errno(_("failed to stat '%s'"), dest->buf);
404 else if (!S_ISDIR(buf.st_mode))
405 die(_("%s exists and is not a directory"), dest->buf);
408 strbuf_addch(src, '/');
409 src_len = src->len;
410 strbuf_addch(dest, '/');
411 dest_len = dest->len;
413 while ((de = readdir(dir)) != NULL) {
414 strbuf_setlen(src, src_len);
415 strbuf_addstr(src, de->d_name);
416 strbuf_setlen(dest, dest_len);
417 strbuf_addstr(dest, de->d_name);
418 if (stat(src->buf, &buf)) {
419 warning (_("failed to stat %s\n"), src->buf);
420 continue;
422 if (S_ISDIR(buf.st_mode)) {
423 if (de->d_name[0] != '.')
424 copy_or_link_directory(src, dest,
425 src_repo, src_baselen);
426 continue;
429 /* Files that cannot be copied bit-for-bit... */
430 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
431 copy_alternates(src, dest, src_repo);
432 continue;
435 if (unlink(dest->buf) && errno != ENOENT)
436 die_errno(_("failed to unlink '%s'"), dest->buf);
437 if (!option_no_hardlinks) {
438 if (!link(src->buf, dest->buf))
439 continue;
440 if (option_local > 0)
441 die_errno(_("failed to create link '%s'"), dest->buf);
442 option_no_hardlinks = 1;
444 if (copy_file_with_time(dest->buf, src->buf, 0666))
445 die_errno(_("failed to copy file to '%s'"), dest->buf);
447 closedir(dir);
450 static void clone_local(const char *src_repo, const char *dest_repo)
452 if (option_shared) {
453 struct strbuf alt = STRBUF_INIT;
454 strbuf_addf(&alt, "%s/objects", src_repo);
455 add_to_alternates_file(alt.buf);
456 strbuf_release(&alt);
457 } else {
458 struct strbuf src = STRBUF_INIT;
459 struct strbuf dest = STRBUF_INIT;
460 get_common_dir(&src, src_repo);
461 get_common_dir(&dest, dest_repo);
462 strbuf_addstr(&src, "/objects");
463 strbuf_addstr(&dest, "/objects");
464 copy_or_link_directory(&src, &dest, src_repo, src.len);
465 strbuf_release(&src);
466 strbuf_release(&dest);
469 if (0 <= option_verbosity)
470 fprintf(stderr, _("done.\n"));
473 static const char *junk_work_tree;
474 static const char *junk_git_dir;
475 static enum {
476 JUNK_LEAVE_NONE,
477 JUNK_LEAVE_REPO,
478 JUNK_LEAVE_ALL
479 } junk_mode = JUNK_LEAVE_NONE;
481 static const char junk_leave_repo_msg[] =
482 N_("Clone succeeded, but checkout failed.\n"
483 "You can inspect what was checked out with 'git status'\n"
484 "and retry the checkout with 'git checkout -f HEAD'\n");
486 static void remove_junk(void)
488 struct strbuf sb = STRBUF_INIT;
490 switch (junk_mode) {
491 case JUNK_LEAVE_REPO:
492 warning("%s", _(junk_leave_repo_msg));
493 /* fall-through */
494 case JUNK_LEAVE_ALL:
495 return;
496 default:
497 /* proceed to removal */
498 break;
501 if (junk_git_dir) {
502 strbuf_addstr(&sb, junk_git_dir);
503 remove_dir_recursively(&sb, 0);
504 strbuf_reset(&sb);
506 if (junk_work_tree) {
507 strbuf_addstr(&sb, junk_work_tree);
508 remove_dir_recursively(&sb, 0);
509 strbuf_reset(&sb);
513 static void remove_junk_on_signal(int signo)
515 remove_junk();
516 sigchain_pop(signo);
517 raise(signo);
520 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
522 struct ref *ref;
523 struct strbuf head = STRBUF_INIT;
524 strbuf_addstr(&head, "refs/heads/");
525 strbuf_addstr(&head, branch);
526 ref = find_ref_by_name(refs, head.buf);
527 strbuf_release(&head);
529 if (ref)
530 return ref;
532 strbuf_addstr(&head, "refs/tags/");
533 strbuf_addstr(&head, branch);
534 ref = find_ref_by_name(refs, head.buf);
535 strbuf_release(&head);
537 return ref;
540 static struct ref *wanted_peer_refs(const struct ref *refs,
541 struct refspec *refspec)
543 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
544 struct ref *local_refs = head;
545 struct ref **tail = head ? &head->next : &local_refs;
547 if (option_single_branch) {
548 struct ref *remote_head = NULL;
550 if (!option_branch)
551 remote_head = guess_remote_head(head, refs, 0);
552 else {
553 local_refs = NULL;
554 tail = &local_refs;
555 remote_head = copy_ref(find_remote_branch(refs, option_branch));
558 if (!remote_head && option_branch)
559 warning(_("Could not find remote branch %s to clone."),
560 option_branch);
561 else {
562 get_fetch_map(remote_head, refspec, &tail, 0);
564 /* if --branch=tag, pull the requested tag explicitly */
565 get_fetch_map(remote_head, tag_refspec, &tail, 0);
567 } else
568 get_fetch_map(refs, refspec, &tail, 0);
570 if (!option_mirror && !option_single_branch && !option_no_tags)
571 get_fetch_map(refs, tag_refspec, &tail, 0);
573 return local_refs;
576 static void write_remote_refs(const struct ref *local_refs)
578 const struct ref *r;
580 struct ref_transaction *t;
581 struct strbuf err = STRBUF_INIT;
583 t = ref_transaction_begin(&err);
584 if (!t)
585 die("%s", err.buf);
587 for (r = local_refs; r; r = r->next) {
588 if (!r->peer_ref)
589 continue;
590 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
591 0, NULL, &err))
592 die("%s", err.buf);
595 if (initial_ref_transaction_commit(t, &err))
596 die("%s", err.buf);
598 strbuf_release(&err);
599 ref_transaction_free(t);
602 static void write_followtags(const struct ref *refs, const char *msg)
604 const struct ref *ref;
605 for (ref = refs; ref; ref = ref->next) {
606 if (!starts_with(ref->name, "refs/tags/"))
607 continue;
608 if (ends_with(ref->name, "^{}"))
609 continue;
610 if (!has_object_file(&ref->old_oid))
611 continue;
612 update_ref(msg, ref->name, ref->old_oid.hash,
613 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
617 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
619 struct ref **rm = cb_data;
620 struct ref *ref = *rm;
623 * Skip anything missing a peer_ref, which we are not
624 * actually going to write a ref for.
626 while (ref && !ref->peer_ref)
627 ref = ref->next;
628 /* Returning -1 notes "end of list" to the caller. */
629 if (!ref)
630 return -1;
632 hashcpy(sha1, ref->old_oid.hash);
633 *rm = ref->next;
634 return 0;
637 static void update_remote_refs(const struct ref *refs,
638 const struct ref *mapped_refs,
639 const struct ref *remote_head_points_at,
640 const char *branch_top,
641 const char *msg,
642 struct transport *transport,
643 int check_connectivity)
645 const struct ref *rm = mapped_refs;
647 if (check_connectivity) {
648 struct check_connected_options opt = CHECK_CONNECTED_INIT;
650 opt.transport = transport;
651 opt.progress = transport->progress;
653 if (check_connected(iterate_ref_map, &rm, &opt))
654 die(_("remote did not send all necessary objects"));
657 if (refs) {
658 write_remote_refs(mapped_refs);
659 if (option_single_branch && !option_no_tags)
660 write_followtags(refs, msg);
663 if (remote_head_points_at && !option_bare) {
664 struct strbuf head_ref = STRBUF_INIT;
665 strbuf_addstr(&head_ref, branch_top);
666 strbuf_addstr(&head_ref, "HEAD");
667 if (create_symref(head_ref.buf,
668 remote_head_points_at->peer_ref->name,
669 msg) < 0)
670 die(_("unable to update %s"), head_ref.buf);
671 strbuf_release(&head_ref);
675 static void update_head(const struct ref *our, const struct ref *remote,
676 const char *msg)
678 const char *head;
679 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
680 /* Local default branch link */
681 if (create_symref("HEAD", our->name, NULL) < 0)
682 die(_("unable to update HEAD"));
683 if (!option_bare) {
684 update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
685 UPDATE_REFS_DIE_ON_ERR);
686 install_branch_config(0, head, option_origin, our->name);
688 } else if (our) {
689 struct commit *c = lookup_commit_reference(&our->old_oid);
690 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
691 update_ref(msg, "HEAD", c->object.oid.hash,
692 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
693 } else if (remote) {
695 * We know remote HEAD points to a non-branch, or
696 * HEAD points to a branch but we don't know which one.
697 * Detach HEAD in all these cases.
699 update_ref(msg, "HEAD", remote->old_oid.hash,
700 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
704 static int checkout(int submodule_progress)
706 struct object_id oid;
707 char *head;
708 struct lock_file *lock_file;
709 struct unpack_trees_options opts;
710 struct tree *tree;
711 struct tree_desc t;
712 int err = 0;
714 if (option_no_checkout)
715 return 0;
717 head = resolve_refdup("HEAD", RESOLVE_REF_READING, oid.hash, NULL);
718 if (!head) {
719 warning(_("remote HEAD refers to nonexistent ref, "
720 "unable to checkout.\n"));
721 return 0;
723 if (!strcmp(head, "HEAD")) {
724 if (advice_detached_head)
725 detach_advice(oid_to_hex(&oid));
726 } else {
727 if (!starts_with(head, "refs/heads/"))
728 die(_("HEAD not found below refs/heads!"));
730 free(head);
732 /* We need to be in the new work tree for the checkout */
733 setup_work_tree();
735 lock_file = xcalloc(1, sizeof(struct lock_file));
736 hold_locked_index(lock_file, LOCK_DIE_ON_ERROR);
738 memset(&opts, 0, sizeof opts);
739 opts.update = 1;
740 opts.merge = 1;
741 opts.fn = oneway_merge;
742 opts.verbose_update = (option_verbosity >= 0);
743 opts.src_index = &the_index;
744 opts.dst_index = &the_index;
746 tree = parse_tree_indirect(&oid);
747 parse_tree(tree);
748 init_tree_desc(&t, tree->buffer, tree->size);
749 if (unpack_trees(1, &t, &opts) < 0)
750 die(_("unable to checkout working tree"));
752 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
753 die(_("unable to write new index file"));
755 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
756 oid_to_hex(&oid), "1", NULL);
758 if (!err && (option_recurse_submodules.nr > 0)) {
759 struct argv_array args = ARGV_ARRAY_INIT;
760 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
762 if (option_shallow_submodules == 1)
763 argv_array_push(&args, "--depth=1");
765 if (max_jobs != -1)
766 argv_array_pushf(&args, "--jobs=%d", max_jobs);
768 if (submodule_progress)
769 argv_array_push(&args, "--progress");
771 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
772 argv_array_clear(&args);
775 return err;
778 static int write_one_config(const char *key, const char *value, void *data)
780 return git_config_set_multivar_gently(key,
781 value ? value : "true",
782 CONFIG_REGEX_NONE, 0);
785 static void write_config(struct string_list *config)
787 int i;
789 for (i = 0; i < config->nr; i++) {
790 if (git_config_parse_parameter(config->items[i].string,
791 write_one_config, NULL) < 0)
792 die(_("unable to write parameters to config file"));
796 static void write_refspec_config(const char *src_ref_prefix,
797 const struct ref *our_head_points_at,
798 const struct ref *remote_head_points_at,
799 struct strbuf *branch_top)
801 struct strbuf key = STRBUF_INIT;
802 struct strbuf value = STRBUF_INIT;
804 if (option_mirror || !option_bare) {
805 if (option_single_branch && !option_mirror) {
806 if (option_branch) {
807 if (starts_with(our_head_points_at->name, "refs/tags/"))
808 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
809 our_head_points_at->name);
810 else
811 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
812 branch_top->buf, option_branch);
813 } else if (remote_head_points_at) {
814 const char *head = remote_head_points_at->name;
815 if (!skip_prefix(head, "refs/heads/", &head))
816 die("BUG: remote HEAD points at non-head?");
818 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
819 branch_top->buf, head);
822 * otherwise, the next "git fetch" will
823 * simply fetch from HEAD without updating
824 * any remote-tracking branch, which is what
825 * we want.
827 } else {
828 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
830 /* Configure the remote */
831 if (value.len) {
832 strbuf_addf(&key, "remote.%s.fetch", option_origin);
833 git_config_set_multivar(key.buf, value.buf, "^$", 0);
834 strbuf_reset(&key);
836 if (option_mirror) {
837 strbuf_addf(&key, "remote.%s.mirror", option_origin);
838 git_config_set(key.buf, "true");
839 strbuf_reset(&key);
844 strbuf_release(&key);
845 strbuf_release(&value);
848 static void dissociate_from_references(void)
850 static const char* argv[] = { "repack", "-a", "-d", NULL };
851 char *alternates = git_pathdup("objects/info/alternates");
853 if (!access(alternates, F_OK)) {
854 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
855 die(_("cannot repack to clean up"));
856 if (unlink(alternates) && errno != ENOENT)
857 die_errno(_("cannot unlink temporary alternates file"));
859 free(alternates);
862 int cmd_clone(int argc, const char **argv, const char *prefix)
864 int is_bundle = 0, is_local;
865 struct stat buf;
866 const char *repo_name, *repo, *work_tree, *git_dir;
867 char *path, *dir;
868 int dest_exists;
869 const struct ref *refs, *remote_head;
870 const struct ref *remote_head_points_at;
871 const struct ref *our_head_points_at;
872 struct ref *mapped_refs;
873 const struct ref *ref;
874 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
875 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
876 struct transport *transport = NULL;
877 const char *src_ref_prefix = "refs/heads/";
878 struct remote *remote;
879 int err = 0, complete_refs_before_fetch = 1;
880 int submodule_progress;
882 struct refspec *refspec;
883 const char *fetch_pattern;
885 packet_trace_identity("clone");
886 argc = parse_options(argc, argv, prefix, builtin_clone_options,
887 builtin_clone_usage, 0);
889 if (argc > 2)
890 usage_msg_opt(_("Too many arguments."),
891 builtin_clone_usage, builtin_clone_options);
893 if (argc == 0)
894 usage_msg_opt(_("You must specify a repository to clone."),
895 builtin_clone_usage, builtin_clone_options);
897 if (option_depth || option_since || option_not.nr)
898 deepen = 1;
899 if (option_single_branch == -1)
900 option_single_branch = deepen ? 1 : 0;
902 if (option_mirror)
903 option_bare = 1;
905 if (option_bare) {
906 if (option_origin)
907 die(_("--bare and --origin %s options are incompatible."),
908 option_origin);
909 if (real_git_dir)
910 die(_("--bare and --separate-git-dir are incompatible."));
911 option_no_checkout = 1;
914 if (!option_origin)
915 option_origin = "origin";
917 repo_name = argv[0];
919 path = get_repo_path(repo_name, &is_bundle);
920 if (path)
921 repo = absolute_pathdup(repo_name);
922 else if (!strchr(repo_name, ':'))
923 die(_("repository '%s' does not exist"), repo_name);
924 else
925 repo = repo_name;
927 /* no need to be strict, transport_set_option() will validate it again */
928 if (option_depth && atoi(option_depth) < 1)
929 die(_("depth %s is not a positive number"), option_depth);
931 if (argc == 2)
932 dir = xstrdup(argv[1]);
933 else
934 dir = guess_dir_name(repo_name, is_bundle, option_bare);
935 strip_trailing_slashes(dir);
937 dest_exists = !stat(dir, &buf);
938 if (dest_exists && !is_empty_dir(dir))
939 die(_("destination path '%s' already exists and is not "
940 "an empty directory."), dir);
942 strbuf_addf(&reflog_msg, "clone: from %s", repo);
944 if (option_bare)
945 work_tree = NULL;
946 else {
947 work_tree = getenv("GIT_WORK_TREE");
948 if (work_tree && !stat(work_tree, &buf))
949 die(_("working tree '%s' already exists."), work_tree);
952 if (option_bare || work_tree)
953 git_dir = xstrdup(dir);
954 else {
955 work_tree = dir;
956 git_dir = mkpathdup("%s/.git", dir);
959 atexit(remove_junk);
960 sigchain_push_common(remove_junk_on_signal);
962 if (!option_bare) {
963 if (safe_create_leading_directories_const(work_tree) < 0)
964 die_errno(_("could not create leading directories of '%s'"),
965 work_tree);
966 if (!dest_exists && mkdir(work_tree, 0777))
967 die_errno(_("could not create work tree dir '%s'"),
968 work_tree);
969 junk_work_tree = work_tree;
970 set_git_work_tree(work_tree);
973 junk_git_dir = real_git_dir ? real_git_dir : git_dir;
974 if (safe_create_leading_directories_const(git_dir) < 0)
975 die(_("could not create leading directories of '%s'"), git_dir);
977 if (0 <= option_verbosity) {
978 if (option_bare)
979 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
980 else
981 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
984 if (option_recurse_submodules.nr > 0) {
985 struct string_list_item *item;
986 struct strbuf sb = STRBUF_INIT;
988 /* remove duplicates */
989 string_list_sort(&option_recurse_submodules);
990 string_list_remove_duplicates(&option_recurse_submodules, 0);
993 * NEEDSWORK: In a multi-working-tree world, this needs to be
994 * set in the per-worktree config.
996 for_each_string_list_item(item, &option_recurse_submodules) {
997 strbuf_addf(&sb, "submodule.active=%s",
998 item->string);
999 string_list_append(&option_config,
1000 strbuf_detach(&sb, NULL));
1003 if (option_required_reference.nr &&
1004 option_optional_reference.nr)
1005 die(_("clone --recursive is not compatible with "
1006 "both --reference and --reference-if-able"));
1007 else if (option_required_reference.nr) {
1008 string_list_append(&option_config,
1009 "submodule.alternateLocation=superproject");
1010 string_list_append(&option_config,
1011 "submodule.alternateErrorStrategy=die");
1012 } else if (option_optional_reference.nr) {
1013 string_list_append(&option_config,
1014 "submodule.alternateLocation=superproject");
1015 string_list_append(&option_config,
1016 "submodule.alternateErrorStrategy=info");
1020 init_db(git_dir, real_git_dir, option_template, INIT_DB_QUIET);
1022 if (real_git_dir)
1023 git_dir = real_git_dir;
1025 write_config(&option_config);
1027 git_config(git_default_config, NULL);
1029 if (option_bare) {
1030 if (option_mirror)
1031 src_ref_prefix = "refs/";
1032 strbuf_addstr(&branch_top, src_ref_prefix);
1034 git_config_set("core.bare", "true");
1035 } else {
1036 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
1039 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
1040 strbuf_addf(&key, "remote.%s.url", option_origin);
1041 git_config_set(key.buf, repo);
1042 strbuf_reset(&key);
1044 if (option_no_tags) {
1045 strbuf_addf(&key, "remote.%s.tagOpt", option_origin);
1046 git_config_set(key.buf, "--no-tags");
1047 strbuf_reset(&key);
1050 if (option_required_reference.nr || option_optional_reference.nr)
1051 setup_reference();
1053 fetch_pattern = value.buf;
1054 refspec = parse_fetch_refspec(1, &fetch_pattern);
1056 strbuf_reset(&value);
1058 remote = remote_get(option_origin);
1059 transport = transport_get(remote, remote->url[0]);
1060 transport_set_verbosity(transport, option_verbosity, option_progress);
1061 transport->family = family;
1063 path = get_repo_path(remote->url[0], &is_bundle);
1064 is_local = option_local != 0 && path && !is_bundle;
1065 if (is_local) {
1066 if (option_depth)
1067 warning(_("--depth is ignored in local clones; use file:// instead."));
1068 if (option_since)
1069 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1070 if (option_not.nr)
1071 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1072 if (!access(mkpath("%s/shallow", path), F_OK)) {
1073 if (option_local > 0)
1074 warning(_("source repository is shallow, ignoring --local"));
1075 is_local = 0;
1078 if (option_local > 0 && !is_local)
1079 warning(_("--local is ignored"));
1080 transport->cloning = 1;
1082 if (!transport->get_refs_list || (!is_local && !transport->fetch))
1083 die(_("Don't know how to clone %s"), transport->url);
1085 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1087 if (option_depth)
1088 transport_set_option(transport, TRANS_OPT_DEPTH,
1089 option_depth);
1090 if (option_since)
1091 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1092 option_since);
1093 if (option_not.nr)
1094 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1095 (const char *)&option_not);
1096 if (option_single_branch)
1097 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1099 if (option_upload_pack)
1100 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1101 option_upload_pack);
1103 if (transport->smart_options && !deepen)
1104 transport->smart_options->check_self_contained_and_connected = 1;
1106 refs = transport_get_remote_refs(transport);
1108 if (refs) {
1109 mapped_refs = wanted_peer_refs(refs, refspec);
1111 * transport_get_remote_refs() may return refs with null sha-1
1112 * in mapped_refs (see struct transport->get_refs_list
1113 * comment). In that case we need fetch it early because
1114 * remote_head code below relies on it.
1116 * for normal clones, transport_get_remote_refs() should
1117 * return reliable ref set, we can delay cloning until after
1118 * remote HEAD check.
1120 for (ref = refs; ref; ref = ref->next)
1121 if (is_null_oid(&ref->old_oid)) {
1122 complete_refs_before_fetch = 0;
1123 break;
1126 if (!is_local && !complete_refs_before_fetch)
1127 transport_fetch_refs(transport, mapped_refs);
1129 remote_head = find_ref_by_name(refs, "HEAD");
1130 remote_head_points_at =
1131 guess_remote_head(remote_head, mapped_refs, 0);
1133 if (option_branch) {
1134 our_head_points_at =
1135 find_remote_branch(mapped_refs, option_branch);
1137 if (!our_head_points_at)
1138 die(_("Remote branch %s not found in upstream %s"),
1139 option_branch, option_origin);
1141 else
1142 our_head_points_at = remote_head_points_at;
1144 else {
1145 if (option_branch)
1146 die(_("Remote branch %s not found in upstream %s"),
1147 option_branch, option_origin);
1149 warning(_("You appear to have cloned an empty repository."));
1150 mapped_refs = NULL;
1151 our_head_points_at = NULL;
1152 remote_head_points_at = NULL;
1153 remote_head = NULL;
1154 option_no_checkout = 1;
1155 if (!option_bare)
1156 install_branch_config(0, "master", option_origin,
1157 "refs/heads/master");
1160 write_refspec_config(src_ref_prefix, our_head_points_at,
1161 remote_head_points_at, &branch_top);
1163 if (is_local)
1164 clone_local(path, git_dir);
1165 else if (refs && complete_refs_before_fetch)
1166 transport_fetch_refs(transport, mapped_refs);
1168 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1169 branch_top.buf, reflog_msg.buf, transport, !is_local);
1171 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1174 * We want to show progress for recursive submodule clones iff
1175 * we did so for the main clone. But only the transport knows
1176 * the final decision for this flag, so we need to rescue the value
1177 * before we free the transport.
1179 submodule_progress = transport->progress;
1181 transport_unlock_pack(transport);
1182 transport_disconnect(transport);
1184 if (option_dissociate) {
1185 close_all_packs();
1186 dissociate_from_references();
1189 junk_mode = JUNK_LEAVE_REPO;
1190 err = checkout(submodule_progress);
1192 strbuf_release(&reflog_msg);
1193 strbuf_release(&branch_top);
1194 strbuf_release(&key);
1195 strbuf_release(&value);
1196 junk_mode = JUNK_LEAVE_ALL;
1198 free(refspec);
1199 return err;