clone: add --branch option to select a different HEAD
[git/spearce.git] / builtin-clone.c
blob9d79301b8e373baa0cadccf8dc4ee3f4ed39e8b6
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 "cache.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 "pack-refs.h"
22 #include "sigchain.h"
23 #include "branch.h"
24 #include "remote.h"
25 #include "run-command.h"
28 * Overall FIXMEs:
29 * - respect DB_ENVIRONMENT for .git/objects.
31 * Implementation notes:
32 * - dropping use-separate-remote and no-separate-remote compatibility
35 static const char * const builtin_clone_usage[] = {
36 "git clone [options] [--] <repo> [<dir>]",
37 NULL
40 static int option_quiet, option_no_checkout, option_bare, option_mirror;
41 static int option_local, option_no_hardlinks, option_shared;
42 static char *option_template, *option_reference, *option_depth;
43 static char *option_origin = NULL;
44 static char *option_branch = NULL;
45 static char *option_upload_pack = "git-upload-pack";
46 static int option_verbose;
48 static struct option builtin_clone_options[] = {
49 OPT__QUIET(&option_quiet),
50 OPT__VERBOSE(&option_verbose),
51 OPT_BOOLEAN('n', "no-checkout", &option_no_checkout,
52 "don't create a checkout"),
53 OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"),
54 OPT_BOOLEAN(0, "naked", &option_bare, "create a bare repository"),
55 OPT_BOOLEAN(0, "mirror", &option_mirror,
56 "create a mirror repository (implies bare)"),
57 OPT_BOOLEAN('l', "local", &option_local,
58 "to clone from a local repository"),
59 OPT_BOOLEAN(0, "no-hardlinks", &option_no_hardlinks,
60 "don't use local hardlinks, always copy"),
61 OPT_BOOLEAN('s', "shared", &option_shared,
62 "setup as shared repository"),
63 OPT_STRING(0, "template", &option_template, "path",
64 "path the template repository"),
65 OPT_STRING(0, "reference", &option_reference, "repo",
66 "reference repository"),
67 OPT_STRING('o', "origin", &option_origin, "branch",
68 "use <branch> instead of 'origin' to track upstream"),
69 OPT_STRING('b', "branch", &option_branch, "branch",
70 "checkout <branch> instead of the remote's HEAD"),
71 OPT_STRING('u', "upload-pack", &option_upload_pack, "path",
72 "path to git-upload-pack on the remote"),
73 OPT_STRING(0, "depth", &option_depth, "depth",
74 "create a shallow clone of that depth"),
76 OPT_END()
79 static char *get_repo_path(const char *repo, int *is_bundle)
81 static char *suffix[] = { "/.git", ".git", "" };
82 static char *bundle_suffix[] = { ".bundle", "" };
83 struct stat st;
84 int i;
86 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
87 const char *path;
88 path = mkpath("%s%s", repo, suffix[i]);
89 if (is_directory(path)) {
90 *is_bundle = 0;
91 return xstrdup(make_nonrelative_path(path));
95 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
96 const char *path;
97 path = mkpath("%s%s", repo, bundle_suffix[i]);
98 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
99 *is_bundle = 1;
100 return xstrdup(make_nonrelative_path(path));
104 return NULL;
107 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
109 const char *end = repo + strlen(repo), *start;
110 char *dir;
113 * Strip trailing spaces, slashes and /.git
115 while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
116 end--;
117 if (end - repo > 5 && is_dir_sep(end[-5]) &&
118 !strncmp(end - 4, ".git", 4)) {
119 end -= 5;
120 while (repo < end && is_dir_sep(end[-1]))
121 end--;
125 * Find last component, but be prepared that repo could have
126 * the form "remote.example.com:foo.git", i.e. no slash
127 * in the directory part.
129 start = end;
130 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
131 start--;
134 * Strip .{bundle,git}.
136 if (is_bundle) {
137 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
138 end -= 7;
139 } else {
140 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
141 end -= 4;
144 if (is_bare) {
145 struct strbuf result = STRBUF_INIT;
146 strbuf_addf(&result, "%.*s.git", (int)(end - start), start);
147 dir = strbuf_detach(&result, NULL);
148 } else
149 dir = xstrndup(start, end - start);
151 * Replace sequences of 'control' characters and whitespace
152 * with one ascii space, remove leading and trailing spaces.
154 if (*dir) {
155 char *out = dir;
156 int prev_space = 1 /* strip leading whitespace */;
157 for (end = dir; *end; ++end) {
158 char ch = *end;
159 if ((unsigned char)ch < '\x20')
160 ch = '\x20';
161 if (isspace(ch)) {
162 if (prev_space)
163 continue;
164 prev_space = 1;
165 } else
166 prev_space = 0;
167 *out++ = ch;
169 *out = '\0';
170 if (out > dir && prev_space)
171 out[-1] = '\0';
173 return dir;
176 static void strip_trailing_slashes(char *dir)
178 char *end = dir + strlen(dir);
180 while (dir < end - 1 && is_dir_sep(end[-1]))
181 end--;
182 *end = '\0';
185 static void setup_reference(const char *repo)
187 const char *ref_git;
188 char *ref_git_copy;
190 struct remote *remote;
191 struct transport *transport;
192 const struct ref *extra;
194 ref_git = make_absolute_path(option_reference);
196 if (is_directory(mkpath("%s/.git/objects", ref_git)))
197 ref_git = mkpath("%s/.git", ref_git);
198 else if (!is_directory(mkpath("%s/objects", ref_git)))
199 die("reference repository '%s' is not a local directory.",
200 option_reference);
202 ref_git_copy = xstrdup(ref_git);
204 add_to_alternates_file(ref_git_copy);
206 remote = remote_get(ref_git_copy);
207 transport = transport_get(remote, ref_git_copy);
208 for (extra = transport_get_remote_refs(transport); extra;
209 extra = extra->next)
210 add_extra_ref(extra->name, extra->old_sha1, 0);
212 transport_disconnect(transport);
214 free(ref_git_copy);
217 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest)
219 struct dirent *de;
220 struct stat buf;
221 int src_len, dest_len;
222 DIR *dir;
224 dir = opendir(src->buf);
225 if (!dir)
226 die_errno("failed to open '%s'", src->buf);
228 if (mkdir(dest->buf, 0777)) {
229 if (errno != EEXIST)
230 die_errno("failed to create directory '%s'", dest->buf);
231 else if (stat(dest->buf, &buf))
232 die_errno("failed to stat '%s'", dest->buf);
233 else if (!S_ISDIR(buf.st_mode))
234 die("%s exists and is not a directory", dest->buf);
237 strbuf_addch(src, '/');
238 src_len = src->len;
239 strbuf_addch(dest, '/');
240 dest_len = dest->len;
242 while ((de = readdir(dir)) != NULL) {
243 strbuf_setlen(src, src_len);
244 strbuf_addstr(src, de->d_name);
245 strbuf_setlen(dest, dest_len);
246 strbuf_addstr(dest, de->d_name);
247 if (stat(src->buf, &buf)) {
248 warning ("failed to stat %s\n", src->buf);
249 continue;
251 if (S_ISDIR(buf.st_mode)) {
252 if (de->d_name[0] != '.')
253 copy_or_link_directory(src, dest);
254 continue;
257 if (unlink(dest->buf) && errno != ENOENT)
258 die_errno("failed to unlink '%s'", dest->buf);
259 if (!option_no_hardlinks) {
260 if (!link(src->buf, dest->buf))
261 continue;
262 if (option_local)
263 die_errno("failed to create link '%s'", dest->buf);
264 option_no_hardlinks = 1;
266 if (copy_file(dest->buf, src->buf, 0666))
267 die_errno("failed to copy file to '%s'", dest->buf);
269 closedir(dir);
272 static const struct ref *clone_local(const char *src_repo,
273 const char *dest_repo)
275 const struct ref *ret;
276 struct strbuf src = STRBUF_INIT;
277 struct strbuf dest = STRBUF_INIT;
278 struct remote *remote;
279 struct transport *transport;
281 if (option_shared)
282 add_to_alternates_file(src_repo);
283 else {
284 strbuf_addf(&src, "%s/objects", src_repo);
285 strbuf_addf(&dest, "%s/objects", dest_repo);
286 copy_or_link_directory(&src, &dest);
287 strbuf_release(&src);
288 strbuf_release(&dest);
291 remote = remote_get(src_repo);
292 transport = transport_get(remote, src_repo);
293 ret = transport_get_remote_refs(transport);
294 transport_disconnect(transport);
295 return ret;
298 static const char *junk_work_tree;
299 static const char *junk_git_dir;
300 static pid_t junk_pid;
302 static void remove_junk(void)
304 struct strbuf sb = STRBUF_INIT;
305 if (getpid() != junk_pid)
306 return;
307 if (junk_git_dir) {
308 strbuf_addstr(&sb, junk_git_dir);
309 remove_dir_recursively(&sb, 0);
310 strbuf_reset(&sb);
312 if (junk_work_tree) {
313 strbuf_addstr(&sb, junk_work_tree);
314 remove_dir_recursively(&sb, 0);
315 strbuf_reset(&sb);
319 static void remove_junk_on_signal(int signo)
321 remove_junk();
322 sigchain_pop(signo);
323 raise(signo);
326 static struct ref *write_remote_refs(const struct ref *refs,
327 struct refspec *refspec, const char *reflog)
329 struct ref *local_refs = NULL;
330 struct ref **tail = &local_refs;
331 struct ref *r;
333 get_fetch_map(refs, refspec, &tail, 0);
334 if (!option_mirror)
335 get_fetch_map(refs, tag_refspec, &tail, 0);
337 for (r = local_refs; r; r = r->next)
338 add_extra_ref(r->peer_ref->name, r->old_sha1, 0);
340 pack_refs(PACK_REFS_ALL);
341 clear_extra_refs();
343 return local_refs;
346 int cmd_clone(int argc, const char **argv, const char *prefix)
348 int is_bundle = 0;
349 struct stat buf;
350 const char *repo_name, *repo, *work_tree, *git_dir;
351 char *path, *dir;
352 int dest_exists;
353 const struct ref *refs, *remote_head, *mapped_refs;
354 const struct ref *remote_head_points_at;
355 const struct ref *our_head_points_at;
356 struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
357 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
358 struct transport *transport = NULL;
359 char *src_ref_prefix = "refs/heads/";
360 int err = 0;
362 struct refspec *refspec;
363 const char *fetch_pattern;
365 junk_pid = getpid();
367 argc = parse_options(argc, argv, prefix, builtin_clone_options,
368 builtin_clone_usage, 0);
370 if (argc == 0)
371 die("You must specify a repository to clone.");
373 if (option_mirror)
374 option_bare = 1;
376 if (option_bare) {
377 if (option_origin)
378 die("--bare and --origin %s options are incompatible.",
379 option_origin);
380 option_no_checkout = 1;
383 if (!option_origin)
384 option_origin = "origin";
386 repo_name = argv[0];
388 path = get_repo_path(repo_name, &is_bundle);
389 if (path)
390 repo = xstrdup(make_nonrelative_path(repo_name));
391 else if (!strchr(repo_name, ':'))
392 repo = xstrdup(make_absolute_path(repo_name));
393 else
394 repo = repo_name;
396 if (argc == 2)
397 dir = xstrdup(argv[1]);
398 else
399 dir = guess_dir_name(repo_name, is_bundle, option_bare);
400 strip_trailing_slashes(dir);
402 dest_exists = !stat(dir, &buf);
403 if (dest_exists && !is_empty_dir(dir))
404 die("destination path '%s' already exists and is not "
405 "an empty directory.", dir);
407 strbuf_addf(&reflog_msg, "clone: from %s", repo);
409 if (option_bare)
410 work_tree = NULL;
411 else {
412 work_tree = getenv("GIT_WORK_TREE");
413 if (work_tree && !stat(work_tree, &buf))
414 die("working tree '%s' already exists.", work_tree);
417 if (option_bare || work_tree)
418 git_dir = xstrdup(dir);
419 else {
420 work_tree = dir;
421 git_dir = xstrdup(mkpath("%s/.git", dir));
424 if (!option_bare) {
425 junk_work_tree = work_tree;
426 if (safe_create_leading_directories_const(work_tree) < 0)
427 die_errno("could not create leading directories of '%s'",
428 work_tree);
429 if (!dest_exists && mkdir(work_tree, 0755))
430 die_errno("could not create work tree dir '%s'.",
431 work_tree);
432 set_git_work_tree(work_tree);
434 junk_git_dir = git_dir;
435 atexit(remove_junk);
436 sigchain_push_common(remove_junk_on_signal);
438 setenv(CONFIG_ENVIRONMENT, mkpath("%s/config", git_dir), 1);
440 if (safe_create_leading_directories_const(git_dir) < 0)
441 die("could not create leading directories of '%s'", git_dir);
442 set_git_dir(make_absolute_path(git_dir));
444 init_db(option_template, option_quiet ? INIT_DB_QUIET : 0);
447 * At this point, the config exists, so we do not need the
448 * environment variable. We actually need to unset it, too, to
449 * re-enable parsing of the global configs.
451 unsetenv(CONFIG_ENVIRONMENT);
453 if (option_reference)
454 setup_reference(git_dir);
456 git_config(git_default_config, NULL);
458 if (option_bare) {
459 if (option_mirror)
460 src_ref_prefix = "refs/";
461 strbuf_addstr(&branch_top, src_ref_prefix);
463 git_config_set("core.bare", "true");
464 } else {
465 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
468 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
470 if (option_mirror || !option_bare) {
471 /* Configure the remote */
472 strbuf_addf(&key, "remote.%s.fetch", option_origin);
473 git_config_set_multivar(key.buf, value.buf, "^$", 0);
474 strbuf_reset(&key);
476 if (option_mirror) {
477 strbuf_addf(&key, "remote.%s.mirror", option_origin);
478 git_config_set(key.buf, "true");
479 strbuf_reset(&key);
482 strbuf_addf(&key, "remote.%s.url", option_origin);
483 git_config_set(key.buf, repo);
484 strbuf_reset(&key);
487 fetch_pattern = value.buf;
488 refspec = parse_fetch_refspec(1, &fetch_pattern);
490 strbuf_reset(&value);
492 if (path && !is_bundle)
493 refs = clone_local(path, git_dir);
494 else {
495 struct remote *remote = remote_get(argv[0]);
496 transport = transport_get(remote, remote->url[0]);
498 if (!transport->get_refs_list || !transport->fetch)
499 die("Don't know how to clone %s", transport->url);
501 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
503 if (option_depth)
504 transport_set_option(transport, TRANS_OPT_DEPTH,
505 option_depth);
507 if (option_quiet)
508 transport->verbose = -1;
509 else if (option_verbose)
510 transport->progress = 1;
512 if (option_upload_pack)
513 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
514 option_upload_pack);
516 refs = transport_get_remote_refs(transport);
517 if(refs)
518 transport_fetch_refs(transport, refs);
521 if (refs) {
522 clear_extra_refs();
524 mapped_refs = write_remote_refs(refs, refspec, reflog_msg.buf);
526 remote_head = find_ref_by_name(refs, "HEAD");
527 remote_head_points_at =
528 guess_remote_head(remote_head, mapped_refs, 0);
530 if (option_branch) {
531 struct strbuf head = STRBUF_INIT;
532 strbuf_addstr(&head, src_ref_prefix);
533 strbuf_addstr(&head, option_branch);
534 our_head_points_at =
535 find_ref_by_name(mapped_refs, head.buf);
536 strbuf_release(&head);
538 if (!our_head_points_at) {
539 warning("Remote branch %s not found in "
540 "upstream %s, using HEAD instead",
541 option_branch, option_origin);
542 our_head_points_at = remote_head_points_at;
545 else
546 our_head_points_at = remote_head_points_at;
548 else {
549 warning("You appear to have cloned an empty repository.");
550 our_head_points_at = NULL;
551 remote_head_points_at = NULL;
552 remote_head = NULL;
553 option_no_checkout = 1;
554 if (!option_bare)
555 install_branch_config(0, "master", option_origin,
556 "refs/heads/master");
559 if (remote_head_points_at && !option_bare) {
560 struct strbuf head_ref = STRBUF_INIT;
561 strbuf_addstr(&head_ref, branch_top.buf);
562 strbuf_addstr(&head_ref, "HEAD");
563 create_symref(head_ref.buf,
564 remote_head_points_at->peer_ref->name,
565 reflog_msg.buf);
568 if (our_head_points_at) {
569 /* Local default branch link */
570 create_symref("HEAD", our_head_points_at->name, NULL);
571 if (!option_bare) {
572 const char *head = skip_prefix(our_head_points_at->name,
573 "refs/heads/");
574 update_ref(reflog_msg.buf, "HEAD",
575 our_head_points_at->old_sha1,
576 NULL, 0, DIE_ON_ERR);
577 install_branch_config(0, head, option_origin,
578 our_head_points_at->name);
580 } else if (remote_head) {
581 /* Source had detached HEAD pointing somewhere. */
582 if (!option_bare) {
583 update_ref(reflog_msg.buf, "HEAD",
584 remote_head->old_sha1,
585 NULL, REF_NODEREF, DIE_ON_ERR);
586 our_head_points_at = remote_head;
588 } else {
589 /* Nothing to checkout out */
590 if (!option_no_checkout)
591 warning("remote HEAD refers to nonexistent ref, "
592 "unable to checkout.\n");
593 option_no_checkout = 1;
596 if (transport)
597 transport_unlock_pack(transport);
599 if (!option_no_checkout) {
600 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
601 struct unpack_trees_options opts;
602 struct tree *tree;
603 struct tree_desc t;
604 int fd;
606 /* We need to be in the new work tree for the checkout */
607 setup_work_tree();
609 fd = hold_locked_index(lock_file, 1);
611 memset(&opts, 0, sizeof opts);
612 opts.update = 1;
613 opts.merge = 1;
614 opts.fn = oneway_merge;
615 opts.verbose_update = !option_quiet;
616 opts.src_index = &the_index;
617 opts.dst_index = &the_index;
619 tree = parse_tree_indirect(our_head_points_at->old_sha1);
620 parse_tree(tree);
621 init_tree_desc(&t, tree->buffer, tree->size);
622 unpack_trees(1, &t, &opts);
624 if (write_cache(fd, active_cache, active_nr) ||
625 commit_locked_index(lock_file))
626 die("unable to write new index file");
628 err |= run_hook(NULL, "post-checkout", sha1_to_hex(null_sha1),
629 sha1_to_hex(remote_head->old_sha1), "1", NULL);
632 strbuf_release(&reflog_msg);
633 strbuf_release(&branch_top);
634 strbuf_release(&key);
635 strbuf_release(&value);
636 junk_pid = 0;
637 return err;