Merge branch 'jk/guess-repo-name-regression-fix'
[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 "lockfile.h"
13 #include "parse-options.h"
14 #include "fetch-pack.h"
15 #include "refs.h"
16 #include "tree.h"
17 #include "tree-walk.h"
18 #include "unpack-trees.h"
19 #include "transport.h"
20 #include "strbuf.h"
21 #include "dir.h"
22 #include "sigchain.h"
23 #include "branch.h"
24 #include "remote.h"
25 #include "run-command.h"
26 #include "connected.h"
27
28 /*
29  * Overall FIXMEs:
30  *  - respect DB_ENVIRONMENT for .git/objects.
31  *
32  * Implementation notes:
33  *  - dropping use-separate-remote and no-separate-remote compatibility
34  *
35  */
36 static const char * const builtin_clone_usage[] = {
37         N_("git clone [<options>] [--] <repo> [<dir>]"),
38         NULL
39 };
40
41 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
42 static int option_local = -1, option_no_hardlinks, option_shared, option_recursive;
43 static char *option_template, *option_depth;
44 static char *option_origin = NULL;
45 static char *option_branch = NULL;
46 static const char *real_git_dir;
47 static char *option_upload_pack = "git-upload-pack";
48 static int option_verbosity;
49 static int option_progress = -1;
50 static struct string_list option_config;
51 static struct string_list option_reference;
52 static int option_dissociate;
53
54 static struct option builtin_clone_options[] = {
55         OPT__VERBOSITY(&option_verbosity),
56         OPT_BOOL(0, "progress", &option_progress,
57                  N_("force progress reporting")),
58         OPT_BOOL('n', "no-checkout", &option_no_checkout,
59                  N_("don't create a checkout")),
60         OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
61         OPT_HIDDEN_BOOL(0, "naked", &option_bare,
62                         N_("create a bare repository")),
63         OPT_BOOL(0, "mirror", &option_mirror,
64                  N_("create a mirror repository (implies bare)")),
65         OPT_BOOL('l', "local", &option_local,
66                 N_("to clone from a local repository")),
67         OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
68                     N_("don't use local hardlinks, always copy")),
69         OPT_BOOL('s', "shared", &option_shared,
70                     N_("setup as shared repository")),
71         OPT_BOOL(0, "recursive", &option_recursive,
72                     N_("initialize submodules in the clone")),
73         OPT_BOOL(0, "recurse-submodules", &option_recursive,
74                     N_("initialize submodules in the clone")),
75         OPT_STRING(0, "template", &option_template, N_("template-directory"),
76                    N_("directory from which templates will be used")),
77         OPT_STRING_LIST(0, "reference", &option_reference, N_("repo"),
78                         N_("reference repository")),
79         OPT_BOOL(0, "dissociate", &option_dissociate,
80                  N_("use --reference only while cloning")),
81         OPT_STRING('o', "origin", &option_origin, N_("name"),
82                    N_("use <name> instead of 'origin' to track upstream")),
83         OPT_STRING('b', "branch", &option_branch, N_("branch"),
84                    N_("checkout <branch> instead of the remote's HEAD")),
85         OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
86                    N_("path to git-upload-pack on the remote")),
87         OPT_STRING(0, "depth", &option_depth, N_("depth"),
88                     N_("create a shallow clone of that depth")),
89         OPT_BOOL(0, "single-branch", &option_single_branch,
90                     N_("clone only one branch, HEAD or --branch")),
91         OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
92                    N_("separate git dir from working tree")),
93         OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
94                         N_("set config inside the new repository")),
95         OPT_END()
96 };
97
98 static const char *argv_submodule[] = {
99         "submodule", "update", "--init", "--recursive", NULL
100 };
101
102 static char *get_repo_path(const char *repo, int *is_bundle)
103 {
104         static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
105         static char *bundle_suffix[] = { ".bundle", "" };
106         struct stat st;
107         int i;
108
109         for (i = 0; i < ARRAY_SIZE(suffix); i++) {
110                 const char *path;
111                 path = mkpath("%s%s", repo, suffix[i]);
112                 if (stat(path, &st))
113                         continue;
114                 if (S_ISDIR(st.st_mode) && is_git_directory(path)) {
115                         *is_bundle = 0;
116                         return xstrdup(absolute_path(path));
117                 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
118                         /* Is it a "gitfile"? */
119                         char signature[8];
120                         int len, fd = open(path, O_RDONLY);
121                         if (fd < 0)
122                                 continue;
123                         len = read_in_full(fd, signature, 8);
124                         close(fd);
125                         if (len != 8 || strncmp(signature, "gitdir: ", 8))
126                                 continue;
127                         path = read_gitfile(path);
128                         if (path) {
129                                 *is_bundle = 0;
130                                 return xstrdup(absolute_path(path));
131                         }
132                 }
133         }
134
135         for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
136                 const char *path;
137                 path = mkpath("%s%s", repo, bundle_suffix[i]);
138                 if (!stat(path, &st) && S_ISREG(st.st_mode)) {
139                         *is_bundle = 1;
140                         return xstrdup(absolute_path(path));
141                 }
142         }
143
144         return NULL;
145 }
146
147 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
148 {
149         const char *end = repo + strlen(repo), *start;
150         size_t len;
151         char *dir;
152
153         /*
154          * Strip trailing spaces, slashes and /.git
155          */
156         while (repo < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
157                 end--;
158         if (end - repo > 5 && is_dir_sep(end[-5]) &&
159             !strncmp(end - 4, ".git", 4)) {
160                 end -= 5;
161                 while (repo < end && is_dir_sep(end[-1]))
162                         end--;
163         }
164
165         /*
166          * Find last component, but be prepared that repo could have
167          * the form  "remote.example.com:foo.git", i.e. no slash
168          * in the directory part.
169          */
170         start = end;
171         while (repo < start && !is_dir_sep(start[-1]) && start[-1] != ':')
172                 start--;
173
174         /*
175          * Strip .{bundle,git}.
176          */
177         len = end - start;
178         strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
179
180         if (is_bare)
181                 dir = xstrfmt("%.*s.git", (int)len, start);
182         else
183                 dir = xstrndup(start, len);
184         /*
185          * Replace sequences of 'control' characters and whitespace
186          * with one ascii space, remove leading and trailing spaces.
187          */
188         if (*dir) {
189                 char *out = dir;
190                 int prev_space = 1 /* strip leading whitespace */;
191                 for (end = dir; *end; ++end) {
192                         char ch = *end;
193                         if ((unsigned char)ch < '\x20')
194                                 ch = '\x20';
195                         if (isspace(ch)) {
196                                 if (prev_space)
197                                         continue;
198                                 prev_space = 1;
199                         } else
200                                 prev_space = 0;
201                         *out++ = ch;
202                 }
203                 *out = '\0';
204                 if (out > dir && prev_space)
205                         out[-1] = '\0';
206         }
207         return dir;
208 }
209
210 static void strip_trailing_slashes(char *dir)
211 {
212         char *end = dir + strlen(dir);
213
214         while (dir < end - 1 && is_dir_sep(end[-1]))
215                 end--;
216         *end = '\0';
217 }
218
219 static int add_one_reference(struct string_list_item *item, void *cb_data)
220 {
221         char *ref_git;
222         const char *repo;
223         struct strbuf alternate = STRBUF_INIT;
224
225         /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
226         ref_git = xstrdup(real_path(item->string));
227
228         repo = read_gitfile(ref_git);
229         if (!repo)
230                 repo = read_gitfile(mkpath("%s/.git", ref_git));
231         if (repo) {
232                 free(ref_git);
233                 ref_git = xstrdup(repo);
234         }
235
236         if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
237                 char *ref_git_git = mkpathdup("%s/.git", ref_git);
238                 free(ref_git);
239                 ref_git = ref_git_git;
240         } else if (!is_directory(mkpath("%s/objects", ref_git)))
241                 die(_("reference repository '%s' is not a local repository."),
242                     item->string);
243
244         if (!access(mkpath("%s/shallow", ref_git), F_OK))
245                 die(_("reference repository '%s' is shallow"), item->string);
246
247         if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
248                 die(_("reference repository '%s' is grafted"), item->string);
249
250         strbuf_addf(&alternate, "%s/objects", ref_git);
251         add_to_alternates_file(alternate.buf);
252         strbuf_release(&alternate);
253         free(ref_git);
254         return 0;
255 }
256
257 static void setup_reference(void)
258 {
259         for_each_string_list(&option_reference, add_one_reference, NULL);
260 }
261
262 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
263                             const char *src_repo)
264 {
265         /*
266          * Read from the source objects/info/alternates file
267          * and copy the entries to corresponding file in the
268          * destination repository with add_to_alternates_file().
269          * Both src and dst have "$path/objects/info/alternates".
270          *
271          * Instead of copying bit-for-bit from the original,
272          * we need to append to existing one so that the already
273          * created entry via "clone -s" is not lost, and also
274          * to turn entries with paths relative to the original
275          * absolute, so that they can be used in the new repository.
276          */
277         FILE *in = fopen(src->buf, "r");
278         struct strbuf line = STRBUF_INIT;
279
280         while (strbuf_getline(&line, in, '\n') != EOF) {
281                 char *abs_path;
282                 if (!line.len || line.buf[0] == '#')
283                         continue;
284                 if (is_absolute_path(line.buf)) {
285                         add_to_alternates_file(line.buf);
286                         continue;
287                 }
288                 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
289                 normalize_path_copy(abs_path, abs_path);
290                 add_to_alternates_file(abs_path);
291                 free(abs_path);
292         }
293         strbuf_release(&line);
294         fclose(in);
295 }
296
297 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
298                                    const char *src_repo, int src_baselen)
299 {
300         struct dirent *de;
301         struct stat buf;
302         int src_len, dest_len;
303         DIR *dir;
304
305         dir = opendir(src->buf);
306         if (!dir)
307                 die_errno(_("failed to open '%s'"), src->buf);
308
309         if (mkdir(dest->buf, 0777)) {
310                 if (errno != EEXIST)
311                         die_errno(_("failed to create directory '%s'"), dest->buf);
312                 else if (stat(dest->buf, &buf))
313                         die_errno(_("failed to stat '%s'"), dest->buf);
314                 else if (!S_ISDIR(buf.st_mode))
315                         die(_("%s exists and is not a directory"), dest->buf);
316         }
317
318         strbuf_addch(src, '/');
319         src_len = src->len;
320         strbuf_addch(dest, '/');
321         dest_len = dest->len;
322
323         while ((de = readdir(dir)) != NULL) {
324                 strbuf_setlen(src, src_len);
325                 strbuf_addstr(src, de->d_name);
326                 strbuf_setlen(dest, dest_len);
327                 strbuf_addstr(dest, de->d_name);
328                 if (stat(src->buf, &buf)) {
329                         warning (_("failed to stat %s\n"), src->buf);
330                         continue;
331                 }
332                 if (S_ISDIR(buf.st_mode)) {
333                         if (de->d_name[0] != '.')
334                                 copy_or_link_directory(src, dest,
335                                                        src_repo, src_baselen);
336                         continue;
337                 }
338
339                 /* Files that cannot be copied bit-for-bit... */
340                 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
341                         copy_alternates(src, dest, src_repo);
342                         continue;
343                 }
344
345                 if (unlink(dest->buf) && errno != ENOENT)
346                         die_errno(_("failed to unlink '%s'"), dest->buf);
347                 if (!option_no_hardlinks) {
348                         if (!link(src->buf, dest->buf))
349                                 continue;
350                         if (option_local > 0)
351                                 die_errno(_("failed to create link '%s'"), dest->buf);
352                         option_no_hardlinks = 1;
353                 }
354                 if (copy_file_with_time(dest->buf, src->buf, 0666))
355                         die_errno(_("failed to copy file to '%s'"), dest->buf);
356         }
357         closedir(dir);
358 }
359
360 static void clone_local(const char *src_repo, const char *dest_repo)
361 {
362         if (option_shared) {
363                 struct strbuf alt = STRBUF_INIT;
364                 strbuf_addf(&alt, "%s/objects", src_repo);
365                 add_to_alternates_file(alt.buf);
366                 strbuf_release(&alt);
367         } else {
368                 struct strbuf src = STRBUF_INIT;
369                 struct strbuf dest = STRBUF_INIT;
370                 strbuf_addf(&src, "%s/objects", src_repo);
371                 strbuf_addf(&dest, "%s/objects", dest_repo);
372                 copy_or_link_directory(&src, &dest, src_repo, src.len);
373                 strbuf_release(&src);
374                 strbuf_release(&dest);
375         }
376
377         if (0 <= option_verbosity)
378                 fprintf(stderr, _("done.\n"));
379 }
380
381 static const char *junk_work_tree;
382 static const char *junk_git_dir;
383 static enum {
384         JUNK_LEAVE_NONE,
385         JUNK_LEAVE_REPO,
386         JUNK_LEAVE_ALL
387 } junk_mode = JUNK_LEAVE_NONE;
388
389 static const char junk_leave_repo_msg[] =
390 N_("Clone succeeded, but checkout failed.\n"
391    "You can inspect what was checked out with 'git status'\n"
392    "and retry the checkout with 'git checkout -f HEAD'\n");
393
394 static void remove_junk(void)
395 {
396         struct strbuf sb = STRBUF_INIT;
397
398         switch (junk_mode) {
399         case JUNK_LEAVE_REPO:
400                 warning("%s", _(junk_leave_repo_msg));
401                 /* fall-through */
402         case JUNK_LEAVE_ALL:
403                 return;
404         default:
405                 /* proceed to removal */
406                 break;
407         }
408
409         if (junk_git_dir) {
410                 strbuf_addstr(&sb, junk_git_dir);
411                 remove_dir_recursively(&sb, 0);
412                 strbuf_reset(&sb);
413         }
414         if (junk_work_tree) {
415                 strbuf_addstr(&sb, junk_work_tree);
416                 remove_dir_recursively(&sb, 0);
417                 strbuf_reset(&sb);
418         }
419 }
420
421 static void remove_junk_on_signal(int signo)
422 {
423         remove_junk();
424         sigchain_pop(signo);
425         raise(signo);
426 }
427
428 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
429 {
430         struct ref *ref;
431         struct strbuf head = STRBUF_INIT;
432         strbuf_addstr(&head, "refs/heads/");
433         strbuf_addstr(&head, branch);
434         ref = find_ref_by_name(refs, head.buf);
435         strbuf_release(&head);
436
437         if (ref)
438                 return ref;
439
440         strbuf_addstr(&head, "refs/tags/");
441         strbuf_addstr(&head, branch);
442         ref = find_ref_by_name(refs, head.buf);
443         strbuf_release(&head);
444
445         return ref;
446 }
447
448 static struct ref *wanted_peer_refs(const struct ref *refs,
449                 struct refspec *refspec)
450 {
451         struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
452         struct ref *local_refs = head;
453         struct ref **tail = head ? &head->next : &local_refs;
454
455         if (option_single_branch) {
456                 struct ref *remote_head = NULL;
457
458                 if (!option_branch)
459                         remote_head = guess_remote_head(head, refs, 0);
460                 else {
461                         local_refs = NULL;
462                         tail = &local_refs;
463                         remote_head = copy_ref(find_remote_branch(refs, option_branch));
464                 }
465
466                 if (!remote_head && option_branch)
467                         warning(_("Could not find remote branch %s to clone."),
468                                 option_branch);
469                 else {
470                         get_fetch_map(remote_head, refspec, &tail, 0);
471
472                         /* if --branch=tag, pull the requested tag explicitly */
473                         get_fetch_map(remote_head, tag_refspec, &tail, 0);
474                 }
475         } else
476                 get_fetch_map(refs, refspec, &tail, 0);
477
478         if (!option_mirror && !option_single_branch)
479                 get_fetch_map(refs, tag_refspec, &tail, 0);
480
481         return local_refs;
482 }
483
484 static void write_remote_refs(const struct ref *local_refs)
485 {
486         const struct ref *r;
487
488         struct ref_transaction *t;
489         struct strbuf err = STRBUF_INIT;
490
491         t = ref_transaction_begin(&err);
492         if (!t)
493                 die("%s", err.buf);
494
495         for (r = local_refs; r; r = r->next) {
496                 if (!r->peer_ref)
497                         continue;
498                 if (ref_transaction_create(t, r->peer_ref->name, r->old_sha1,
499                                            0, NULL, &err))
500                         die("%s", err.buf);
501         }
502
503         if (initial_ref_transaction_commit(t, &err))
504                 die("%s", err.buf);
505
506         strbuf_release(&err);
507         ref_transaction_free(t);
508 }
509
510 static void write_followtags(const struct ref *refs, const char *msg)
511 {
512         const struct ref *ref;
513         for (ref = refs; ref; ref = ref->next) {
514                 if (!starts_with(ref->name, "refs/tags/"))
515                         continue;
516                 if (ends_with(ref->name, "^{}"))
517                         continue;
518                 if (!has_sha1_file(ref->old_sha1))
519                         continue;
520                 update_ref(msg, ref->name, ref->old_sha1,
521                            NULL, 0, UPDATE_REFS_DIE_ON_ERR);
522         }
523 }
524
525 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
526 {
527         struct ref **rm = cb_data;
528         struct ref *ref = *rm;
529
530         /*
531          * Skip anything missing a peer_ref, which we are not
532          * actually going to write a ref for.
533          */
534         while (ref && !ref->peer_ref)
535                 ref = ref->next;
536         /* Returning -1 notes "end of list" to the caller. */
537         if (!ref)
538                 return -1;
539
540         hashcpy(sha1, ref->old_sha1);
541         *rm = ref->next;
542         return 0;
543 }
544
545 static void update_remote_refs(const struct ref *refs,
546                                const struct ref *mapped_refs,
547                                const struct ref *remote_head_points_at,
548                                const char *branch_top,
549                                const char *msg,
550                                struct transport *transport,
551                                int check_connectivity)
552 {
553         const struct ref *rm = mapped_refs;
554
555         if (check_connectivity) {
556                 if (transport->progress)
557                         fprintf(stderr, _("Checking connectivity... "));
558                 if (check_everything_connected_with_transport(iterate_ref_map,
559                                                               0, &rm, transport))
560                         die(_("remote did not send all necessary objects"));
561                 if (transport->progress)
562                         fprintf(stderr, _("done.\n"));
563         }
564
565         if (refs) {
566                 write_remote_refs(mapped_refs);
567                 if (option_single_branch)
568                         write_followtags(refs, msg);
569         }
570
571         if (remote_head_points_at && !option_bare) {
572                 struct strbuf head_ref = STRBUF_INIT;
573                 strbuf_addstr(&head_ref, branch_top);
574                 strbuf_addstr(&head_ref, "HEAD");
575                 create_symref(head_ref.buf,
576                               remote_head_points_at->peer_ref->name,
577                               msg);
578         }
579 }
580
581 static void update_head(const struct ref *our, const struct ref *remote,
582                         const char *msg)
583 {
584         const char *head;
585         if (our && skip_prefix(our->name, "refs/heads/", &head)) {
586                 /* Local default branch link */
587                 create_symref("HEAD", our->name, NULL);
588                 if (!option_bare) {
589                         update_ref(msg, "HEAD", our->old_sha1, NULL, 0,
590                                    UPDATE_REFS_DIE_ON_ERR);
591                         install_branch_config(0, head, option_origin, our->name);
592                 }
593         } else if (our) {
594                 struct commit *c = lookup_commit_reference(our->old_sha1);
595                 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
596                 update_ref(msg, "HEAD", c->object.sha1,
597                            NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
598         } else if (remote) {
599                 /*
600                  * We know remote HEAD points to a non-branch, or
601                  * HEAD points to a branch but we don't know which one.
602                  * Detach HEAD in all these cases.
603                  */
604                 update_ref(msg, "HEAD", remote->old_sha1,
605                            NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
606         }
607 }
608
609 static int checkout(void)
610 {
611         unsigned char sha1[20];
612         char *head;
613         struct lock_file *lock_file;
614         struct unpack_trees_options opts;
615         struct tree *tree;
616         struct tree_desc t;
617         int err = 0;
618
619         if (option_no_checkout)
620                 return 0;
621
622         head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
623         if (!head) {
624                 warning(_("remote HEAD refers to nonexistent ref, "
625                           "unable to checkout.\n"));
626                 return 0;
627         }
628         if (!strcmp(head, "HEAD")) {
629                 if (advice_detached_head)
630                         detach_advice(sha1_to_hex(sha1));
631         } else {
632                 if (!starts_with(head, "refs/heads/"))
633                         die(_("HEAD not found below refs/heads!"));
634         }
635         free(head);
636
637         /* We need to be in the new work tree for the checkout */
638         setup_work_tree();
639
640         lock_file = xcalloc(1, sizeof(struct lock_file));
641         hold_locked_index(lock_file, 1);
642
643         memset(&opts, 0, sizeof opts);
644         opts.update = 1;
645         opts.merge = 1;
646         opts.fn = oneway_merge;
647         opts.verbose_update = (option_verbosity >= 0);
648         opts.src_index = &the_index;
649         opts.dst_index = &the_index;
650
651         tree = parse_tree_indirect(sha1);
652         parse_tree(tree);
653         init_tree_desc(&t, tree->buffer, tree->size);
654         if (unpack_trees(1, &t, &opts) < 0)
655                 die(_("unable to checkout working tree"));
656
657         if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
658                 die(_("unable to write new index file"));
659
660         err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
661                            sha1_to_hex(sha1), "1", NULL);
662
663         if (!err && option_recursive)
664                 err = run_command_v_opt(argv_submodule, RUN_GIT_CMD);
665
666         return err;
667 }
668
669 static int write_one_config(const char *key, const char *value, void *data)
670 {
671         return git_config_set_multivar(key, value ? value : "true", "^$", 0);
672 }
673
674 static void write_config(struct string_list *config)
675 {
676         int i;
677
678         for (i = 0; i < config->nr; i++) {
679                 if (git_config_parse_parameter(config->items[i].string,
680                                                write_one_config, NULL) < 0)
681                         die("unable to write parameters to config file");
682         }
683 }
684
685 static void write_refspec_config(const char *src_ref_prefix,
686                 const struct ref *our_head_points_at,
687                 const struct ref *remote_head_points_at,
688                 struct strbuf *branch_top)
689 {
690         struct strbuf key = STRBUF_INIT;
691         struct strbuf value = STRBUF_INIT;
692
693         if (option_mirror || !option_bare) {
694                 if (option_single_branch && !option_mirror) {
695                         if (option_branch) {
696                                 if (starts_with(our_head_points_at->name, "refs/tags/"))
697                                         strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
698                                                 our_head_points_at->name);
699                                 else
700                                         strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
701                                                 branch_top->buf, option_branch);
702                         } else if (remote_head_points_at) {
703                                 const char *head = remote_head_points_at->name;
704                                 if (!skip_prefix(head, "refs/heads/", &head))
705                                         die("BUG: remote HEAD points at non-head?");
706
707                                 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
708                                                 branch_top->buf, head);
709                         }
710                         /*
711                          * otherwise, the next "git fetch" will
712                          * simply fetch from HEAD without updating
713                          * any remote-tracking branch, which is what
714                          * we want.
715                          */
716                 } else {
717                         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
718                 }
719                 /* Configure the remote */
720                 if (value.len) {
721                         strbuf_addf(&key, "remote.%s.fetch", option_origin);
722                         git_config_set_multivar(key.buf, value.buf, "^$", 0);
723                         strbuf_reset(&key);
724
725                         if (option_mirror) {
726                                 strbuf_addf(&key, "remote.%s.mirror", option_origin);
727                                 git_config_set(key.buf, "true");
728                                 strbuf_reset(&key);
729                         }
730                 }
731         }
732
733         strbuf_release(&key);
734         strbuf_release(&value);
735 }
736
737 static void dissociate_from_references(void)
738 {
739         static const char* argv[] = { "repack", "-a", "-d", NULL };
740
741         if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
742                 die(_("cannot repack to clean up"));
743         if (unlink(git_path("objects/info/alternates")) && errno != ENOENT)
744                 die_errno(_("cannot unlink temporary alternates file"));
745 }
746
747 int cmd_clone(int argc, const char **argv, const char *prefix)
748 {
749         int is_bundle = 0, is_local;
750         struct stat buf;
751         const char *repo_name, *repo, *work_tree, *git_dir;
752         char *path, *dir;
753         int dest_exists;
754         const struct ref *refs, *remote_head;
755         const struct ref *remote_head_points_at;
756         const struct ref *our_head_points_at;
757         struct ref *mapped_refs;
758         const struct ref *ref;
759         struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
760         struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
761         struct transport *transport = NULL;
762         const char *src_ref_prefix = "refs/heads/";
763         struct remote *remote;
764         int err = 0, complete_refs_before_fetch = 1;
765
766         struct refspec *refspec;
767         const char *fetch_pattern;
768
769         packet_trace_identity("clone");
770         argc = parse_options(argc, argv, prefix, builtin_clone_options,
771                              builtin_clone_usage, 0);
772
773         if (argc > 2)
774                 usage_msg_opt(_("Too many arguments."),
775                         builtin_clone_usage, builtin_clone_options);
776
777         if (argc == 0)
778                 usage_msg_opt(_("You must specify a repository to clone."),
779                         builtin_clone_usage, builtin_clone_options);
780
781         if (option_single_branch == -1)
782                 option_single_branch = option_depth ? 1 : 0;
783
784         if (option_mirror)
785                 option_bare = 1;
786
787         if (option_bare) {
788                 if (option_origin)
789                         die(_("--bare and --origin %s options are incompatible."),
790                             option_origin);
791                 if (real_git_dir)
792                         die(_("--bare and --separate-git-dir are incompatible."));
793                 option_no_checkout = 1;
794         }
795
796         if (!option_origin)
797                 option_origin = "origin";
798
799         repo_name = argv[0];
800
801         path = get_repo_path(repo_name, &is_bundle);
802         if (path)
803                 repo = xstrdup(absolute_path(repo_name));
804         else if (!strchr(repo_name, ':'))
805                 die(_("repository '%s' does not exist"), repo_name);
806         else
807                 repo = repo_name;
808
809         /* no need to be strict, transport_set_option() will validate it again */
810         if (option_depth && atoi(option_depth) < 1)
811                 die(_("depth %s is not a positive number"), option_depth);
812
813         if (argc == 2)
814                 dir = xstrdup(argv[1]);
815         else
816                 dir = guess_dir_name(repo_name, is_bundle, option_bare);
817         strip_trailing_slashes(dir);
818
819         dest_exists = !stat(dir, &buf);
820         if (dest_exists && !is_empty_dir(dir))
821                 die(_("destination path '%s' already exists and is not "
822                         "an empty directory."), dir);
823
824         strbuf_addf(&reflog_msg, "clone: from %s", repo);
825
826         if (option_bare)
827                 work_tree = NULL;
828         else {
829                 work_tree = getenv("GIT_WORK_TREE");
830                 if (work_tree && !stat(work_tree, &buf))
831                         die(_("working tree '%s' already exists."), work_tree);
832         }
833
834         if (option_bare || work_tree)
835                 git_dir = xstrdup(dir);
836         else {
837                 work_tree = dir;
838                 git_dir = mkpathdup("%s/.git", dir);
839         }
840
841         atexit(remove_junk);
842         sigchain_push_common(remove_junk_on_signal);
843
844         if (!option_bare) {
845                 if (safe_create_leading_directories_const(work_tree) < 0)
846                         die_errno(_("could not create leading directories of '%s'"),
847                                   work_tree);
848                 if (!dest_exists && mkdir(work_tree, 0777))
849                         die_errno(_("could not create work tree dir '%s'"),
850                                   work_tree);
851                 junk_work_tree = work_tree;
852                 set_git_work_tree(work_tree);
853         }
854
855         junk_git_dir = git_dir;
856         if (safe_create_leading_directories_const(git_dir) < 0)
857                 die(_("could not create leading directories of '%s'"), git_dir);
858
859         set_git_dir_init(git_dir, real_git_dir, 0);
860         if (real_git_dir) {
861                 git_dir = real_git_dir;
862                 junk_git_dir = real_git_dir;
863         }
864
865         if (0 <= option_verbosity) {
866                 if (option_bare)
867                         fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
868                 else
869                         fprintf(stderr, _("Cloning into '%s'...\n"), dir);
870         }
871         init_db(option_template, INIT_DB_QUIET);
872         write_config(&option_config);
873
874         git_config(git_default_config, NULL);
875
876         if (option_bare) {
877                 if (option_mirror)
878                         src_ref_prefix = "refs/";
879                 strbuf_addstr(&branch_top, src_ref_prefix);
880
881                 git_config_set("core.bare", "true");
882         } else {
883                 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
884         }
885
886         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
887         strbuf_addf(&key, "remote.%s.url", option_origin);
888         git_config_set(key.buf, repo);
889         strbuf_reset(&key);
890
891         if (option_reference.nr)
892                 setup_reference();
893         else if (option_dissociate) {
894                 warning(_("--dissociate given, but there is no --reference"));
895                 option_dissociate = 0;
896         }
897
898         fetch_pattern = value.buf;
899         refspec = parse_fetch_refspec(1, &fetch_pattern);
900
901         strbuf_reset(&value);
902
903         remote = remote_get(option_origin);
904         transport = transport_get(remote, remote->url[0]);
905         transport_set_verbosity(transport, option_verbosity, option_progress);
906
907         path = get_repo_path(remote->url[0], &is_bundle);
908         is_local = option_local != 0 && path && !is_bundle;
909         if (is_local) {
910                 if (option_depth)
911                         warning(_("--depth is ignored in local clones; use file:// instead."));
912                 if (!access(mkpath("%s/shallow", path), F_OK)) {
913                         if (option_local > 0)
914                                 warning(_("source repository is shallow, ignoring --local"));
915                         is_local = 0;
916                 }
917         }
918         if (option_local > 0 && !is_local)
919                 warning(_("--local is ignored"));
920         transport->cloning = 1;
921
922         if (!transport->get_refs_list || (!is_local && !transport->fetch))
923                 die(_("Don't know how to clone %s"), transport->url);
924
925         transport_set_option(transport, TRANS_OPT_KEEP, "yes");
926
927         if (option_depth)
928                 transport_set_option(transport, TRANS_OPT_DEPTH,
929                                      option_depth);
930         if (option_single_branch)
931                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
932
933         if (option_upload_pack)
934                 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
935                                      option_upload_pack);
936
937         if (transport->smart_options && !option_depth)
938                 transport->smart_options->check_self_contained_and_connected = 1;
939
940         refs = transport_get_remote_refs(transport);
941
942         if (refs) {
943                 mapped_refs = wanted_peer_refs(refs, refspec);
944                 /*
945                  * transport_get_remote_refs() may return refs with null sha-1
946                  * in mapped_refs (see struct transport->get_refs_list
947                  * comment). In that case we need fetch it early because
948                  * remote_head code below relies on it.
949                  *
950                  * for normal clones, transport_get_remote_refs() should
951                  * return reliable ref set, we can delay cloning until after
952                  * remote HEAD check.
953                  */
954                 for (ref = refs; ref; ref = ref->next)
955                         if (is_null_sha1(ref->old_sha1)) {
956                                 complete_refs_before_fetch = 0;
957                                 break;
958                         }
959
960                 if (!is_local && !complete_refs_before_fetch)
961                         transport_fetch_refs(transport, mapped_refs);
962
963                 remote_head = find_ref_by_name(refs, "HEAD");
964                 remote_head_points_at =
965                         guess_remote_head(remote_head, mapped_refs, 0);
966
967                 if (option_branch) {
968                         our_head_points_at =
969                                 find_remote_branch(mapped_refs, option_branch);
970
971                         if (!our_head_points_at)
972                                 die(_("Remote branch %s not found in upstream %s"),
973                                     option_branch, option_origin);
974                 }
975                 else
976                         our_head_points_at = remote_head_points_at;
977         }
978         else {
979                 if (option_branch)
980                         die(_("Remote branch %s not found in upstream %s"),
981                                         option_branch, option_origin);
982
983                 warning(_("You appear to have cloned an empty repository."));
984                 mapped_refs = NULL;
985                 our_head_points_at = NULL;
986                 remote_head_points_at = NULL;
987                 remote_head = NULL;
988                 option_no_checkout = 1;
989                 if (!option_bare)
990                         install_branch_config(0, "master", option_origin,
991                                               "refs/heads/master");
992         }
993
994         write_refspec_config(src_ref_prefix, our_head_points_at,
995                         remote_head_points_at, &branch_top);
996
997         if (is_local)
998                 clone_local(path, git_dir);
999         else if (refs && complete_refs_before_fetch)
1000                 transport_fetch_refs(transport, mapped_refs);
1001
1002         update_remote_refs(refs, mapped_refs, remote_head_points_at,
1003                            branch_top.buf, reflog_msg.buf, transport, !is_local);
1004
1005         update_head(our_head_points_at, remote_head, reflog_msg.buf);
1006
1007         transport_unlock_pack(transport);
1008         transport_disconnect(transport);
1009
1010         if (option_dissociate)
1011                 dissociate_from_references();
1012
1013         junk_mode = JUNK_LEAVE_REPO;
1014         err = checkout();
1015
1016         strbuf_release(&reflog_msg);
1017         strbuf_release(&branch_top);
1018         strbuf_release(&key);
1019         strbuf_release(&value);
1020         junk_mode = JUNK_LEAVE_ALL;
1021
1022         free(refspec);
1023         return err;
1024 }