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