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