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