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