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