clone: partial clone
[git.git] / builtin / clone.c
blobf519bd49b03dfe60f9a2d05f1c1177096c0c80ab
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"
28 #include "packfile.h"
29 #include "list-objects-filter-options.h"
32 * Overall FIXMEs:
33 * - respect DB_ENVIRONMENT for .git/objects.
35 * Implementation notes:
36 * - dropping use-separate-remote and no-separate-remote compatibility
39 static const char * const builtin_clone_usage[] = {
40 N_("git clone [<options>] [--] <repo> [<dir>]"),
41 NULL
44 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
45 static int option_local = -1, option_no_hardlinks, option_shared;
46 static int option_no_tags;
47 static int option_shallow_submodules;
48 static int deepen;
49 static char *option_template, *option_depth, *option_since;
50 static char *option_origin = NULL;
51 static char *option_branch = NULL;
52 static struct string_list option_not = STRING_LIST_INIT_NODUP;
53 static const char *real_git_dir;
54 static char *option_upload_pack = "git-upload-pack";
55 static int option_verbosity;
56 static int option_progress = -1;
57 static enum transport_family family;
58 static struct string_list option_config = STRING_LIST_INIT_NODUP;
59 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
60 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
61 static int option_dissociate;
62 static int max_jobs = -1;
63 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
64 static struct list_objects_filter_options filter_options;
66 static int recurse_submodules_cb(const struct option *opt,
67 const char *arg, int unset)
69 if (unset)
70 string_list_clear((struct string_list *)opt->value, 0);
71 else if (arg)
72 string_list_append((struct string_list *)opt->value, arg);
73 else
74 string_list_append((struct string_list *)opt->value,
75 (const char *)opt->defval);
77 return 0;
80 static struct option builtin_clone_options[] = {
81 OPT__VERBOSITY(&option_verbosity),
82 OPT_BOOL(0, "progress", &option_progress,
83 N_("force progress reporting")),
84 OPT_BOOL('n', "no-checkout", &option_no_checkout,
85 N_("don't create a checkout")),
86 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
87 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
88 N_("create a bare repository")),
89 OPT_BOOL(0, "mirror", &option_mirror,
90 N_("create a mirror repository (implies bare)")),
91 OPT_BOOL('l', "local", &option_local,
92 N_("to clone from a local repository")),
93 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
94 N_("don't use local hardlinks, always copy")),
95 OPT_BOOL('s', "shared", &option_shared,
96 N_("setup as shared repository")),
97 { OPTION_CALLBACK, 0, "recursive", &option_recurse_submodules,
98 N_("pathspec"), N_("initialize submodules in the clone"),
99 PARSE_OPT_OPTARG | PARSE_OPT_HIDDEN, recurse_submodules_cb,
100 (intptr_t)"." },
101 { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
102 N_("pathspec"), N_("initialize submodules in the clone"),
103 PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
104 OPT_INTEGER('j', "jobs", &max_jobs,
105 N_("number of submodules cloned in parallel")),
106 OPT_STRING(0, "template", &option_template, N_("template-directory"),
107 N_("directory from which templates will be used")),
108 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
109 N_("reference repository")),
110 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
111 N_("repo"), N_("reference repository")),
112 OPT_BOOL(0, "dissociate", &option_dissociate,
113 N_("use --reference only while cloning")),
114 OPT_STRING('o', "origin", &option_origin, N_("name"),
115 N_("use <name> instead of 'origin' to track upstream")),
116 OPT_STRING('b', "branch", &option_branch, N_("branch"),
117 N_("checkout <branch> instead of the remote's HEAD")),
118 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
119 N_("path to git-upload-pack on the remote")),
120 OPT_STRING(0, "depth", &option_depth, N_("depth"),
121 N_("create a shallow clone of that depth")),
122 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
123 N_("create a shallow clone since a specific time")),
124 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
125 N_("deepen history of shallow clone, excluding rev")),
126 OPT_BOOL(0, "single-branch", &option_single_branch,
127 N_("clone only one branch, HEAD or --branch")),
128 OPT_BOOL(0, "no-tags", &option_no_tags,
129 N_("don't clone any tags, and make later fetches not to follow them")),
130 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
131 N_("any cloned submodules will be shallow")),
132 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
133 N_("separate git dir from working tree")),
134 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
135 N_("set config inside the new repository")),
136 OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
137 TRANSPORT_FAMILY_IPV4),
138 OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
139 TRANSPORT_FAMILY_IPV6),
140 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
141 OPT_END()
144 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
146 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
147 static char *bundle_suffix[] = { ".bundle", "" };
148 size_t baselen = path->len;
149 struct stat st;
150 int i;
152 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
153 strbuf_setlen(path, baselen);
154 strbuf_addstr(path, suffix[i]);
155 if (stat(path->buf, &st))
156 continue;
157 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
158 *is_bundle = 0;
159 return path->buf;
160 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
161 /* Is it a "gitfile"? */
162 char signature[8];
163 const char *dst;
164 int len, fd = open(path->buf, O_RDONLY);
165 if (fd < 0)
166 continue;
167 len = read_in_full(fd, signature, 8);
168 close(fd);
169 if (len != 8 || strncmp(signature, "gitdir: ", 8))
170 continue;
171 dst = read_gitfile(path->buf);
172 if (dst) {
173 *is_bundle = 0;
174 return dst;
179 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
180 strbuf_setlen(path, baselen);
181 strbuf_addstr(path, bundle_suffix[i]);
182 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
183 *is_bundle = 1;
184 return path->buf;
188 return NULL;
191 static char *get_repo_path(const char *repo, int *is_bundle)
193 struct strbuf path = STRBUF_INIT;
194 const char *raw;
195 char *canon;
197 strbuf_addstr(&path, repo);
198 raw = get_repo_path_1(&path, is_bundle);
199 canon = raw ? absolute_pathdup(raw) : NULL;
200 strbuf_release(&path);
201 return canon;
204 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
206 const char *end = repo + strlen(repo), *start, *ptr;
207 size_t len;
208 char *dir;
211 * Skip scheme.
213 start = strstr(repo, "://");
214 if (start == NULL)
215 start = repo;
216 else
217 start += 3;
220 * Skip authentication data. The stripping does happen
221 * greedily, such that we strip up to the last '@' inside
222 * the host part.
224 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
225 if (*ptr == '@')
226 start = ptr + 1;
230 * Strip trailing spaces, slashes and /.git
232 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
233 end--;
234 if (end - start > 5 && is_dir_sep(end[-5]) &&
235 !strncmp(end - 4, ".git", 4)) {
236 end -= 5;
237 while (start < end && is_dir_sep(end[-1]))
238 end--;
242 * Strip trailing port number if we've got only a
243 * hostname (that is, there is no dir separator but a
244 * colon). This check is required such that we do not
245 * strip URI's like '/foo/bar:2222.git', which should
246 * result in a dir '2222' being guessed due to backwards
247 * compatibility.
249 if (memchr(start, '/', end - start) == NULL
250 && memchr(start, ':', end - start) != NULL) {
251 ptr = end;
252 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
253 ptr--;
254 if (start < ptr && ptr[-1] == ':')
255 end = ptr - 1;
259 * Find last component. To remain backwards compatible we
260 * also regard colons as path separators, such that
261 * cloning a repository 'foo:bar.git' would result in a
262 * directory 'bar' being guessed.
264 ptr = end;
265 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
266 ptr--;
267 start = ptr;
270 * Strip .{bundle,git}.
272 len = end - start;
273 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
275 if (!len || (len == 1 && *start == '/'))
276 die(_("No directory name could be guessed.\n"
277 "Please specify a directory on the command line"));
279 if (is_bare)
280 dir = xstrfmt("%.*s.git", (int)len, start);
281 else
282 dir = xstrndup(start, len);
284 * Replace sequences of 'control' characters and whitespace
285 * with one ascii space, remove leading and trailing spaces.
287 if (*dir) {
288 char *out = dir;
289 int prev_space = 1 /* strip leading whitespace */;
290 for (end = dir; *end; ++end) {
291 char ch = *end;
292 if ((unsigned char)ch < '\x20')
293 ch = '\x20';
294 if (isspace(ch)) {
295 if (prev_space)
296 continue;
297 prev_space = 1;
298 } else
299 prev_space = 0;
300 *out++ = ch;
302 *out = '\0';
303 if (out > dir && prev_space)
304 out[-1] = '\0';
306 return dir;
309 static void strip_trailing_slashes(char *dir)
311 char *end = dir + strlen(dir);
313 while (dir < end - 1 && is_dir_sep(end[-1]))
314 end--;
315 *end = '\0';
318 static int add_one_reference(struct string_list_item *item, void *cb_data)
320 struct strbuf err = STRBUF_INIT;
321 int *required = cb_data;
322 char *ref_git = compute_alternate_path(item->string, &err);
324 if (!ref_git) {
325 if (*required)
326 die("%s", err.buf);
327 else
328 fprintf(stderr,
329 _("info: Could not add alternate for '%s': %s\n"),
330 item->string, err.buf);
331 } else {
332 struct strbuf sb = STRBUF_INIT;
333 strbuf_addf(&sb, "%s/objects", ref_git);
334 add_to_alternates_file(sb.buf);
335 strbuf_release(&sb);
338 strbuf_release(&err);
339 free(ref_git);
340 return 0;
343 static void setup_reference(void)
345 int required = 1;
346 for_each_string_list(&option_required_reference,
347 add_one_reference, &required);
348 required = 0;
349 for_each_string_list(&option_optional_reference,
350 add_one_reference, &required);
353 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
354 const char *src_repo)
357 * Read from the source objects/info/alternates file
358 * and copy the entries to corresponding file in the
359 * destination repository with add_to_alternates_file().
360 * Both src and dst have "$path/objects/info/alternates".
362 * Instead of copying bit-for-bit from the original,
363 * we need to append to existing one so that the already
364 * created entry via "clone -s" is not lost, and also
365 * to turn entries with paths relative to the original
366 * absolute, so that they can be used in the new repository.
368 FILE *in = xfopen(src->buf, "r");
369 struct strbuf line = STRBUF_INIT;
371 while (strbuf_getline(&line, in) != EOF) {
372 char *abs_path;
373 if (!line.len || line.buf[0] == '#')
374 continue;
375 if (is_absolute_path(line.buf)) {
376 add_to_alternates_file(line.buf);
377 continue;
379 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
380 if (!normalize_path_copy(abs_path, abs_path))
381 add_to_alternates_file(abs_path);
382 else
383 warning("skipping invalid relative alternate: %s/%s",
384 src_repo, line.buf);
385 free(abs_path);
387 strbuf_release(&line);
388 fclose(in);
391 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
392 const char *src_repo, int src_baselen)
394 struct dirent *de;
395 struct stat buf;
396 int src_len, dest_len;
397 DIR *dir;
399 dir = opendir(src->buf);
400 if (!dir)
401 die_errno(_("failed to open '%s'"), src->buf);
403 if (mkdir(dest->buf, 0777)) {
404 if (errno != EEXIST)
405 die_errno(_("failed to create directory '%s'"), dest->buf);
406 else if (stat(dest->buf, &buf))
407 die_errno(_("failed to stat '%s'"), dest->buf);
408 else if (!S_ISDIR(buf.st_mode))
409 die(_("%s exists and is not a directory"), dest->buf);
412 strbuf_addch(src, '/');
413 src_len = src->len;
414 strbuf_addch(dest, '/');
415 dest_len = dest->len;
417 while ((de = readdir(dir)) != NULL) {
418 strbuf_setlen(src, src_len);
419 strbuf_addstr(src, de->d_name);
420 strbuf_setlen(dest, dest_len);
421 strbuf_addstr(dest, de->d_name);
422 if (stat(src->buf, &buf)) {
423 warning (_("failed to stat %s\n"), src->buf);
424 continue;
426 if (S_ISDIR(buf.st_mode)) {
427 if (de->d_name[0] != '.')
428 copy_or_link_directory(src, dest,
429 src_repo, src_baselen);
430 continue;
433 /* Files that cannot be copied bit-for-bit... */
434 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
435 copy_alternates(src, dest, src_repo);
436 continue;
439 if (unlink(dest->buf) && errno != ENOENT)
440 die_errno(_("failed to unlink '%s'"), dest->buf);
441 if (!option_no_hardlinks) {
442 if (!link(src->buf, dest->buf))
443 continue;
444 if (option_local > 0)
445 die_errno(_("failed to create link '%s'"), dest->buf);
446 option_no_hardlinks = 1;
448 if (copy_file_with_time(dest->buf, src->buf, 0666))
449 die_errno(_("failed to copy file to '%s'"), dest->buf);
451 closedir(dir);
454 static void clone_local(const char *src_repo, const char *dest_repo)
456 if (option_shared) {
457 struct strbuf alt = STRBUF_INIT;
458 strbuf_addf(&alt, "%s/objects", src_repo);
459 add_to_alternates_file(alt.buf);
460 strbuf_release(&alt);
461 } else {
462 struct strbuf src = STRBUF_INIT;
463 struct strbuf dest = STRBUF_INIT;
464 get_common_dir(&src, src_repo);
465 get_common_dir(&dest, dest_repo);
466 strbuf_addstr(&src, "/objects");
467 strbuf_addstr(&dest, "/objects");
468 copy_or_link_directory(&src, &dest, src_repo, src.len);
469 strbuf_release(&src);
470 strbuf_release(&dest);
473 if (0 <= option_verbosity)
474 fprintf(stderr, _("done.\n"));
477 static const char *junk_work_tree;
478 static const char *junk_git_dir;
479 static enum {
480 JUNK_LEAVE_NONE,
481 JUNK_LEAVE_REPO,
482 JUNK_LEAVE_ALL
483 } junk_mode = JUNK_LEAVE_NONE;
485 static const char junk_leave_repo_msg[] =
486 N_("Clone succeeded, but checkout failed.\n"
487 "You can inspect what was checked out with 'git status'\n"
488 "and retry the checkout with 'git checkout -f HEAD'\n");
490 static void remove_junk(void)
492 struct strbuf sb = STRBUF_INIT;
494 switch (junk_mode) {
495 case JUNK_LEAVE_REPO:
496 warning("%s", _(junk_leave_repo_msg));
497 /* fall-through */
498 case JUNK_LEAVE_ALL:
499 return;
500 default:
501 /* proceed to removal */
502 break;
505 if (junk_git_dir) {
506 strbuf_addstr(&sb, junk_git_dir);
507 remove_dir_recursively(&sb, 0);
508 strbuf_reset(&sb);
510 if (junk_work_tree) {
511 strbuf_addstr(&sb, junk_work_tree);
512 remove_dir_recursively(&sb, 0);
514 strbuf_release(&sb);
517 static void remove_junk_on_signal(int signo)
519 remove_junk();
520 sigchain_pop(signo);
521 raise(signo);
524 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
526 struct ref *ref;
527 struct strbuf head = STRBUF_INIT;
528 strbuf_addstr(&head, "refs/heads/");
529 strbuf_addstr(&head, branch);
530 ref = find_ref_by_name(refs, head.buf);
531 strbuf_release(&head);
533 if (ref)
534 return ref;
536 strbuf_addstr(&head, "refs/tags/");
537 strbuf_addstr(&head, branch);
538 ref = find_ref_by_name(refs, head.buf);
539 strbuf_release(&head);
541 return ref;
544 static struct ref *wanted_peer_refs(const struct ref *refs,
545 struct refspec *refspec)
547 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
548 struct ref *local_refs = head;
549 struct ref **tail = head ? &head->next : &local_refs;
551 if (option_single_branch) {
552 struct ref *remote_head = NULL;
554 if (!option_branch)
555 remote_head = guess_remote_head(head, refs, 0);
556 else {
557 local_refs = NULL;
558 tail = &local_refs;
559 remote_head = copy_ref(find_remote_branch(refs, option_branch));
562 if (!remote_head && option_branch)
563 warning(_("Could not find remote branch %s to clone."),
564 option_branch);
565 else {
566 get_fetch_map(remote_head, refspec, &tail, 0);
568 /* if --branch=tag, pull the requested tag explicitly */
569 get_fetch_map(remote_head, tag_refspec, &tail, 0);
571 } else
572 get_fetch_map(refs, refspec, &tail, 0);
574 if (!option_mirror && !option_single_branch && !option_no_tags)
575 get_fetch_map(refs, tag_refspec, &tail, 0);
577 return local_refs;
580 static void write_remote_refs(const struct ref *local_refs)
582 const struct ref *r;
584 struct ref_transaction *t;
585 struct strbuf err = STRBUF_INIT;
587 t = ref_transaction_begin(&err);
588 if (!t)
589 die("%s", err.buf);
591 for (r = local_refs; r; r = r->next) {
592 if (!r->peer_ref)
593 continue;
594 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
595 0, NULL, &err))
596 die("%s", err.buf);
599 if (initial_ref_transaction_commit(t, &err))
600 die("%s", err.buf);
602 strbuf_release(&err);
603 ref_transaction_free(t);
606 static void write_followtags(const struct ref *refs, const char *msg)
608 const struct ref *ref;
609 for (ref = refs; ref; ref = ref->next) {
610 if (!starts_with(ref->name, "refs/tags/"))
611 continue;
612 if (ends_with(ref->name, "^{}"))
613 continue;
614 if (!has_object_file(&ref->old_oid))
615 continue;
616 update_ref(msg, ref->name, ref->old_oid.hash,
617 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
621 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
623 struct ref **rm = cb_data;
624 struct ref *ref = *rm;
627 * Skip anything missing a peer_ref, which we are not
628 * actually going to write a ref for.
630 while (ref && !ref->peer_ref)
631 ref = ref->next;
632 /* Returning -1 notes "end of list" to the caller. */
633 if (!ref)
634 return -1;
636 hashcpy(sha1, ref->old_oid.hash);
637 *rm = ref->next;
638 return 0;
641 static void update_remote_refs(const struct ref *refs,
642 const struct ref *mapped_refs,
643 const struct ref *remote_head_points_at,
644 const char *branch_top,
645 const char *msg,
646 struct transport *transport,
647 int check_connectivity)
649 const struct ref *rm = mapped_refs;
651 if (check_connectivity) {
652 struct check_connected_options opt = CHECK_CONNECTED_INIT;
654 opt.transport = transport;
655 opt.progress = transport->progress;
657 if (check_connected(iterate_ref_map, &rm, &opt))
658 die(_("remote did not send all necessary objects"));
661 if (refs) {
662 write_remote_refs(mapped_refs);
663 if (option_single_branch && !option_no_tags)
664 write_followtags(refs, msg);
667 if (remote_head_points_at && !option_bare) {
668 struct strbuf head_ref = STRBUF_INIT;
669 strbuf_addstr(&head_ref, branch_top);
670 strbuf_addstr(&head_ref, "HEAD");
671 if (create_symref(head_ref.buf,
672 remote_head_points_at->peer_ref->name,
673 msg) < 0)
674 die(_("unable to update %s"), head_ref.buf);
675 strbuf_release(&head_ref);
679 static void update_head(const struct ref *our, const struct ref *remote,
680 const char *msg)
682 const char *head;
683 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
684 /* Local default branch link */
685 if (create_symref("HEAD", our->name, NULL) < 0)
686 die(_("unable to update HEAD"));
687 if (!option_bare) {
688 update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
689 UPDATE_REFS_DIE_ON_ERR);
690 install_branch_config(0, head, option_origin, our->name);
692 } else if (our) {
693 struct commit *c = lookup_commit_reference(&our->old_oid);
694 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
695 update_ref(msg, "HEAD", c->object.oid.hash,
696 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
697 } else if (remote) {
699 * We know remote HEAD points to a non-branch, or
700 * HEAD points to a branch but we don't know which one.
701 * Detach HEAD in all these cases.
703 update_ref(msg, "HEAD", remote->old_oid.hash,
704 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
708 static int checkout(int submodule_progress)
710 struct object_id oid;
711 char *head;
712 struct lock_file *lock_file;
713 struct unpack_trees_options opts;
714 struct tree *tree;
715 struct tree_desc t;
716 int err = 0;
718 if (option_no_checkout)
719 return 0;
721 head = resolve_refdup("HEAD", RESOLVE_REF_READING, oid.hash, NULL);
722 if (!head) {
723 warning(_("remote HEAD refers to nonexistent ref, "
724 "unable to checkout.\n"));
725 return 0;
727 if (!strcmp(head, "HEAD")) {
728 if (advice_detached_head)
729 detach_advice(oid_to_hex(&oid));
730 } else {
731 if (!starts_with(head, "refs/heads/"))
732 die(_("HEAD not found below refs/heads!"));
734 free(head);
736 /* We need to be in the new work tree for the checkout */
737 setup_work_tree();
739 lock_file = xcalloc(1, sizeof(struct lock_file));
740 hold_locked_index(lock_file, LOCK_DIE_ON_ERROR);
742 memset(&opts, 0, sizeof opts);
743 opts.update = 1;
744 opts.merge = 1;
745 opts.fn = oneway_merge;
746 opts.verbose_update = (option_verbosity >= 0);
747 opts.src_index = &the_index;
748 opts.dst_index = &the_index;
750 tree = parse_tree_indirect(&oid);
751 parse_tree(tree);
752 init_tree_desc(&t, tree->buffer, tree->size);
753 if (unpack_trees(1, &t, &opts) < 0)
754 die(_("unable to checkout working tree"));
756 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
757 die(_("unable to write new index file"));
759 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
760 oid_to_hex(&oid), "1", NULL);
762 if (!err && (option_recurse_submodules.nr > 0)) {
763 struct argv_array args = ARGV_ARRAY_INIT;
764 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
766 if (option_shallow_submodules == 1)
767 argv_array_push(&args, "--depth=1");
769 if (max_jobs != -1)
770 argv_array_pushf(&args, "--jobs=%d", max_jobs);
772 if (submodule_progress)
773 argv_array_push(&args, "--progress");
775 if (option_verbosity < 0)
776 argv_array_push(&args, "--quiet");
778 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
779 argv_array_clear(&args);
782 return err;
785 static int write_one_config(const char *key, const char *value, void *data)
787 return git_config_set_multivar_gently(key,
788 value ? value : "true",
789 CONFIG_REGEX_NONE, 0);
792 static void write_config(struct string_list *config)
794 int i;
796 for (i = 0; i < config->nr; i++) {
797 if (git_config_parse_parameter(config->items[i].string,
798 write_one_config, NULL) < 0)
799 die(_("unable to write parameters to config file"));
803 static void write_refspec_config(const char *src_ref_prefix,
804 const struct ref *our_head_points_at,
805 const struct ref *remote_head_points_at,
806 struct strbuf *branch_top)
808 struct strbuf key = STRBUF_INIT;
809 struct strbuf value = STRBUF_INIT;
811 if (option_mirror || !option_bare) {
812 if (option_single_branch && !option_mirror) {
813 if (option_branch) {
814 if (starts_with(our_head_points_at->name, "refs/tags/"))
815 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
816 our_head_points_at->name);
817 else
818 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
819 branch_top->buf, option_branch);
820 } else if (remote_head_points_at) {
821 const char *head = remote_head_points_at->name;
822 if (!skip_prefix(head, "refs/heads/", &head))
823 die("BUG: remote HEAD points at non-head?");
825 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
826 branch_top->buf, head);
829 * otherwise, the next "git fetch" will
830 * simply fetch from HEAD without updating
831 * any remote-tracking branch, which is what
832 * we want.
834 } else {
835 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
837 /* Configure the remote */
838 if (value.len) {
839 strbuf_addf(&key, "remote.%s.fetch", option_origin);
840 git_config_set_multivar(key.buf, value.buf, "^$", 0);
841 strbuf_reset(&key);
843 if (option_mirror) {
844 strbuf_addf(&key, "remote.%s.mirror", option_origin);
845 git_config_set(key.buf, "true");
846 strbuf_reset(&key);
851 strbuf_release(&key);
852 strbuf_release(&value);
855 static void dissociate_from_references(void)
857 static const char* argv[] = { "repack", "-a", "-d", NULL };
858 char *alternates = git_pathdup("objects/info/alternates");
860 if (!access(alternates, F_OK)) {
861 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
862 die(_("cannot repack to clean up"));
863 if (unlink(alternates) && errno != ENOENT)
864 die_errno(_("cannot unlink temporary alternates file"));
866 free(alternates);
869 int cmd_clone(int argc, const char **argv, const char *prefix)
871 int is_bundle = 0, is_local;
872 struct stat buf;
873 const char *repo_name, *repo, *work_tree, *git_dir;
874 char *path, *dir;
875 int dest_exists;
876 const struct ref *refs, *remote_head;
877 const struct ref *remote_head_points_at;
878 const struct ref *our_head_points_at;
879 struct ref *mapped_refs;
880 const struct ref *ref;
881 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
882 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
883 struct transport *transport = NULL;
884 const char *src_ref_prefix = "refs/heads/";
885 struct remote *remote;
886 int err = 0, complete_refs_before_fetch = 1;
887 int submodule_progress;
889 struct refspec *refspec;
890 const char *fetch_pattern;
892 fetch_if_missing = 0;
894 packet_trace_identity("clone");
895 argc = parse_options(argc, argv, prefix, builtin_clone_options,
896 builtin_clone_usage, 0);
898 if (argc > 2)
899 usage_msg_opt(_("Too many arguments."),
900 builtin_clone_usage, builtin_clone_options);
902 if (argc == 0)
903 usage_msg_opt(_("You must specify a repository to clone."),
904 builtin_clone_usage, builtin_clone_options);
906 if (option_depth || option_since || option_not.nr)
907 deepen = 1;
908 if (option_single_branch == -1)
909 option_single_branch = deepen ? 1 : 0;
911 if (option_mirror)
912 option_bare = 1;
914 if (option_bare) {
915 if (option_origin)
916 die(_("--bare and --origin %s options are incompatible."),
917 option_origin);
918 if (real_git_dir)
919 die(_("--bare and --separate-git-dir are incompatible."));
920 option_no_checkout = 1;
923 if (!option_origin)
924 option_origin = "origin";
926 repo_name = argv[0];
928 path = get_repo_path(repo_name, &is_bundle);
929 if (path)
930 repo = absolute_pathdup(repo_name);
931 else if (!strchr(repo_name, ':'))
932 die(_("repository '%s' does not exist"), repo_name);
933 else
934 repo = repo_name;
936 /* no need to be strict, transport_set_option() will validate it again */
937 if (option_depth && atoi(option_depth) < 1)
938 die(_("depth %s is not a positive number"), option_depth);
940 if (argc == 2)
941 dir = xstrdup(argv[1]);
942 else
943 dir = guess_dir_name(repo_name, is_bundle, option_bare);
944 strip_trailing_slashes(dir);
946 dest_exists = !stat(dir, &buf);
947 if (dest_exists && !is_empty_dir(dir))
948 die(_("destination path '%s' already exists and is not "
949 "an empty directory."), dir);
951 strbuf_addf(&reflog_msg, "clone: from %s", repo);
953 if (option_bare)
954 work_tree = NULL;
955 else {
956 work_tree = getenv("GIT_WORK_TREE");
957 if (work_tree && !stat(work_tree, &buf))
958 die(_("working tree '%s' already exists."), work_tree);
961 if (option_bare || work_tree)
962 git_dir = xstrdup(dir);
963 else {
964 work_tree = dir;
965 git_dir = mkpathdup("%s/.git", dir);
968 atexit(remove_junk);
969 sigchain_push_common(remove_junk_on_signal);
971 if (!option_bare) {
972 if (safe_create_leading_directories_const(work_tree) < 0)
973 die_errno(_("could not create leading directories of '%s'"),
974 work_tree);
975 if (!dest_exists && mkdir(work_tree, 0777))
976 die_errno(_("could not create work tree dir '%s'"),
977 work_tree);
978 junk_work_tree = work_tree;
979 set_git_work_tree(work_tree);
982 junk_git_dir = real_git_dir ? real_git_dir : git_dir;
983 if (safe_create_leading_directories_const(git_dir) < 0)
984 die(_("could not create leading directories of '%s'"), git_dir);
986 if (0 <= option_verbosity) {
987 if (option_bare)
988 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
989 else
990 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
993 if (option_recurse_submodules.nr > 0) {
994 struct string_list_item *item;
995 struct strbuf sb = STRBUF_INIT;
997 /* remove duplicates */
998 string_list_sort(&option_recurse_submodules);
999 string_list_remove_duplicates(&option_recurse_submodules, 0);
1002 * NEEDSWORK: In a multi-working-tree world, this needs to be
1003 * set in the per-worktree config.
1005 for_each_string_list_item(item, &option_recurse_submodules) {
1006 strbuf_addf(&sb, "submodule.active=%s",
1007 item->string);
1008 string_list_append(&option_config,
1009 strbuf_detach(&sb, NULL));
1012 if (option_required_reference.nr &&
1013 option_optional_reference.nr)
1014 die(_("clone --recursive is not compatible with "
1015 "both --reference and --reference-if-able"));
1016 else if (option_required_reference.nr) {
1017 string_list_append(&option_config,
1018 "submodule.alternateLocation=superproject");
1019 string_list_append(&option_config,
1020 "submodule.alternateErrorStrategy=die");
1021 } else if (option_optional_reference.nr) {
1022 string_list_append(&option_config,
1023 "submodule.alternateLocation=superproject");
1024 string_list_append(&option_config,
1025 "submodule.alternateErrorStrategy=info");
1029 init_db(git_dir, real_git_dir, option_template, INIT_DB_QUIET);
1031 if (real_git_dir)
1032 git_dir = real_git_dir;
1034 write_config(&option_config);
1036 git_config(git_default_config, NULL);
1038 if (option_bare) {
1039 if (option_mirror)
1040 src_ref_prefix = "refs/";
1041 strbuf_addstr(&branch_top, src_ref_prefix);
1043 git_config_set("core.bare", "true");
1044 } else {
1045 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
1048 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
1049 strbuf_addf(&key, "remote.%s.url", option_origin);
1050 git_config_set(key.buf, repo);
1051 strbuf_reset(&key);
1053 if (option_no_tags) {
1054 strbuf_addf(&key, "remote.%s.tagOpt", option_origin);
1055 git_config_set(key.buf, "--no-tags");
1056 strbuf_reset(&key);
1059 if (option_required_reference.nr || option_optional_reference.nr)
1060 setup_reference();
1062 fetch_pattern = value.buf;
1063 refspec = parse_fetch_refspec(1, &fetch_pattern);
1065 strbuf_reset(&value);
1067 remote = remote_get(option_origin);
1068 transport = transport_get(remote, remote->url[0]);
1069 transport_set_verbosity(transport, option_verbosity, option_progress);
1070 transport->family = family;
1072 path = get_repo_path(remote->url[0], &is_bundle);
1073 is_local = option_local != 0 && path && !is_bundle;
1074 if (is_local) {
1075 if (option_depth)
1076 warning(_("--depth is ignored in local clones; use file:// instead."));
1077 if (option_since)
1078 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1079 if (option_not.nr)
1080 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1081 if (filter_options.choice)
1082 warning(_("--filter is ignored in local clones; use file:// instead."));
1083 if (!access(mkpath("%s/shallow", path), F_OK)) {
1084 if (option_local > 0)
1085 warning(_("source repository is shallow, ignoring --local"));
1086 is_local = 0;
1089 if (option_local > 0 && !is_local)
1090 warning(_("--local is ignored"));
1091 transport->cloning = 1;
1093 if (!transport->get_refs_list || (!is_local && !transport->fetch))
1094 die(_("Don't know how to clone %s"), transport->url);
1096 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1098 if (option_depth)
1099 transport_set_option(transport, TRANS_OPT_DEPTH,
1100 option_depth);
1101 if (option_since)
1102 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1103 option_since);
1104 if (option_not.nr)
1105 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1106 (const char *)&option_not);
1107 if (option_single_branch)
1108 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1110 if (option_upload_pack)
1111 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1112 option_upload_pack);
1114 if (filter_options.choice) {
1115 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1116 filter_options.filter_spec);
1117 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1120 if (transport->smart_options && !deepen && !filter_options.choice)
1121 transport->smart_options->check_self_contained_and_connected = 1;
1123 refs = transport_get_remote_refs(transport);
1125 if (refs) {
1126 mapped_refs = wanted_peer_refs(refs, refspec);
1128 * transport_get_remote_refs() may return refs with null sha-1
1129 * in mapped_refs (see struct transport->get_refs_list
1130 * comment). In that case we need fetch it early because
1131 * remote_head code below relies on it.
1133 * for normal clones, transport_get_remote_refs() should
1134 * return reliable ref set, we can delay cloning until after
1135 * remote HEAD check.
1137 for (ref = refs; ref; ref = ref->next)
1138 if (is_null_oid(&ref->old_oid)) {
1139 complete_refs_before_fetch = 0;
1140 break;
1143 if (!is_local && !complete_refs_before_fetch)
1144 transport_fetch_refs(transport, mapped_refs);
1146 remote_head = find_ref_by_name(refs, "HEAD");
1147 remote_head_points_at =
1148 guess_remote_head(remote_head, mapped_refs, 0);
1150 if (option_branch) {
1151 our_head_points_at =
1152 find_remote_branch(mapped_refs, option_branch);
1154 if (!our_head_points_at)
1155 die(_("Remote branch %s not found in upstream %s"),
1156 option_branch, option_origin);
1158 else
1159 our_head_points_at = remote_head_points_at;
1161 else {
1162 if (option_branch)
1163 die(_("Remote branch %s not found in upstream %s"),
1164 option_branch, option_origin);
1166 warning(_("You appear to have cloned an empty repository."));
1167 mapped_refs = NULL;
1168 our_head_points_at = NULL;
1169 remote_head_points_at = NULL;
1170 remote_head = NULL;
1171 option_no_checkout = 1;
1172 if (!option_bare)
1173 install_branch_config(0, "master", option_origin,
1174 "refs/heads/master");
1177 write_refspec_config(src_ref_prefix, our_head_points_at,
1178 remote_head_points_at, &branch_top);
1180 if (filter_options.choice)
1181 partial_clone_register("origin", &filter_options);
1183 if (is_local)
1184 clone_local(path, git_dir);
1185 else if (refs && complete_refs_before_fetch)
1186 transport_fetch_refs(transport, mapped_refs);
1188 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1189 branch_top.buf, reflog_msg.buf, transport,
1190 !is_local && !filter_options.choice);
1192 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1195 * We want to show progress for recursive submodule clones iff
1196 * we did so for the main clone. But only the transport knows
1197 * the final decision for this flag, so we need to rescue the value
1198 * before we free the transport.
1200 submodule_progress = transport->progress;
1202 transport_unlock_pack(transport);
1203 transport_disconnect(transport);
1205 if (option_dissociate) {
1206 close_all_packs();
1207 dissociate_from_references();
1210 junk_mode = JUNK_LEAVE_REPO;
1211 fetch_if_missing = 1;
1212 err = checkout(submodule_progress);
1214 strbuf_release(&reflog_msg);
1215 strbuf_release(&branch_top);
1216 strbuf_release(&key);
1217 strbuf_release(&value);
1218 junk_mode = JUNK_LEAVE_ALL;
1220 free(refspec);
1221 return err;