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 "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
23/*
24 * Overall FIXMEs:
25 * - respect DB_ENVIRONMENT for .git/objects.
26 *
27 * Implementation notes:
28 * - dropping use-separate-remote and no-separate-remote compatibility
29 *
30 */
31static const char * const builtin_clone_usage[] = {
32 "git clone [options] [--] <repo> [<dir>]",
33 NULL
34};
35
36static int option_quiet, option_no_checkout, option_bare, option_mirror;
37static int option_local, option_no_hardlinks, option_shared;
38static char *option_template, *option_reference, *option_depth;
39static char *option_origin = NULL;
40static char *option_upload_pack = "git-upload-pack";
41
42static struct option builtin_clone_options[] = {
43 OPT__QUIET(&option_quiet),
44 OPT_BOOLEAN('n', "no-checkout", &option_no_checkout,
45 "don't create a checkout"),
46 OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"),
47 OPT_BOOLEAN(0, "naked", &option_bare, "create a bare repository"),
48 OPT_BOOLEAN(0, "mirror", &option_mirror,
49 "create a mirror repository (implies bare)"),
50 OPT_BOOLEAN('l', "local", &option_local,
51 "to clone from a local repository"),
52 OPT_BOOLEAN(0, "no-hardlinks", &option_no_hardlinks,
53 "don't use local hardlinks, always copy"),
54 OPT_BOOLEAN('s', "shared", &option_shared,
55 "setup as shared repository"),
56 OPT_STRING(0, "template", &option_template, "path",
57 "path the template repository"),
58 OPT_STRING(0, "reference", &option_reference, "repo",
59 "reference repository"),
60 OPT_STRING('o', "origin", &option_origin, "branch",
61 "use <branch> instead of 'origin' to track upstream"),
62 OPT_STRING('u', "upload-pack", &option_upload_pack, "path",
63 "path to git-upload-pack on the remote"),
64 OPT_STRING(0, "depth", &option_depth, "depth",
65 "create a shallow clone of that depth"),
66
67 OPT_END()
68};
69
70static char *get_repo_path(const char *repo, int *is_bundle)
71{
72 static char *suffix[] = { "/.git", ".git", "" };
73 static char *bundle_suffix[] = { ".bundle", "" };
74 struct stat st;
75 int i;
76
77 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
78 const char *path;
79 path = mkpath("%s%s", repo, suffix[i]);
80 if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
81 *is_bundle = 0;
82 return xstrdup(make_nonrelative_path(path));
83 }
84 }
85
86 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
87 const char *path;
88 path = mkpath("%s%s", repo, bundle_suffix[i]);
89 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
90 *is_bundle = 1;
91 return xstrdup(make_nonrelative_path(path));
92 }
93 }
94
95 return NULL;
96}
97
98static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
99{
100 const char *end = repo + strlen(repo), *start;
101
102 /*
103 * Strip trailing slashes and /.git
104 */
105 while (repo < end && is_dir_sep(end[-1]))
106 end--;
107 if (end - repo > 5 && is_dir_sep(end[-5]) &&
108 !strncmp(end - 4, ".git", 4)) {
109 end -= 5;
110 while (repo < end && is_dir_sep(end[-1]))
111 end--;
112 }
113
114 /*
115 * Find last component, but be prepared that repo could have
116 * the form "remote.example.com:foo.git", i.e. no slash
117 * in the directory part.
118 */
119 start = end;
120 while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
121 start--;
122
123 /*
124 * Strip .{bundle,git}.
125 */
126 if (is_bundle) {
127 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
128 end -= 7;
129 } else {
130 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
131 end -= 4;
132 }
133
134 if (is_bare) {
135 char *result = xmalloc(end - start + 5);
136 sprintf(result, "%.*s.git", (int)(end - start), start);
137 return result;
138 }
139
140 return xstrndup(start, end - start);
141}
142
143static int is_directory(const char *path)
144{
145 struct stat buf;
146
147 return !stat(path, &buf) && S_ISDIR(buf.st_mode);
148}
149
150static void strip_trailing_slashes(char *dir)
151{
152 char *end = dir + strlen(dir);
153
154 while (dir < end - 1 && is_dir_sep(end[-1]))
155 end--;
156 *end = '\0';
157}
158
159static void setup_reference(const char *repo)
160{
161 const char *ref_git;
162 char *ref_git_copy;
163
164 struct remote *remote;
165 struct transport *transport;
166 const struct ref *extra;
167
168 ref_git = make_absolute_path(option_reference);
169
170 if (is_directory(mkpath("%s/.git/objects", ref_git)))
171 ref_git = mkpath("%s/.git", ref_git);
172 else if (!is_directory(mkpath("%s/objects", ref_git)))
173 die("reference repository '%s' is not a local directory.",
174 option_reference);
175
176 ref_git_copy = xstrdup(ref_git);
177
178 add_to_alternates_file(ref_git_copy);
179
180 remote = remote_get(ref_git_copy);
181 transport = transport_get(remote, ref_git_copy);
182 for (extra = transport_get_remote_refs(transport); extra;
183 extra = extra->next)
184 add_extra_ref(extra->name, extra->old_sha1, 0);
185
186 transport_disconnect(transport);
187
188 free(ref_git_copy);
189}
190
191static void copy_or_link_directory(char *src, char *dest)
192{
193 struct dirent *de;
194 struct stat buf;
195 int src_len, dest_len;
196 DIR *dir;
197
198 dir = opendir(src);
199 if (!dir)
200 die("failed to open %s\n", src);
201
202 if (mkdir(dest, 0777)) {
203 if (errno != EEXIST)
204 die("failed to create directory %s\n", dest);
205 else if (stat(dest, &buf))
206 die("failed to stat %s\n", dest);
207 else if (!S_ISDIR(buf.st_mode))
208 die("%s exists and is not a directory\n", dest);
209 }
210
211 src_len = strlen(src);
212 src[src_len] = '/';
213 dest_len = strlen(dest);
214 dest[dest_len] = '/';
215
216 while ((de = readdir(dir)) != NULL) {
217 strcpy(src + src_len + 1, de->d_name);
218 strcpy(dest + dest_len + 1, de->d_name);
219 if (stat(src, &buf)) {
220 warning ("failed to stat %s\n", src);
221 continue;
222 }
223 if (S_ISDIR(buf.st_mode)) {
224 if (de->d_name[0] != '.')
225 copy_or_link_directory(src, dest);
226 continue;
227 }
228
229 if (unlink(dest) && errno != ENOENT)
230 die("failed to unlink %s\n", dest);
231 if (!option_no_hardlinks) {
232 if (!link(src, dest))
233 continue;
234 if (option_local)
235 die("failed to create link %s\n", dest);
236 option_no_hardlinks = 1;
237 }
238 if (copy_file(dest, src, 0666))
239 die("failed to copy file to %s\n", dest);
240 }
241 closedir(dir);
242}
243
244static const struct ref *clone_local(const char *src_repo,
245 const char *dest_repo)
246{
247 const struct ref *ret;
248 char src[PATH_MAX];
249 char dest[PATH_MAX];
250 struct remote *remote;
251 struct transport *transport;
252
253 if (option_shared)
254 add_to_alternates_file(src_repo);
255 else {
256 snprintf(src, PATH_MAX, "%s/objects", src_repo);
257 snprintf(dest, PATH_MAX, "%s/objects", dest_repo);
258 copy_or_link_directory(src, dest);
259 }
260
261 remote = remote_get(src_repo);
262 transport = transport_get(remote, src_repo);
263 ret = transport_get_remote_refs(transport);
264 transport_disconnect(transport);
265 return ret;
266}
267
268static const char *junk_work_tree;
269static const char *junk_git_dir;
270pid_t junk_pid;
271
272static void remove_junk(void)
273{
274 struct strbuf sb;
275 if (getpid() != junk_pid)
276 return;
277 strbuf_init(&sb, 0);
278 if (junk_git_dir) {
279 strbuf_addstr(&sb, junk_git_dir);
280 remove_dir_recursively(&sb, 0);
281 strbuf_reset(&sb);
282 }
283 if (junk_work_tree) {
284 strbuf_addstr(&sb, junk_work_tree);
285 remove_dir_recursively(&sb, 0);
286 strbuf_reset(&sb);
287 }
288}
289
290static void remove_junk_on_signal(int signo)
291{
292 remove_junk();
293 signal(SIGINT, SIG_DFL);
294 raise(signo);
295}
296
297static const struct ref *locate_head(const struct ref *refs,
298 const struct ref *mapped_refs,
299 const struct ref **remote_head_p)
300{
301 const struct ref *remote_head = NULL;
302 const struct ref *remote_master = NULL;
303 const struct ref *r;
304 for (r = refs; r; r = r->next)
305 if (!strcmp(r->name, "HEAD"))
306 remote_head = r;
307
308 for (r = mapped_refs; r; r = r->next)
309 if (!strcmp(r->name, "refs/heads/master"))
310 remote_master = r;
311
312 if (remote_head_p)
313 *remote_head_p = remote_head;
314
315 /* If there's no HEAD value at all, never mind. */
316 if (!remote_head)
317 return NULL;
318
319 /* If refs/heads/master could be right, it is. */
320 if (remote_master && !hashcmp(remote_master->old_sha1,
321 remote_head->old_sha1))
322 return remote_master;
323
324 /* Look for another ref that points there */
325 for (r = mapped_refs; r; r = r->next)
326 if (r != remote_head &&
327 !hashcmp(r->old_sha1, remote_head->old_sha1))
328 return r;
329
330 /* Nothing is the same */
331 return NULL;
332}
333
334static struct ref *write_remote_refs(const struct ref *refs,
335 struct refspec *refspec, const char *reflog)
336{
337 struct ref *local_refs = NULL;
338 struct ref **tail = &local_refs;
339 struct ref *r;
340
341 get_fetch_map(refs, refspec, &tail, 0);
342 if (!option_mirror)
343 get_fetch_map(refs, tag_refspec, &tail, 0);
344
345 for (r = local_refs; r; r = r->next)
346 add_extra_ref(r->peer_ref->name, r->old_sha1, 0);
347
348 pack_refs(PACK_REFS_ALL);
349 clear_extra_refs();
350
351 return local_refs;
352}
353
354int cmd_clone(int argc, const char **argv, const char *prefix)
355{
356 int use_local_hardlinks = 1;
357 int use_separate_remote = 1;
358 int is_bundle = 0;
359 struct stat buf;
360 const char *repo_name, *repo, *work_tree, *git_dir;
361 char *path, *dir;
362 const struct ref *refs, *head_points_at, *remote_head, *mapped_refs;
363 char branch_top[256], key[256], value[256];
364 struct strbuf reflog_msg;
365 struct transport *transport = NULL;
366 char *src_ref_prefix = "refs/heads/";
367
368 struct refspec refspec;
369
370 junk_pid = getpid();
371
372 argc = parse_options(argc, argv, builtin_clone_options,
373 builtin_clone_usage, 0);
374
375 if (argc == 0)
376 die("You must specify a repository to clone.");
377
378 if (option_no_hardlinks)
379 use_local_hardlinks = 0;
380
381 if (option_mirror)
382 option_bare = 1;
383
384 if (option_bare) {
385 if (option_origin)
386 die("--bare and --origin %s options are incompatible.",
387 option_origin);
388 option_no_checkout = 1;
389 use_separate_remote = 0;
390 }
391
392 if (!option_origin)
393 option_origin = "origin";
394
395 repo_name = argv[0];
396
397 path = get_repo_path(repo_name, &is_bundle);
398 if (path)
399 repo = xstrdup(make_nonrelative_path(repo_name));
400 else if (!strchr(repo_name, ':'))
401 repo = xstrdup(make_absolute_path(repo_name));
402 else
403 repo = repo_name;
404
405 if (argc == 2)
406 dir = xstrdup(argv[1]);
407 else
408 dir = guess_dir_name(repo_name, is_bundle, option_bare);
409 strip_trailing_slashes(dir);
410
411 if (!stat(dir, &buf))
412 die("destination directory '%s' already exists.", dir);
413
414 strbuf_init(&reflog_msg, 0);
415 strbuf_addf(&reflog_msg, "clone: from %s", repo);
416
417 if (option_bare)
418 work_tree = NULL;
419 else {
420 work_tree = getenv("GIT_WORK_TREE");
421 if (work_tree && !stat(work_tree, &buf))
422 die("working tree '%s' already exists.", work_tree);
423 }
424
425 if (option_bare || work_tree)
426 git_dir = xstrdup(dir);
427 else {
428 work_tree = dir;
429 git_dir = xstrdup(mkpath("%s/.git", dir));
430 }
431
432 if (!option_bare) {
433 junk_work_tree = work_tree;
434 if (safe_create_leading_directories_const(work_tree) < 0)
435 die("could not create leading directories of '%s': %s",
436 work_tree, strerror(errno));
437 if (mkdir(work_tree, 0755))
438 die("could not create work tree dir '%s': %s.",
439 work_tree, strerror(errno));
440 set_git_work_tree(work_tree);
441 }
442 junk_git_dir = git_dir;
443 atexit(remove_junk);
444 signal(SIGINT, remove_junk_on_signal);
445
446 setenv(CONFIG_ENVIRONMENT, xstrdup(mkpath("%s/config", git_dir)), 1);
447
448 if (safe_create_leading_directories_const(git_dir) < 0)
449 die("could not create leading directories of '%s'", git_dir);
450 set_git_dir(make_absolute_path(git_dir));
451
452 init_db(option_template, option_quiet ? INIT_DB_QUIET : 0);
453
454 /*
455 * At this point, the config exists, so we do not need the
456 * environment variable. We actually need to unset it, too, to
457 * re-enable parsing of the global configs.
458 */
459 unsetenv(CONFIG_ENVIRONMENT);
460
461 if (option_reference)
462 setup_reference(git_dir);
463
464 git_config(git_default_config, NULL);
465
466 if (option_bare) {
467 if (option_mirror)
468 src_ref_prefix = "refs/";
469 strcpy(branch_top, src_ref_prefix);
470
471 git_config_set("core.bare", "true");
472 } else {
473 snprintf(branch_top, sizeof(branch_top),
474 "refs/remotes/%s/", option_origin);
475 }
476
477 if (option_mirror || !option_bare) {
478 /* Configure the remote */
479 if (option_mirror) {
480 snprintf(key, sizeof(key),
481 "remote.%s.mirror", option_origin);
482 git_config_set(key, "true");
483 }
484
485 snprintf(key, sizeof(key), "remote.%s.url", option_origin);
486 git_config_set(key, repo);
487
488 snprintf(key, sizeof(key), "remote.%s.fetch", option_origin);
489 snprintf(value, sizeof(value),
490 "+%s*:%s*", src_ref_prefix, branch_top);
491 git_config_set_multivar(key, value, "^$", 0);
492 }
493
494 refspec.force = 0;
495 refspec.pattern = 1;
496 refspec.src = src_ref_prefix;
497 refspec.dst = branch_top;
498
499 if (path && !is_bundle)
500 refs = clone_local(path, git_dir);
501 else {
502 struct remote *remote = remote_get(argv[0]);
503 transport = transport_get(remote, remote->url[0]);
504
505 if (!transport->get_refs_list || !transport->fetch)
506 die("Don't know how to clone %s", transport->url);
507
508 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
509
510 if (option_depth)
511 transport_set_option(transport, TRANS_OPT_DEPTH,
512 option_depth);
513
514 if (option_quiet)
515 transport->verbose = -1;
516
517 if (option_upload_pack)
518 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
519 option_upload_pack);
520
521 refs = transport_get_remote_refs(transport);
522 transport_fetch_refs(transport, refs);
523 }
524
525 clear_extra_refs();
526
527 mapped_refs = write_remote_refs(refs, &refspec, reflog_msg.buf);
528
529 head_points_at = locate_head(refs, mapped_refs, &remote_head);
530
531 if (head_points_at) {
532 /* Local default branch link */
533 create_symref("HEAD", head_points_at->name, NULL);
534
535 if (!option_bare) {
536 struct strbuf head_ref;
537 const char *head = head_points_at->name;
538
539 if (!prefixcmp(head, "refs/heads/"))
540 head += 11;
541
542 /* Set up the initial local branch */
543
544 /* Local branch initial value */
545 update_ref(reflog_msg.buf, "HEAD",
546 head_points_at->old_sha1,
547 NULL, 0, DIE_ON_ERR);
548
549 strbuf_init(&head_ref, 0);
550 strbuf_addstr(&head_ref, branch_top);
551 strbuf_addstr(&head_ref, "HEAD");
552
553 /* Remote branch link */
554 create_symref(head_ref.buf,
555 head_points_at->peer_ref->name,
556 reflog_msg.buf);
557
558 snprintf(key, sizeof(key), "branch.%s.remote", head);
559 git_config_set(key, option_origin);
560 snprintf(key, sizeof(key), "branch.%s.merge", head);
561 git_config_set(key, head_points_at->name);
562 }
563 } else if (remote_head) {
564 /* Source had detached HEAD pointing somewhere. */
565 if (!option_bare)
566 update_ref(reflog_msg.buf, "HEAD",
567 remote_head->old_sha1,
568 NULL, REF_NODEREF, DIE_ON_ERR);
569 } else {
570 /* Nothing to checkout out */
571 if (!option_no_checkout)
572 warning("remote HEAD refers to nonexistent ref, "
573 "unable to checkout.\n");
574 option_no_checkout = 1;
575 }
576
577 if (transport)
578 transport_unlock_pack(transport);
579
580 if (!option_no_checkout) {
581 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
582 struct unpack_trees_options opts;
583 struct tree *tree;
584 struct tree_desc t;
585 int fd;
586
587 /* We need to be in the new work tree for the checkout */
588 setup_work_tree();
589
590 fd = hold_locked_index(lock_file, 1);
591
592 memset(&opts, 0, sizeof opts);
593 opts.update = 1;
594 opts.merge = 1;
595 opts.fn = oneway_merge;
596 opts.verbose_update = !option_quiet;
597 opts.src_index = &the_index;
598 opts.dst_index = &the_index;
599
600 tree = parse_tree_indirect(remote_head->old_sha1);
601 parse_tree(tree);
602 init_tree_desc(&t, tree->buffer, tree->size);
603 unpack_trees(1, &t, &opts);
604
605 if (write_cache(fd, active_cache, active_nr) ||
606 commit_locked_index(lock_file))
607 die("unable to write new index file");
608 }
609
610 strbuf_release(&reflog_msg);
611 junk_pid = 0;
612 return 0;
613}