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