clone: do not let --depth imply --shallow-submodules
[git/git.git] / builtin / clone.c
1 /*
2 * Builtin "git clone"
3 *
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
7 *
8 * Clone a repository into a different directory that does not yet exist.
9 */
10
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"
27
28 /*
29 * Overall FIXMEs:
30 * - respect DB_ENVIRONMENT for .git/objects.
31 *
32 * Implementation notes:
33 * - dropping use-separate-remote and no-separate-remote compatibility
34 *
35 */
36 static const char * const builtin_clone_usage[] = {
37 N_("git clone [<options>] [--] <repo> [<dir>]"),
38 NULL
39 };
40
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 int option_shallow_submodules;
44 static char *option_template, *option_depth;
45 static char *option_origin = NULL;
46 static char *option_branch = NULL;
47 static const char *real_git_dir;
48 static char *option_upload_pack = "git-upload-pack";
49 static int option_verbosity;
50 static int option_progress = -1;
51 static struct string_list option_config;
52 static struct string_list option_reference;
53 static int option_dissociate;
54 static int max_jobs = -1;
55
56 static struct option builtin_clone_options[] = {
57 OPT__VERBOSITY(&option_verbosity),
58 OPT_BOOL(0, "progress", &option_progress,
59 N_("force progress reporting")),
60 OPT_BOOL('n', "no-checkout", &option_no_checkout,
61 N_("don't create a checkout")),
62 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
63 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
64 N_("create a bare repository")),
65 OPT_BOOL(0, "mirror", &option_mirror,
66 N_("create a mirror repository (implies bare)")),
67 OPT_BOOL('l', "local", &option_local,
68 N_("to clone from a local repository")),
69 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
70 N_("don't use local hardlinks, always copy")),
71 OPT_BOOL('s', "shared", &option_shared,
72 N_("setup as shared repository")),
73 OPT_BOOL(0, "recursive", &option_recursive,
74 N_("initialize submodules in the clone")),
75 OPT_BOOL(0, "recurse-submodules", &option_recursive,
76 N_("initialize submodules in the clone")),
77 OPT_INTEGER('j', "jobs", &max_jobs,
78 N_("number of submodules cloned in parallel")),
79 OPT_STRING(0, "template", &option_template, N_("template-directory"),
80 N_("directory from which templates will be used")),
81 OPT_STRING_LIST(0, "reference", &option_reference, N_("repo"),
82 N_("reference repository")),
83 OPT_BOOL(0, "dissociate", &option_dissociate,
84 N_("use --reference only while cloning")),
85 OPT_STRING('o', "origin", &option_origin, N_("name"),
86 N_("use <name> instead of 'origin' to track upstream")),
87 OPT_STRING('b', "branch", &option_branch, N_("branch"),
88 N_("checkout <branch> instead of the remote's HEAD")),
89 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
90 N_("path to git-upload-pack on the remote")),
91 OPT_STRING(0, "depth", &option_depth, N_("depth"),
92 N_("create a shallow clone of that depth")),
93 OPT_BOOL(0, "single-branch", &option_single_branch,
94 N_("clone only one branch, HEAD or --branch")),
95 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
96 N_("any cloned submodules will be shallow")),
97 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
98 N_("separate git dir from working tree")),
99 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
100 N_("set config inside the new repository")),
101 OPT_END()
102 };
103
104 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
105 {
106 static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
107 static char *bundle_suffix[] = { ".bundle", "" };
108 size_t baselen = path->len;
109 struct stat st;
110 int i;
111
112 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
113 strbuf_setlen(path, baselen);
114 strbuf_addstr(path, suffix[i]);
115 if (stat(path->buf, &st))
116 continue;
117 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
118 *is_bundle = 0;
119 return path->buf;
120 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
121 /* Is it a "gitfile"? */
122 char signature[8];
123 const char *dst;
124 int len, fd = open(path->buf, O_RDONLY);
125 if (fd < 0)
126 continue;
127 len = read_in_full(fd, signature, 8);
128 close(fd);
129 if (len != 8 || strncmp(signature, "gitdir: ", 8))
130 continue;
131 dst = read_gitfile(path->buf);
132 if (dst) {
133 *is_bundle = 0;
134 return dst;
135 }
136 }
137 }
138
139 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
140 strbuf_setlen(path, baselen);
141 strbuf_addstr(path, bundle_suffix[i]);
142 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
143 *is_bundle = 1;
144 return path->buf;
145 }
146 }
147
148 return NULL;
149 }
150
151 static char *get_repo_path(const char *repo, int *is_bundle)
152 {
153 struct strbuf path = STRBUF_INIT;
154 const char *raw;
155 char *canon;
156
157 strbuf_addstr(&path, repo);
158 raw = get_repo_path_1(&path, is_bundle);
159 canon = raw ? xstrdup(absolute_path(raw)) : NULL;
160 strbuf_release(&path);
161 return canon;
162 }
163
164 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
165 {
166 const char *end = repo + strlen(repo), *start, *ptr;
167 size_t len;
168 char *dir;
169
170 /*
171 * Skip scheme.
172 */
173 start = strstr(repo, "://");
174 if (start == NULL)
175 start = repo;
176 else
177 start += 3;
178
179 /*
180 * Skip authentication data. The stripping does happen
181 * greedily, such that we strip up to the last '@' inside
182 * the host part.
183 */
184 for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
185 if (*ptr == '@')
186 start = ptr + 1;
187 }
188
189 /*
190 * Strip trailing spaces, slashes and /.git
191 */
192 while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
193 end--;
194 if (end - start > 5 && is_dir_sep(end[-5]) &&
195 !strncmp(end - 4, ".git", 4)) {
196 end -= 5;
197 while (start < end && is_dir_sep(end[-1]))
198 end--;
199 }
200
201 /*
202 * Strip trailing port number if we've got only a
203 * hostname (that is, there is no dir separator but a
204 * colon). This check is required such that we do not
205 * strip URI's like '/foo/bar:2222.git', which should
206 * result in a dir '2222' being guessed due to backwards
207 * compatibility.
208 */
209 if (memchr(start, '/', end - start) == NULL
210 && memchr(start, ':', end - start) != NULL) {
211 ptr = end;
212 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
213 ptr--;
214 if (start < ptr && ptr[-1] == ':')
215 end = ptr - 1;
216 }
217
218 /*
219 * Find last component. To remain backwards compatible we
220 * also regard colons as path separators, such that
221 * cloning a repository 'foo:bar.git' would result in a
222 * directory 'bar' being guessed.
223 */
224 ptr = end;
225 while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
226 ptr--;
227 start = ptr;
228
229 /*
230 * Strip .{bundle,git}.
231 */
232 len = end - start;
233 strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
234
235 if (!len || (len == 1 && *start == '/'))
236 die("No directory name could be guessed.\n"
237 "Please specify a directory on the command line");
238
239 if (is_bare)
240 dir = xstrfmt("%.*s.git", (int)len, start);
241 else
242 dir = xstrndup(start, len);
243 /*
244 * Replace sequences of 'control' characters and whitespace
245 * with one ascii space, remove leading and trailing spaces.
246 */
247 if (*dir) {
248 char *out = dir;
249 int prev_space = 1 /* strip leading whitespace */;
250 for (end = dir; *end; ++end) {
251 char ch = *end;
252 if ((unsigned char)ch < '\x20')
253 ch = '\x20';
254 if (isspace(ch)) {
255 if (prev_space)
256 continue;
257 prev_space = 1;
258 } else
259 prev_space = 0;
260 *out++ = ch;
261 }
262 *out = '\0';
263 if (out > dir && prev_space)
264 out[-1] = '\0';
265 }
266 return dir;
267 }
268
269 static void strip_trailing_slashes(char *dir)
270 {
271 char *end = dir + strlen(dir);
272
273 while (dir < end - 1 && is_dir_sep(end[-1]))
274 end--;
275 *end = '\0';
276 }
277
278 static int add_one_reference(struct string_list_item *item, void *cb_data)
279 {
280 char *ref_git;
281 const char *repo;
282 struct strbuf alternate = STRBUF_INIT;
283
284 /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
285 ref_git = xstrdup(real_path(item->string));
286
287 repo = read_gitfile(ref_git);
288 if (!repo)
289 repo = read_gitfile(mkpath("%s/.git", ref_git));
290 if (repo) {
291 free(ref_git);
292 ref_git = xstrdup(repo);
293 }
294
295 if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
296 char *ref_git_git = mkpathdup("%s/.git", ref_git);
297 free(ref_git);
298 ref_git = ref_git_git;
299 } else if (!is_directory(mkpath("%s/objects", ref_git))) {
300 struct strbuf sb = STRBUF_INIT;
301 if (get_common_dir(&sb, ref_git))
302 die(_("reference repository '%s' as a linked checkout is not supported yet."),
303 item->string);
304 die(_("reference repository '%s' is not a local repository."),
305 item->string);
306 }
307
308 if (!access(mkpath("%s/shallow", ref_git), F_OK))
309 die(_("reference repository '%s' is shallow"), item->string);
310
311 if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
312 die(_("reference repository '%s' is grafted"), item->string);
313
314 strbuf_addf(&alternate, "%s/objects", ref_git);
315 add_to_alternates_file(alternate.buf);
316 strbuf_release(&alternate);
317 free(ref_git);
318 return 0;
319 }
320
321 static void setup_reference(void)
322 {
323 for_each_string_list(&option_reference, add_one_reference, NULL);
324 }
325
326 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
327 const char *src_repo)
328 {
329 /*
330 * Read from the source objects/info/alternates file
331 * and copy the entries to corresponding file in the
332 * destination repository with add_to_alternates_file().
333 * Both src and dst have "$path/objects/info/alternates".
334 *
335 * Instead of copying bit-for-bit from the original,
336 * we need to append to existing one so that the already
337 * created entry via "clone -s" is not lost, and also
338 * to turn entries with paths relative to the original
339 * absolute, so that they can be used in the new repository.
340 */
341 FILE *in = fopen(src->buf, "r");
342 struct strbuf line = STRBUF_INIT;
343
344 while (strbuf_getline(&line, in, '\n') != EOF) {
345 char *abs_path;
346 if (!line.len || line.buf[0] == '#')
347 continue;
348 if (is_absolute_path(line.buf)) {
349 add_to_alternates_file(line.buf);
350 continue;
351 }
352 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
353 normalize_path_copy(abs_path, abs_path);
354 add_to_alternates_file(abs_path);
355 free(abs_path);
356 }
357 strbuf_release(&line);
358 fclose(in);
359 }
360
361 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
362 const char *src_repo, int src_baselen)
363 {
364 struct dirent *de;
365 struct stat buf;
366 int src_len, dest_len;
367 DIR *dir;
368
369 dir = opendir(src->buf);
370 if (!dir)
371 die_errno(_("failed to open '%s'"), src->buf);
372
373 if (mkdir(dest->buf, 0777)) {
374 if (errno != EEXIST)
375 die_errno(_("failed to create directory '%s'"), dest->buf);
376 else if (stat(dest->buf, &buf))
377 die_errno(_("failed to stat '%s'"), dest->buf);
378 else if (!S_ISDIR(buf.st_mode))
379 die(_("%s exists and is not a directory"), dest->buf);
380 }
381
382 strbuf_addch(src, '/');
383 src_len = src->len;
384 strbuf_addch(dest, '/');
385 dest_len = dest->len;
386
387 while ((de = readdir(dir)) != NULL) {
388 strbuf_setlen(src, src_len);
389 strbuf_addstr(src, de->d_name);
390 strbuf_setlen(dest, dest_len);
391 strbuf_addstr(dest, de->d_name);
392 if (stat(src->buf, &buf)) {
393 warning (_("failed to stat %s\n"), src->buf);
394 continue;
395 }
396 if (S_ISDIR(buf.st_mode)) {
397 if (de->d_name[0] != '.')
398 copy_or_link_directory(src, dest,
399 src_repo, src_baselen);
400 continue;
401 }
402
403 /* Files that cannot be copied bit-for-bit... */
404 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
405 copy_alternates(src, dest, src_repo);
406 continue;
407 }
408
409 if (unlink(dest->buf) && errno != ENOENT)
410 die_errno(_("failed to unlink '%s'"), dest->buf);
411 if (!option_no_hardlinks) {
412 if (!link(src->buf, dest->buf))
413 continue;
414 if (option_local > 0)
415 die_errno(_("failed to create link '%s'"), dest->buf);
416 option_no_hardlinks = 1;
417 }
418 if (copy_file_with_time(dest->buf, src->buf, 0666))
419 die_errno(_("failed to copy file to '%s'"), dest->buf);
420 }
421 closedir(dir);
422 }
423
424 static void clone_local(const char *src_repo, const char *dest_repo)
425 {
426 if (option_shared) {
427 struct strbuf alt = STRBUF_INIT;
428 strbuf_addf(&alt, "%s/objects", src_repo);
429 add_to_alternates_file(alt.buf);
430 strbuf_release(&alt);
431 } else {
432 struct strbuf src = STRBUF_INIT;
433 struct strbuf dest = STRBUF_INIT;
434 get_common_dir(&src, src_repo);
435 get_common_dir(&dest, dest_repo);
436 strbuf_addstr(&src, "/objects");
437 strbuf_addstr(&dest, "/objects");
438 copy_or_link_directory(&src, &dest, src_repo, src.len);
439 strbuf_release(&src);
440 strbuf_release(&dest);
441 }
442
443 if (0 <= option_verbosity)
444 fprintf(stderr, _("done.\n"));
445 }
446
447 static const char *junk_work_tree;
448 static const char *junk_git_dir;
449 static enum {
450 JUNK_LEAVE_NONE,
451 JUNK_LEAVE_REPO,
452 JUNK_LEAVE_ALL
453 } junk_mode = JUNK_LEAVE_NONE;
454
455 static const char junk_leave_repo_msg[] =
456 N_("Clone succeeded, but checkout failed.\n"
457 "You can inspect what was checked out with 'git status'\n"
458 "and retry the checkout with 'git checkout -f HEAD'\n");
459
460 static void remove_junk(void)
461 {
462 struct strbuf sb = STRBUF_INIT;
463
464 switch (junk_mode) {
465 case JUNK_LEAVE_REPO:
466 warning("%s", _(junk_leave_repo_msg));
467 /* fall-through */
468 case JUNK_LEAVE_ALL:
469 return;
470 default:
471 /* proceed to removal */
472 break;
473 }
474
475 if (junk_git_dir) {
476 strbuf_addstr(&sb, junk_git_dir);
477 remove_dir_recursively(&sb, 0);
478 strbuf_reset(&sb);
479 }
480 if (junk_work_tree) {
481 strbuf_addstr(&sb, junk_work_tree);
482 remove_dir_recursively(&sb, 0);
483 strbuf_reset(&sb);
484 }
485 }
486
487 static void remove_junk_on_signal(int signo)
488 {
489 remove_junk();
490 sigchain_pop(signo);
491 raise(signo);
492 }
493
494 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
495 {
496 struct ref *ref;
497 struct strbuf head = STRBUF_INIT;
498 strbuf_addstr(&head, "refs/heads/");
499 strbuf_addstr(&head, branch);
500 ref = find_ref_by_name(refs, head.buf);
501 strbuf_release(&head);
502
503 if (ref)
504 return ref;
505
506 strbuf_addstr(&head, "refs/tags/");
507 strbuf_addstr(&head, branch);
508 ref = find_ref_by_name(refs, head.buf);
509 strbuf_release(&head);
510
511 return ref;
512 }
513
514 static struct ref *wanted_peer_refs(const struct ref *refs,
515 struct refspec *refspec)
516 {
517 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
518 struct ref *local_refs = head;
519 struct ref **tail = head ? &head->next : &local_refs;
520
521 if (option_single_branch) {
522 struct ref *remote_head = NULL;
523
524 if (!option_branch)
525 remote_head = guess_remote_head(head, refs, 0);
526 else {
527 local_refs = NULL;
528 tail = &local_refs;
529 remote_head = copy_ref(find_remote_branch(refs, option_branch));
530 }
531
532 if (!remote_head && option_branch)
533 warning(_("Could not find remote branch %s to clone."),
534 option_branch);
535 else {
536 get_fetch_map(remote_head, refspec, &tail, 0);
537
538 /* if --branch=tag, pull the requested tag explicitly */
539 get_fetch_map(remote_head, tag_refspec, &tail, 0);
540 }
541 } else
542 get_fetch_map(refs, refspec, &tail, 0);
543
544 if (!option_mirror && !option_single_branch)
545 get_fetch_map(refs, tag_refspec, &tail, 0);
546
547 return local_refs;
548 }
549
550 static void write_remote_refs(const struct ref *local_refs)
551 {
552 const struct ref *r;
553
554 struct ref_transaction *t;
555 struct strbuf err = STRBUF_INIT;
556
557 t = ref_transaction_begin(&err);
558 if (!t)
559 die("%s", err.buf);
560
561 for (r = local_refs; r; r = r->next) {
562 if (!r->peer_ref)
563 continue;
564 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
565 0, NULL, &err))
566 die("%s", err.buf);
567 }
568
569 if (initial_ref_transaction_commit(t, &err))
570 die("%s", err.buf);
571
572 strbuf_release(&err);
573 ref_transaction_free(t);
574 }
575
576 static void write_followtags(const struct ref *refs, const char *msg)
577 {
578 const struct ref *ref;
579 for (ref = refs; ref; ref = ref->next) {
580 if (!starts_with(ref->name, "refs/tags/"))
581 continue;
582 if (ends_with(ref->name, "^{}"))
583 continue;
584 if (!has_object_file(&ref->old_oid))
585 continue;
586 update_ref(msg, ref->name, ref->old_oid.hash,
587 NULL, 0, UPDATE_REFS_DIE_ON_ERR);
588 }
589 }
590
591 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
592 {
593 struct ref **rm = cb_data;
594 struct ref *ref = *rm;
595
596 /*
597 * Skip anything missing a peer_ref, which we are not
598 * actually going to write a ref for.
599 */
600 while (ref && !ref->peer_ref)
601 ref = ref->next;
602 /* Returning -1 notes "end of list" to the caller. */
603 if (!ref)
604 return -1;
605
606 hashcpy(sha1, ref->old_oid.hash);
607 *rm = ref->next;
608 return 0;
609 }
610
611 static void update_remote_refs(const struct ref *refs,
612 const struct ref *mapped_refs,
613 const struct ref *remote_head_points_at,
614 const char *branch_top,
615 const char *msg,
616 struct transport *transport,
617 int check_connectivity)
618 {
619 const struct ref *rm = mapped_refs;
620
621 if (check_connectivity) {
622 if (transport->progress)
623 fprintf(stderr, _("Checking connectivity... "));
624 if (check_everything_connected_with_transport(iterate_ref_map,
625 0, &rm, transport))
626 die(_("remote did not send all necessary objects"));
627 if (transport->progress)
628 fprintf(stderr, _("done.\n"));
629 }
630
631 if (refs) {
632 write_remote_refs(mapped_refs);
633 if (option_single_branch)
634 write_followtags(refs, msg);
635 }
636
637 if (remote_head_points_at && !option_bare) {
638 struct strbuf head_ref = STRBUF_INIT;
639 strbuf_addstr(&head_ref, branch_top);
640 strbuf_addstr(&head_ref, "HEAD");
641 create_symref(head_ref.buf,
642 remote_head_points_at->peer_ref->name,
643 msg);
644 }
645 }
646
647 static void update_head(const struct ref *our, const struct ref *remote,
648 const char *msg)
649 {
650 const char *head;
651 if (our && skip_prefix(our->name, "refs/heads/", &head)) {
652 /* Local default branch link */
653 create_symref("HEAD", our->name, NULL);
654 if (!option_bare) {
655 update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
656 UPDATE_REFS_DIE_ON_ERR);
657 install_branch_config(0, head, option_origin, our->name);
658 }
659 } else if (our) {
660 struct commit *c = lookup_commit_reference(our->old_oid.hash);
661 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
662 update_ref(msg, "HEAD", c->object.oid.hash,
663 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
664 } else if (remote) {
665 /*
666 * We know remote HEAD points to a non-branch, or
667 * HEAD points to a branch but we don't know which one.
668 * Detach HEAD in all these cases.
669 */
670 update_ref(msg, "HEAD", remote->old_oid.hash,
671 NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
672 }
673 }
674
675 static int checkout(void)
676 {
677 unsigned char sha1[20];
678 char *head;
679 struct lock_file *lock_file;
680 struct unpack_trees_options opts;
681 struct tree *tree;
682 struct tree_desc t;
683 int err = 0;
684
685 if (option_no_checkout)
686 return 0;
687
688 head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
689 if (!head) {
690 warning(_("remote HEAD refers to nonexistent ref, "
691 "unable to checkout.\n"));
692 return 0;
693 }
694 if (!strcmp(head, "HEAD")) {
695 if (advice_detached_head)
696 detach_advice(sha1_to_hex(sha1));
697 } else {
698 if (!starts_with(head, "refs/heads/"))
699 die(_("HEAD not found below refs/heads!"));
700 }
701 free(head);
702
703 /* We need to be in the new work tree for the checkout */
704 setup_work_tree();
705
706 lock_file = xcalloc(1, sizeof(struct lock_file));
707 hold_locked_index(lock_file, 1);
708
709 memset(&opts, 0, sizeof opts);
710 opts.update = 1;
711 opts.merge = 1;
712 opts.fn = oneway_merge;
713 opts.verbose_update = (option_verbosity >= 0);
714 opts.src_index = &the_index;
715 opts.dst_index = &the_index;
716
717 tree = parse_tree_indirect(sha1);
718 parse_tree(tree);
719 init_tree_desc(&t, tree->buffer, tree->size);
720 if (unpack_trees(1, &t, &opts) < 0)
721 die(_("unable to checkout working tree"));
722
723 if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
724 die(_("unable to write new index file"));
725
726 err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
727 sha1_to_hex(sha1), "1", NULL);
728
729 if (!err && option_recursive) {
730 struct argv_array args = ARGV_ARRAY_INIT;
731 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
732
733 if (option_shallow_submodules == 1)
734 argv_array_push(&args, "--depth=1");
735
736 if (max_jobs != -1)
737 argv_array_pushf(&args, "--jobs=%d", max_jobs);
738
739 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
740 argv_array_clear(&args);
741 }
742
743 return err;
744 }
745
746 static int write_one_config(const char *key, const char *value, void *data)
747 {
748 return git_config_set_multivar(key, value ? value : "true", "^$", 0);
749 }
750
751 static void write_config(struct string_list *config)
752 {
753 int i;
754
755 for (i = 0; i < config->nr; i++) {
756 if (git_config_parse_parameter(config->items[i].string,
757 write_one_config, NULL) < 0)
758 die("unable to write parameters to config file");
759 }
760 }
761
762 static void write_refspec_config(const char *src_ref_prefix,
763 const struct ref *our_head_points_at,
764 const struct ref *remote_head_points_at,
765 struct strbuf *branch_top)
766 {
767 struct strbuf key = STRBUF_INIT;
768 struct strbuf value = STRBUF_INIT;
769
770 if (option_mirror || !option_bare) {
771 if (option_single_branch && !option_mirror) {
772 if (option_branch) {
773 if (starts_with(our_head_points_at->name, "refs/tags/"))
774 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
775 our_head_points_at->name);
776 else
777 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
778 branch_top->buf, option_branch);
779 } else if (remote_head_points_at) {
780 const char *head = remote_head_points_at->name;
781 if (!skip_prefix(head, "refs/heads/", &head))
782 die("BUG: remote HEAD points at non-head?");
783
784 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
785 branch_top->buf, head);
786 }
787 /*
788 * otherwise, the next "git fetch" will
789 * simply fetch from HEAD without updating
790 * any remote-tracking branch, which is what
791 * we want.
792 */
793 } else {
794 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
795 }
796 /* Configure the remote */
797 if (value.len) {
798 strbuf_addf(&key, "remote.%s.fetch", option_origin);
799 git_config_set_multivar(key.buf, value.buf, "^$", 0);
800 strbuf_reset(&key);
801
802 if (option_mirror) {
803 strbuf_addf(&key, "remote.%s.mirror", option_origin);
804 git_config_set(key.buf, "true");
805 strbuf_reset(&key);
806 }
807 }
808 }
809
810 strbuf_release(&key);
811 strbuf_release(&value);
812 }
813
814 static void dissociate_from_references(void)
815 {
816 static const char* argv[] = { "repack", "-a", "-d", NULL };
817 char *alternates = git_pathdup("objects/info/alternates");
818
819 if (!access(alternates, F_OK)) {
820 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
821 die(_("cannot repack to clean up"));
822 if (unlink(alternates) && errno != ENOENT)
823 die_errno(_("cannot unlink temporary alternates file"));
824 }
825 free(alternates);
826 }
827
828 int cmd_clone(int argc, const char **argv, const char *prefix)
829 {
830 int is_bundle = 0, is_local;
831 struct stat buf;
832 const char *repo_name, *repo, *work_tree, *git_dir;
833 char *path, *dir;
834 int dest_exists;
835 const struct ref *refs, *remote_head;
836 const struct ref *remote_head_points_at;
837 const struct ref *our_head_points_at;
838 struct ref *mapped_refs;
839 const struct ref *ref;
840 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
841 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
842 struct transport *transport = NULL;
843 const char *src_ref_prefix = "refs/heads/";
844 struct remote *remote;
845 int err = 0, complete_refs_before_fetch = 1;
846
847 struct refspec *refspec;
848 const char *fetch_pattern;
849
850 packet_trace_identity("clone");
851 argc = parse_options(argc, argv, prefix, builtin_clone_options,
852 builtin_clone_usage, 0);
853
854 if (argc > 2)
855 usage_msg_opt(_("Too many arguments."),
856 builtin_clone_usage, builtin_clone_options);
857
858 if (argc == 0)
859 usage_msg_opt(_("You must specify a repository to clone."),
860 builtin_clone_usage, builtin_clone_options);
861
862 if (option_single_branch == -1)
863 option_single_branch = option_depth ? 1 : 0;
864
865 if (option_mirror)
866 option_bare = 1;
867
868 if (option_bare) {
869 if (option_origin)
870 die(_("--bare and --origin %s options are incompatible."),
871 option_origin);
872 if (real_git_dir)
873 die(_("--bare and --separate-git-dir are incompatible."));
874 option_no_checkout = 1;
875 }
876
877 if (!option_origin)
878 option_origin = "origin";
879
880 repo_name = argv[0];
881
882 path = get_repo_path(repo_name, &is_bundle);
883 if (path)
884 repo = xstrdup(absolute_path(repo_name));
885 else if (!strchr(repo_name, ':'))
886 die(_("repository '%s' does not exist"), repo_name);
887 else
888 repo = repo_name;
889
890 /* no need to be strict, transport_set_option() will validate it again */
891 if (option_depth && atoi(option_depth) < 1)
892 die(_("depth %s is not a positive number"), option_depth);
893
894 if (argc == 2)
895 dir = xstrdup(argv[1]);
896 else
897 dir = guess_dir_name(repo_name, is_bundle, option_bare);
898 strip_trailing_slashes(dir);
899
900 dest_exists = !stat(dir, &buf);
901 if (dest_exists && !is_empty_dir(dir))
902 die(_("destination path '%s' already exists and is not "
903 "an empty directory."), dir);
904
905 strbuf_addf(&reflog_msg, "clone: from %s", repo);
906
907 if (option_bare)
908 work_tree = NULL;
909 else {
910 work_tree = getenv("GIT_WORK_TREE");
911 if (work_tree && !stat(work_tree, &buf))
912 die(_("working tree '%s' already exists."), work_tree);
913 }
914
915 if (option_bare || work_tree)
916 git_dir = xstrdup(dir);
917 else {
918 work_tree = dir;
919 git_dir = mkpathdup("%s/.git", dir);
920 }
921
922 atexit(remove_junk);
923 sigchain_push_common(remove_junk_on_signal);
924
925 if (!option_bare) {
926 if (safe_create_leading_directories_const(work_tree) < 0)
927 die_errno(_("could not create leading directories of '%s'"),
928 work_tree);
929 if (!dest_exists && mkdir(work_tree, 0777))
930 die_errno(_("could not create work tree dir '%s'"),
931 work_tree);
932 junk_work_tree = work_tree;
933 set_git_work_tree(work_tree);
934 }
935
936 junk_git_dir = git_dir;
937 if (safe_create_leading_directories_const(git_dir) < 0)
938 die(_("could not create leading directories of '%s'"), git_dir);
939
940 set_git_dir_init(git_dir, real_git_dir, 0);
941 if (real_git_dir) {
942 git_dir = real_git_dir;
943 junk_git_dir = real_git_dir;
944 }
945
946 if (0 <= option_verbosity) {
947 if (option_bare)
948 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
949 else
950 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
951 }
952 init_db(option_template, INIT_DB_QUIET);
953 write_config(&option_config);
954
955 git_config(git_default_config, NULL);
956
957 if (option_bare) {
958 if (option_mirror)
959 src_ref_prefix = "refs/";
960 strbuf_addstr(&branch_top, src_ref_prefix);
961
962 git_config_set("core.bare", "true");
963 } else {
964 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
965 }
966
967 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
968 strbuf_addf(&key, "remote.%s.url", option_origin);
969 git_config_set(key.buf, repo);
970 strbuf_reset(&key);
971
972 if (option_reference.nr)
973 setup_reference();
974
975 fetch_pattern = value.buf;
976 refspec = parse_fetch_refspec(1, &fetch_pattern);
977
978 strbuf_reset(&value);
979
980 remote = remote_get(option_origin);
981 transport = transport_get(remote, remote->url[0]);
982 transport_set_verbosity(transport, option_verbosity, option_progress);
983
984 path = get_repo_path(remote->url[0], &is_bundle);
985 is_local = option_local != 0 && path && !is_bundle;
986 if (is_local) {
987 if (option_depth)
988 warning(_("--depth is ignored in local clones; use file:// instead."));
989 if (!access(mkpath("%s/shallow", path), F_OK)) {
990 if (option_local > 0)
991 warning(_("source repository is shallow, ignoring --local"));
992 is_local = 0;
993 }
994 }
995 if (option_local > 0 && !is_local)
996 warning(_("--local is ignored"));
997 transport->cloning = 1;
998
999 if (!transport->get_refs_list || (!is_local && !transport->fetch))
1000 die(_("Don't know how to clone %s"), transport->url);
1001
1002 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1003
1004 if (option_depth)
1005 transport_set_option(transport, TRANS_OPT_DEPTH,
1006 option_depth);
1007 if (option_single_branch)
1008 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1009
1010 if (option_upload_pack)
1011 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1012 option_upload_pack);
1013
1014 if (transport->smart_options && !option_depth)
1015 transport->smart_options->check_self_contained_and_connected = 1;
1016
1017 refs = transport_get_remote_refs(transport);
1018
1019 if (refs) {
1020 mapped_refs = wanted_peer_refs(refs, refspec);
1021 /*
1022 * transport_get_remote_refs() may return refs with null sha-1
1023 * in mapped_refs (see struct transport->get_refs_list
1024 * comment). In that case we need fetch it early because
1025 * remote_head code below relies on it.
1026 *
1027 * for normal clones, transport_get_remote_refs() should
1028 * return reliable ref set, we can delay cloning until after
1029 * remote HEAD check.
1030 */
1031 for (ref = refs; ref; ref = ref->next)
1032 if (is_null_oid(&ref->old_oid)) {
1033 complete_refs_before_fetch = 0;
1034 break;
1035 }
1036
1037 if (!is_local && !complete_refs_before_fetch)
1038 transport_fetch_refs(transport, mapped_refs);
1039
1040 remote_head = find_ref_by_name(refs, "HEAD");
1041 remote_head_points_at =
1042 guess_remote_head(remote_head, mapped_refs, 0);
1043
1044 if (option_branch) {
1045 our_head_points_at =
1046 find_remote_branch(mapped_refs, option_branch);
1047
1048 if (!our_head_points_at)
1049 die(_("Remote branch %s not found in upstream %s"),
1050 option_branch, option_origin);
1051 }
1052 else
1053 our_head_points_at = remote_head_points_at;
1054 }
1055 else {
1056 if (option_branch)
1057 die(_("Remote branch %s not found in upstream %s"),
1058 option_branch, option_origin);
1059
1060 warning(_("You appear to have cloned an empty repository."));
1061 mapped_refs = NULL;
1062 our_head_points_at = NULL;
1063 remote_head_points_at = NULL;
1064 remote_head = NULL;
1065 option_no_checkout = 1;
1066 if (!option_bare)
1067 install_branch_config(0, "master", option_origin,
1068 "refs/heads/master");
1069 }
1070
1071 write_refspec_config(src_ref_prefix, our_head_points_at,
1072 remote_head_points_at, &branch_top);
1073
1074 if (is_local)
1075 clone_local(path, git_dir);
1076 else if (refs && complete_refs_before_fetch)
1077 transport_fetch_refs(transport, mapped_refs);
1078
1079 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1080 branch_top.buf, reflog_msg.buf, transport, !is_local);
1081
1082 update_head(our_head_points_at, remote_head, reflog_msg.buf);
1083
1084 transport_unlock_pack(transport);
1085 transport_disconnect(transport);
1086
1087 if (option_dissociate) {
1088 close_all_packs();
1089 dissociate_from_references();
1090 }
1091
1092 junk_mode = JUNK_LEAVE_REPO;
1093 err = checkout();
1094
1095 strbuf_release(&reflog_msg);
1096 strbuf_release(&branch_top);
1097 strbuf_release(&key);
1098 strbuf_release(&value);
1099 junk_mode = JUNK_LEAVE_ALL;
1100
1101 free(refspec);
1102 return err;
1103 }