Code

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