Merge branch 'dc/stash-con-untracked'
[git.git] / builtin / clone.c
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 "pack-refs.h"
22 #include "sigchain.h"
23 #include "branch.h"
24 #include "remote.h"
25 #include "run-command.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  */
35 static const char * const builtin_clone_usage[] = {
36         "git clone [options] [--] <repo> [<dir>]",
37         NULL
38 };
39
40 static int option_no_checkout, option_bare, option_mirror;
41 static int option_local, option_no_hardlinks, option_shared, option_recursive;
42 static char *option_template, *option_reference, *option_depth;
43 static char *option_origin = NULL;
44 static char *option_branch = NULL;
45 static const char *real_git_dir;
46 static char *option_upload_pack = "git-upload-pack";
47 static int option_verbosity;
48 static int option_progress;
49 static struct string_list option_config;
50
51 static struct option builtin_clone_options[] = {
52         OPT__VERBOSITY(&option_verbosity),
53         OPT_BOOLEAN(0, "progress", &option_progress,
54                         "force progress reporting"),
55         OPT_BOOLEAN('n', "no-checkout", &option_no_checkout,
56                     "don't create a checkout"),
57         OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"),
58         { OPTION_BOOLEAN, 0, "naked", &option_bare, NULL,
59                 "create a bare repository",
60                 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
61         OPT_BOOLEAN(0, "mirror", &option_mirror,
62                     "create a mirror repository (implies bare)"),
63         OPT_BOOLEAN('l', "local", &option_local,
64                     "to clone from a local repository"),
65         OPT_BOOLEAN(0, "no-hardlinks", &option_no_hardlinks,
66                     "don't use local hardlinks, always copy"),
67         OPT_BOOLEAN('s', "shared", &option_shared,
68                     "setup as shared repository"),
69         OPT_BOOLEAN(0, "recursive", &option_recursive,
70                     "initialize submodules in the clone"),
71         OPT_BOOLEAN(0, "recurse-submodules", &option_recursive,
72                     "initialize submodules in the clone"),
73         OPT_STRING(0, "template", &option_template, "template-directory",
74                    "directory from which templates will be used"),
75         OPT_STRING(0, "reference", &option_reference, "repo",
76                    "reference repository"),
77         OPT_STRING('o', "origin", &option_origin, "branch",
78                    "use <branch> instead of 'origin' to track upstream"),
79         OPT_STRING('b', "branch", &option_branch, "branch",
80                    "checkout <branch> instead of the remote's HEAD"),
81         OPT_STRING('u', "upload-pack", &option_upload_pack, "path",
82                    "path to git-upload-pack on the remote"),
83         OPT_STRING(0, "depth", &option_depth, "depth",
84                     "create a shallow clone of that depth"),
85         OPT_STRING(0, "separate-git-dir", &real_git_dir, "gitdir",
86                    "separate git dir from working tree"),
87         OPT_STRING_LIST('c', "config", &option_config, "key=value",
88                         "set config inside the new repository"),
89         OPT_END()
90 };
91
92 static const char *argv_submodule[] = {
93         "submodule", "update", "--init", "--recursive", NULL
94 };
95
96 static char *get_repo_path(const char *repo, int *is_bundle)
97 {
98         static char *suffix[] = { "/.git", ".git", "" };
99         static char *bundle_suffix[] = { ".bundle", "" };
100         struct stat st;
101         int i;
102
103         for (i = 0; i < ARRAY_SIZE(suffix); i++) {
104                 const char *path;
105                 path = mkpath("%s%s", repo, suffix[i]);
106                 if (is_directory(path)) {
107                         *is_bundle = 0;
108                         return xstrdup(absolute_path(path));
109                 }
110         }
111
112         for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
113                 const char *path;
114                 path = mkpath("%s%s", repo, bundle_suffix[i]);
115                 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
116                         *is_bundle = 1;
117                         return xstrdup(absolute_path(path));
118                 }
119         }
120
121         return NULL;
122 }
123
124 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
125 {
126         const char *end = repo + strlen(repo), *start;
127         char *dir;
128
129         /*
130          * Strip trailing spaces, slashes and /.git
131          */
132         while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
133                 end--;
134         if (end - repo > 5 && is_dir_sep(end[-5]) &&
135             !strncmp(end - 4, ".git", 4)) {
136                 end -= 5;
137                 while (repo < end && is_dir_sep(end[-1]))
138                         end--;
139         }
140
141         /*
142          * Find last component, but be prepared that repo could have
143          * the form  "remote.example.com:foo.git", i.e. no slash
144          * in the directory part.
145          */
146         start = end;
147         while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
148                 start--;
149
150         /*
151          * Strip .{bundle,git}.
152          */
153         if (is_bundle) {
154                 if (end - start > 7 && !strncmp(end - 7, ".bundle", 7))
155                         end -= 7;
156         } else {
157                 if (end - start > 4 && !strncmp(end - 4, ".git", 4))
158                         end -= 4;
159         }
160
161         if (is_bare) {
162                 struct strbuf result = STRBUF_INIT;
163                 strbuf_addf(&result, "%.*s.git", (int)(end - start), start);
164                 dir = strbuf_detach(&result, NULL);
165         } else
166                 dir = xstrndup(start, end - start);
167         /*
168          * Replace sequences of 'control' characters and whitespace
169          * with one ascii space, remove leading and trailing spaces.
170          */
171         if (*dir) {
172                 char *out = dir;
173                 int prev_space = 1 /* strip leading whitespace */;
174                 for (end = dir; *end; ++end) {
175                         char ch = *end;
176                         if ((unsigned char)ch < '\x20')
177                                 ch = '\x20';
178                         if (isspace(ch)) {
179                                 if (prev_space)
180                                         continue;
181                                 prev_space = 1;
182                         } else
183                                 prev_space = 0;
184                         *out++ = ch;
185                 }
186                 *out = '\0';
187                 if (out > dir && prev_space)
188                         out[-1] = '\0';
189         }
190         return dir;
191 }
192
193 static void strip_trailing_slashes(char *dir)
194 {
195         char *end = dir + strlen(dir);
196
197         while (dir < end - 1 && is_dir_sep(end[-1]))
198                 end--;
199         *end = '\0';
200 }
201
202 static void setup_reference(const char *repo)
203 {
204         const char *ref_git;
205         char *ref_git_copy;
206
207         struct remote *remote;
208         struct transport *transport;
209         const struct ref *extra;
210
211         ref_git = real_path(option_reference);
212
213         if (is_directory(mkpath("%s/.git/objects", ref_git)))
214                 ref_git = mkpath("%s/.git", ref_git);
215         else if (!is_directory(mkpath("%s/objects", ref_git)))
216                 die(_("reference repository '%s' is not a local directory."),
217                     option_reference);
218
219         ref_git_copy = xstrdup(ref_git);
220
221         add_to_alternates_file(ref_git_copy);
222
223         remote = remote_get(ref_git_copy);
224         transport = transport_get(remote, ref_git_copy);
225         for (extra = transport_get_remote_refs(transport); extra;
226              extra = extra->next)
227                 add_extra_ref(extra->name, extra->old_sha1, 0);
228
229         transport_disconnect(transport);
230
231         free(ref_git_copy);
232 }
233
234 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest)
235 {
236         struct dirent *de;
237         struct stat buf;
238         int src_len, dest_len;
239         DIR *dir;
240
241         dir = opendir(src->buf);
242         if (!dir)
243                 die_errno(_("failed to open '%s'"), src->buf);
244
245         if (mkdir(dest->buf, 0777)) {
246                 if (errno != EEXIST)
247                         die_errno(_("failed to create directory '%s'"), dest->buf);
248                 else if (stat(dest->buf, &buf))
249                         die_errno(_("failed to stat '%s'"), dest->buf);
250                 else if (!S_ISDIR(buf.st_mode))
251                         die(_("%s exists and is not a directory"), dest->buf);
252         }
253
254         strbuf_addch(src, '/');
255         src_len = src->len;
256         strbuf_addch(dest, '/');
257         dest_len = dest->len;
258
259         while ((de = readdir(dir)) != NULL) {
260                 strbuf_setlen(src, src_len);
261                 strbuf_addstr(src, de->d_name);
262                 strbuf_setlen(dest, dest_len);
263                 strbuf_addstr(dest, de->d_name);
264                 if (stat(src->buf, &buf)) {
265                         warning (_("failed to stat %s\n"), src->buf);
266                         continue;
267                 }
268                 if (S_ISDIR(buf.st_mode)) {
269                         if (de->d_name[0] != '.')
270                                 copy_or_link_directory(src, dest);
271                         continue;
272                 }
273
274                 if (unlink(dest->buf) && errno != ENOENT)
275                         die_errno(_("failed to unlink '%s'"), dest->buf);
276                 if (!option_no_hardlinks) {
277                         if (!link(src->buf, dest->buf))
278                                 continue;
279                         if (option_local)
280                                 die_errno(_("failed to create link '%s'"), dest->buf);
281                         option_no_hardlinks = 1;
282                 }
283                 if (copy_file_with_time(dest->buf, src->buf, 0666))
284                         die_errno(_("failed to copy file to '%s'"), dest->buf);
285         }
286         closedir(dir);
287 }
288
289 static const struct ref *clone_local(const char *src_repo,
290                                      const char *dest_repo)
291 {
292         const struct ref *ret;
293         struct strbuf src = STRBUF_INIT;
294         struct strbuf dest = STRBUF_INIT;
295         struct remote *remote;
296         struct transport *transport;
297
298         if (option_shared)
299                 add_to_alternates_file(src_repo);
300         else {
301                 strbuf_addf(&src, "%s/objects", src_repo);
302                 strbuf_addf(&dest, "%s/objects", dest_repo);
303                 copy_or_link_directory(&src, &dest);
304                 strbuf_release(&src);
305                 strbuf_release(&dest);
306         }
307
308         remote = remote_get(src_repo);
309         transport = transport_get(remote, src_repo);
310         ret = transport_get_remote_refs(transport);
311         transport_disconnect(transport);
312         if (0 <= option_verbosity)
313                 printf(_("done.\n"));
314         return ret;
315 }
316
317 static const char *junk_work_tree;
318 static const char *junk_git_dir;
319 static pid_t junk_pid;
320
321 static void remove_junk(void)
322 {
323         struct strbuf sb = STRBUF_INIT;
324         if (getpid() != junk_pid)
325                 return;
326         if (junk_git_dir) {
327                 strbuf_addstr(&sb, junk_git_dir);
328                 remove_dir_recursively(&sb, 0);
329                 strbuf_reset(&sb);
330         }
331         if (junk_work_tree) {
332                 strbuf_addstr(&sb, junk_work_tree);
333                 remove_dir_recursively(&sb, 0);
334                 strbuf_reset(&sb);
335         }
336 }
337
338 static void remove_junk_on_signal(int signo)
339 {
340         remove_junk();
341         sigchain_pop(signo);
342         raise(signo);
343 }
344
345 static struct ref *wanted_peer_refs(const struct ref *refs,
346                 struct refspec *refspec)
347 {
348         struct ref *local_refs = NULL;
349         struct ref **tail = &local_refs;
350
351         get_fetch_map(refs, refspec, &tail, 0);
352         if (!option_mirror)
353                 get_fetch_map(refs, tag_refspec, &tail, 0);
354
355         return local_refs;
356 }
357
358 static void write_remote_refs(const struct ref *local_refs)
359 {
360         const struct ref *r;
361
362         for (r = local_refs; r; r = r->next)
363                 add_extra_ref(r->peer_ref->name, r->old_sha1, 0);
364
365         pack_refs(PACK_REFS_ALL);
366         clear_extra_refs();
367 }
368
369 static int write_one_config(const char *key, const char *value, void *data)
370 {
371         return git_config_set_multivar(key, value ? value : "true", "^$", 0);
372 }
373
374 static void write_config(struct string_list *config)
375 {
376         int i;
377
378         for (i = 0; i < config->nr; i++) {
379                 if (git_config_parse_parameter(config->items[i].string,
380                                                write_one_config, NULL) < 0)
381                         die("unable to write parameters to config file");
382         }
383 }
384
385 int cmd_clone(int argc, const char **argv, const char *prefix)
386 {
387         int is_bundle = 0, is_local;
388         struct stat buf;
389         const char *repo_name, *repo, *work_tree, *git_dir;
390         char *path, *dir;
391         int dest_exists;
392         const struct ref *refs, *remote_head;
393         const struct ref *remote_head_points_at;
394         const struct ref *our_head_points_at;
395         struct ref *mapped_refs;
396         struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
397         struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
398         struct transport *transport = NULL;
399         char *src_ref_prefix = "refs/heads/";
400         int err = 0;
401
402         struct refspec *refspec;
403         const char *fetch_pattern;
404
405         junk_pid = getpid();
406
407         packet_trace_identity("clone");
408         argc = parse_options(argc, argv, prefix, builtin_clone_options,
409                              builtin_clone_usage, 0);
410
411         if (argc > 2)
412                 usage_msg_opt(_("Too many arguments."),
413                         builtin_clone_usage, builtin_clone_options);
414
415         if (argc == 0)
416                 usage_msg_opt(_("You must specify a repository to clone."),
417                         builtin_clone_usage, builtin_clone_options);
418
419         if (option_mirror)
420                 option_bare = 1;
421
422         if (option_bare) {
423                 if (option_origin)
424                         die(_("--bare and --origin %s options are incompatible."),
425                             option_origin);
426                 option_no_checkout = 1;
427         }
428
429         if (!option_origin)
430                 option_origin = "origin";
431
432         repo_name = argv[0];
433
434         path = get_repo_path(repo_name, &is_bundle);
435         if (path)
436                 repo = xstrdup(absolute_path(repo_name));
437         else if (!strchr(repo_name, ':'))
438                 die(_("repository '%s' does not exist"), repo_name);
439         else
440                 repo = repo_name;
441         is_local = path && !is_bundle;
442         if (is_local && option_depth)
443                 warning(_("--depth is ignored in local clones; use file:// instead."));
444
445         if (argc == 2)
446                 dir = xstrdup(argv[1]);
447         else
448                 dir = guess_dir_name(repo_name, is_bundle, option_bare);
449         strip_trailing_slashes(dir);
450
451         dest_exists = !stat(dir, &buf);
452         if (dest_exists && !is_empty_dir(dir))
453                 die(_("destination path '%s' already exists and is not "
454                         "an empty directory."), dir);
455
456         strbuf_addf(&reflog_msg, "clone: from %s", repo);
457
458         if (option_bare)
459                 work_tree = NULL;
460         else {
461                 work_tree = getenv("GIT_WORK_TREE");
462                 if (work_tree && !stat(work_tree, &buf))
463                         die(_("working tree '%s' already exists."), work_tree);
464         }
465
466         if (option_bare || work_tree)
467                 git_dir = xstrdup(dir);
468         else {
469                 work_tree = dir;
470                 git_dir = xstrdup(mkpath("%s/.git", dir));
471         }
472
473         if (!option_bare) {
474                 junk_work_tree = work_tree;
475                 if (safe_create_leading_directories_const(work_tree) < 0)
476                         die_errno(_("could not create leading directories of '%s'"),
477                                   work_tree);
478                 if (!dest_exists && mkdir(work_tree, 0755))
479                         die_errno(_("could not create work tree dir '%s'."),
480                                   work_tree);
481                 set_git_work_tree(work_tree);
482         }
483         junk_git_dir = git_dir;
484         atexit(remove_junk);
485         sigchain_push_common(remove_junk_on_signal);
486
487         setenv(CONFIG_ENVIRONMENT, mkpath("%s/config", git_dir), 1);
488
489         if (safe_create_leading_directories_const(git_dir) < 0)
490                 die(_("could not create leading directories of '%s'"), git_dir);
491
492         set_git_dir_init(git_dir, real_git_dir, 0);
493         if (real_git_dir)
494                 git_dir = real_git_dir;
495
496         if (0 <= option_verbosity) {
497                 if (option_bare)
498                         printf(_("Cloning into bare repository %s...\n"), dir);
499                 else
500                         printf(_("Cloning into %s...\n"), dir);
501         }
502         init_db(option_template, INIT_DB_QUIET);
503         write_config(&option_config);
504
505         /*
506          * At this point, the config exists, so we do not need the
507          * environment variable.  We actually need to unset it, too, to
508          * re-enable parsing of the global configs.
509          */
510         unsetenv(CONFIG_ENVIRONMENT);
511
512         git_config(git_default_config, NULL);
513
514         if (option_bare) {
515                 if (option_mirror)
516                         src_ref_prefix = "refs/";
517                 strbuf_addstr(&branch_top, src_ref_prefix);
518
519                 git_config_set("core.bare", "true");
520         } else {
521                 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
522         }
523
524         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
525
526         if (option_mirror || !option_bare) {
527                 /* Configure the remote */
528                 strbuf_addf(&key, "remote.%s.fetch", option_origin);
529                 git_config_set_multivar(key.buf, value.buf, "^$", 0);
530                 strbuf_reset(&key);
531
532                 if (option_mirror) {
533                         strbuf_addf(&key, "remote.%s.mirror", option_origin);
534                         git_config_set(key.buf, "true");
535                         strbuf_reset(&key);
536                 }
537         }
538
539         strbuf_addf(&key, "remote.%s.url", option_origin);
540         git_config_set(key.buf, repo);
541         strbuf_reset(&key);
542
543         if (option_reference)
544                 setup_reference(git_dir);
545
546         fetch_pattern = value.buf;
547         refspec = parse_fetch_refspec(1, &fetch_pattern);
548
549         strbuf_reset(&value);
550
551         if (is_local) {
552                 refs = clone_local(path, git_dir);
553                 mapped_refs = wanted_peer_refs(refs, refspec);
554         } else {
555                 struct remote *remote = remote_get(option_origin);
556                 transport = transport_get(remote, remote->url[0]);
557
558                 if (!transport->get_refs_list || !transport->fetch)
559                         die(_("Don't know how to clone %s"), transport->url);
560
561                 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
562
563                 if (option_depth)
564                         transport_set_option(transport, TRANS_OPT_DEPTH,
565                                              option_depth);
566
567                 transport_set_verbosity(transport, option_verbosity, option_progress);
568
569                 if (option_upload_pack)
570                         transport_set_option(transport, TRANS_OPT_UPLOADPACK,
571                                              option_upload_pack);
572
573                 refs = transport_get_remote_refs(transport);
574                 if (refs) {
575                         mapped_refs = wanted_peer_refs(refs, refspec);
576                         transport_fetch_refs(transport, mapped_refs);
577                 }
578         }
579
580         if (refs) {
581                 clear_extra_refs();
582
583                 write_remote_refs(mapped_refs);
584
585                 remote_head = find_ref_by_name(refs, "HEAD");
586                 remote_head_points_at =
587                         guess_remote_head(remote_head, mapped_refs, 0);
588
589                 if (option_branch) {
590                         struct strbuf head = STRBUF_INIT;
591                         strbuf_addstr(&head, src_ref_prefix);
592                         strbuf_addstr(&head, option_branch);
593                         our_head_points_at =
594                                 find_ref_by_name(mapped_refs, head.buf);
595                         strbuf_release(&head);
596
597                         if (!our_head_points_at) {
598                                 warning(_("Remote branch %s not found in "
599                                         "upstream %s, using HEAD instead"),
600                                         option_branch, option_origin);
601                                 our_head_points_at = remote_head_points_at;
602                         }
603                 }
604                 else
605                         our_head_points_at = remote_head_points_at;
606         }
607         else {
608                 warning(_("You appear to have cloned an empty repository."));
609                 our_head_points_at = NULL;
610                 remote_head_points_at = NULL;
611                 remote_head = NULL;
612                 option_no_checkout = 1;
613                 if (!option_bare)
614                         install_branch_config(0, "master", option_origin,
615                                               "refs/heads/master");
616         }
617
618         if (remote_head_points_at && !option_bare) {
619                 struct strbuf head_ref = STRBUF_INIT;
620                 strbuf_addstr(&head_ref, branch_top.buf);
621                 strbuf_addstr(&head_ref, "HEAD");
622                 create_symref(head_ref.buf,
623                               remote_head_points_at->peer_ref->name,
624                               reflog_msg.buf);
625         }
626
627         if (our_head_points_at) {
628                 /* Local default branch link */
629                 create_symref("HEAD", our_head_points_at->name, NULL);
630                 if (!option_bare) {
631                         const char *head = skip_prefix(our_head_points_at->name,
632                                                        "refs/heads/");
633                         update_ref(reflog_msg.buf, "HEAD",
634                                    our_head_points_at->old_sha1,
635                                    NULL, 0, DIE_ON_ERR);
636                         install_branch_config(0, head, option_origin,
637                                               our_head_points_at->name);
638                 }
639         } else if (remote_head) {
640                 /* Source had detached HEAD pointing somewhere. */
641                 if (!option_bare) {
642                         update_ref(reflog_msg.buf, "HEAD",
643                                    remote_head->old_sha1,
644                                    NULL, REF_NODEREF, DIE_ON_ERR);
645                         our_head_points_at = remote_head;
646                 }
647         } else {
648                 /* Nothing to checkout out */
649                 if (!option_no_checkout)
650                         warning(_("remote HEAD refers to nonexistent ref, "
651                                 "unable to checkout.\n"));
652                 option_no_checkout = 1;
653         }
654
655         if (transport) {
656                 transport_unlock_pack(transport);
657                 transport_disconnect(transport);
658         }
659
660         if (!option_no_checkout) {
661                 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
662                 struct unpack_trees_options opts;
663                 struct tree *tree;
664                 struct tree_desc t;
665                 int fd;
666
667                 /* We need to be in the new work tree for the checkout */
668                 setup_work_tree();
669
670                 fd = hold_locked_index(lock_file, 1);
671
672                 memset(&opts, 0, sizeof opts);
673                 opts.update = 1;
674                 opts.merge = 1;
675                 opts.fn = oneway_merge;
676                 opts.verbose_update = (option_verbosity > 0);
677                 opts.src_index = &the_index;
678                 opts.dst_index = &the_index;
679
680                 tree = parse_tree_indirect(our_head_points_at->old_sha1);
681                 parse_tree(tree);
682                 init_tree_desc(&t, tree->buffer, tree->size);
683                 unpack_trees(1, &t, &opts);
684
685                 if (write_cache(fd, active_cache, active_nr) ||
686                     commit_locked_index(lock_file))
687                         die(_("unable to write new index file"));
688
689                 err |= run_hook(NULL, "post-checkout", sha1_to_hex(null_sha1),
690                                 sha1_to_hex(our_head_points_at->old_sha1), "1",
691                                 NULL);
692
693                 if (!err && option_recursive)
694                         err = run_command_v_opt(argv_submodule, RUN_GIT_CMD);
695         }
696
697         strbuf_release(&reflog_msg);
698         strbuf_release(&branch_top);
699         strbuf_release(&key);
700         strbuf_release(&value);
701         junk_pid = 0;
702         return err;
703 }