clone: clarify option_reference as required
[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_required_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_required_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         struct strbuf err = STRBUF_INIT;
286         struct strbuf sb = STRBUF_INIT;
287         char *ref_git = compute_alternate_path(item->string, &err);
288
289         if (!ref_git)
290                 die("%s", err.buf);
291
292         strbuf_addf(&sb, "%s/objects", ref_git);
293         add_to_alternates_file(sb.buf);
294
295         free(ref_git);
296         strbuf_release(&err);
297         strbuf_release(&sb);
298         return 0;
299 }
300
301 static void setup_reference(void)
302 {
303         for_each_string_list(&option_required_reference, add_one_reference, NULL);
304 }
305
306 static void copy_alternates(struct strbuf *src, struct strbuf *dst,
307                             const char *src_repo)
308 {
309         /*
310          * Read from the source objects/info/alternates file
311          * and copy the entries to corresponding file in the
312          * destination repository with add_to_alternates_file().
313          * Both src and dst have "$path/objects/info/alternates".
314          *
315          * Instead of copying bit-for-bit from the original,
316          * we need to append to existing one so that the already
317          * created entry via "clone -s" is not lost, and also
318          * to turn entries with paths relative to the original
319          * absolute, so that they can be used in the new repository.
320          */
321         FILE *in = fopen(src->buf, "r");
322         struct strbuf line = STRBUF_INIT;
323
324         while (strbuf_getline(&line, in) != EOF) {
325                 char *abs_path;
326                 if (!line.len || line.buf[0] == '#')
327                         continue;
328                 if (is_absolute_path(line.buf)) {
329                         add_to_alternates_file(line.buf);
330                         continue;
331                 }
332                 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
333                 normalize_path_copy(abs_path, abs_path);
334                 add_to_alternates_file(abs_path);
335                 free(abs_path);
336         }
337         strbuf_release(&line);
338         fclose(in);
339 }
340
341 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
342                                    const char *src_repo, int src_baselen)
343 {
344         struct dirent *de;
345         struct stat buf;
346         int src_len, dest_len;
347         DIR *dir;
348
349         dir = opendir(src->buf);
350         if (!dir)
351                 die_errno(_("failed to open '%s'"), src->buf);
352
353         if (mkdir(dest->buf, 0777)) {
354                 if (errno != EEXIST)
355                         die_errno(_("failed to create directory '%s'"), dest->buf);
356                 else if (stat(dest->buf, &buf))
357                         die_errno(_("failed to stat '%s'"), dest->buf);
358                 else if (!S_ISDIR(buf.st_mode))
359                         die(_("%s exists and is not a directory"), dest->buf);
360         }
361
362         strbuf_addch(src, '/');
363         src_len = src->len;
364         strbuf_addch(dest, '/');
365         dest_len = dest->len;
366
367         while ((de = readdir(dir)) != NULL) {
368                 strbuf_setlen(src, src_len);
369                 strbuf_addstr(src, de->d_name);
370                 strbuf_setlen(dest, dest_len);
371                 strbuf_addstr(dest, de->d_name);
372                 if (stat(src->buf, &buf)) {
373                         warning (_("failed to stat %s\n"), src->buf);
374                         continue;
375                 }
376                 if (S_ISDIR(buf.st_mode)) {
377                         if (de->d_name[0] != '.')
378                                 copy_or_link_directory(src, dest,
379                                                        src_repo, src_baselen);
380                         continue;
381                 }
382
383                 /* Files that cannot be copied bit-for-bit... */
384                 if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
385                         copy_alternates(src, dest, src_repo);
386                         continue;
387                 }
388
389                 if (unlink(dest->buf) && errno != ENOENT)
390                         die_errno(_("failed to unlink '%s'"), dest->buf);
391                 if (!option_no_hardlinks) {
392                         if (!link(src->buf, dest->buf))
393                                 continue;
394                         if (option_local > 0)
395                                 die_errno(_("failed to create link '%s'"), dest->buf);
396                         option_no_hardlinks = 1;
397                 }
398                 if (copy_file_with_time(dest->buf, src->buf, 0666))
399                         die_errno(_("failed to copy file to '%s'"), dest->buf);
400         }
401         closedir(dir);
402 }
403
404 static void clone_local(const char *src_repo, const char *dest_repo)
405 {
406         if (option_shared) {
407                 struct strbuf alt = STRBUF_INIT;
408                 strbuf_addf(&alt, "%s/objects", src_repo);
409                 add_to_alternates_file(alt.buf);
410                 strbuf_release(&alt);
411         } else {
412                 struct strbuf src = STRBUF_INIT;
413                 struct strbuf dest = STRBUF_INIT;
414                 get_common_dir(&src, src_repo);
415                 get_common_dir(&dest, dest_repo);
416                 strbuf_addstr(&src, "/objects");
417                 strbuf_addstr(&dest, "/objects");
418                 copy_or_link_directory(&src, &dest, src_repo, src.len);
419                 strbuf_release(&src);
420                 strbuf_release(&dest);
421         }
422
423         if (0 <= option_verbosity)
424                 fprintf(stderr, _("done.\n"));
425 }
426
427 static const char *junk_work_tree;
428 static const char *junk_git_dir;
429 static enum {
430         JUNK_LEAVE_NONE,
431         JUNK_LEAVE_REPO,
432         JUNK_LEAVE_ALL
433 } junk_mode = JUNK_LEAVE_NONE;
434
435 static const char junk_leave_repo_msg[] =
436 N_("Clone succeeded, but checkout failed.\n"
437    "You can inspect what was checked out with 'git status'\n"
438    "and retry the checkout with 'git checkout -f HEAD'\n");
439
440 static void remove_junk(void)
441 {
442         struct strbuf sb = STRBUF_INIT;
443
444         switch (junk_mode) {
445         case JUNK_LEAVE_REPO:
446                 warning("%s", _(junk_leave_repo_msg));
447                 /* fall-through */
448         case JUNK_LEAVE_ALL:
449                 return;
450         default:
451                 /* proceed to removal */
452                 break;
453         }
454
455         if (junk_git_dir) {
456                 strbuf_addstr(&sb, junk_git_dir);
457                 remove_dir_recursively(&sb, 0);
458                 strbuf_reset(&sb);
459         }
460         if (junk_work_tree) {
461                 strbuf_addstr(&sb, junk_work_tree);
462                 remove_dir_recursively(&sb, 0);
463                 strbuf_reset(&sb);
464         }
465 }
466
467 static void remove_junk_on_signal(int signo)
468 {
469         remove_junk();
470         sigchain_pop(signo);
471         raise(signo);
472 }
473
474 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
475 {
476         struct ref *ref;
477         struct strbuf head = STRBUF_INIT;
478         strbuf_addstr(&head, "refs/heads/");
479         strbuf_addstr(&head, branch);
480         ref = find_ref_by_name(refs, head.buf);
481         strbuf_release(&head);
482
483         if (ref)
484                 return ref;
485
486         strbuf_addstr(&head, "refs/tags/");
487         strbuf_addstr(&head, branch);
488         ref = find_ref_by_name(refs, head.buf);
489         strbuf_release(&head);
490
491         return ref;
492 }
493
494 static struct ref *wanted_peer_refs(const struct ref *refs,
495                 struct refspec *refspec)
496 {
497         struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
498         struct ref *local_refs = head;
499         struct ref **tail = head ? &head->next : &local_refs;
500
501         if (option_single_branch) {
502                 struct ref *remote_head = NULL;
503
504                 if (!option_branch)
505                         remote_head = guess_remote_head(head, refs, 0);
506                 else {
507                         local_refs = NULL;
508                         tail = &local_refs;
509                         remote_head = copy_ref(find_remote_branch(refs, option_branch));
510                 }
511
512                 if (!remote_head && option_branch)
513                         warning(_("Could not find remote branch %s to clone."),
514                                 option_branch);
515                 else {
516                         get_fetch_map(remote_head, refspec, &tail, 0);
517
518                         /* if --branch=tag, pull the requested tag explicitly */
519                         get_fetch_map(remote_head, tag_refspec, &tail, 0);
520                 }
521         } else
522                 get_fetch_map(refs, refspec, &tail, 0);
523
524         if (!option_mirror && !option_single_branch)
525                 get_fetch_map(refs, tag_refspec, &tail, 0);
526
527         return local_refs;
528 }
529
530 static void write_remote_refs(const struct ref *local_refs)
531 {
532         const struct ref *r;
533
534         struct ref_transaction *t;
535         struct strbuf err = STRBUF_INIT;
536
537         t = ref_transaction_begin(&err);
538         if (!t)
539                 die("%s", err.buf);
540
541         for (r = local_refs; r; r = r->next) {
542                 if (!r->peer_ref)
543                         continue;
544                 if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
545                                            0, NULL, &err))
546                         die("%s", err.buf);
547         }
548
549         if (initial_ref_transaction_commit(t, &err))
550                 die("%s", err.buf);
551
552         strbuf_release(&err);
553         ref_transaction_free(t);
554 }
555
556 static void write_followtags(const struct ref *refs, const char *msg)
557 {
558         const struct ref *ref;
559         for (ref = refs; ref; ref = ref->next) {
560                 if (!starts_with(ref->name, "refs/tags/"))
561                         continue;
562                 if (ends_with(ref->name, "^{}"))
563                         continue;
564                 if (!has_object_file(&ref->old_oid))
565                         continue;
566                 update_ref(msg, ref->name, ref->old_oid.hash,
567                            NULL, 0, UPDATE_REFS_DIE_ON_ERR);
568         }
569 }
570
571 static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
572 {
573         struct ref **rm = cb_data;
574         struct ref *ref = *rm;
575
576         /*
577          * Skip anything missing a peer_ref, which we are not
578          * actually going to write a ref for.
579          */
580         while (ref && !ref->peer_ref)
581                 ref = ref->next;
582         /* Returning -1 notes "end of list" to the caller. */
583         if (!ref)
584                 return -1;
585
586         hashcpy(sha1, ref->old_oid.hash);
587         *rm = ref->next;
588         return 0;
589 }
590
591 static void update_remote_refs(const struct ref *refs,
592                                const struct ref *mapped_refs,
593                                const struct ref *remote_head_points_at,
594                                const char *branch_top,
595                                const char *msg,
596                                struct transport *transport,
597                                int check_connectivity)
598 {
599         const struct ref *rm = mapped_refs;
600
601         if (check_connectivity) {
602                 struct check_connected_options opt = CHECK_CONNECTED_INIT;
603
604                 opt.transport = transport;
605                 opt.progress = transport->progress;
606
607                 if (check_connected(iterate_ref_map, &rm, &opt))
608                         die(_("remote did not send all necessary objects"));
609         }
610
611         if (refs) {
612                 write_remote_refs(mapped_refs);
613                 if (option_single_branch)
614                         write_followtags(refs, msg);
615         }
616
617         if (remote_head_points_at && !option_bare) {
618                 struct strbuf head_ref = STRBUF_INIT;
619                 strbuf_addstr(&head_ref, branch_top);
620                 strbuf_addstr(&head_ref, "HEAD");
621                 if (create_symref(head_ref.buf,
622                                   remote_head_points_at->peer_ref->name,
623                                   msg) < 0)
624                         die(_("unable to update %s"), head_ref.buf);
625                 strbuf_release(&head_ref);
626         }
627 }
628
629 static void update_head(const struct ref *our, const struct ref *remote,
630                         const char *msg)
631 {
632         const char *head;
633         if (our && skip_prefix(our->name, "refs/heads/", &head)) {
634                 /* Local default branch link */
635                 if (create_symref("HEAD", our->name, NULL) < 0)
636                         die(_("unable to update HEAD"));
637                 if (!option_bare) {
638                         update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
639                                    UPDATE_REFS_DIE_ON_ERR);
640                         install_branch_config(0, head, option_origin, our->name);
641                 }
642         } else if (our) {
643                 struct commit *c = lookup_commit_reference(our->old_oid.hash);
644                 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
645                 update_ref(msg, "HEAD", c->object.oid.hash,
646                            NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
647         } else if (remote) {
648                 /*
649                  * We know remote HEAD points to a non-branch, or
650                  * HEAD points to a branch but we don't know which one.
651                  * Detach HEAD in all these cases.
652                  */
653                 update_ref(msg, "HEAD", remote->old_oid.hash,
654                            NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
655         }
656 }
657
658 static int checkout(void)
659 {
660         unsigned char sha1[20];
661         char *head;
662         struct lock_file *lock_file;
663         struct unpack_trees_options opts;
664         struct tree *tree;
665         struct tree_desc t;
666         int err = 0;
667
668         if (option_no_checkout)
669                 return 0;
670
671         head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
672         if (!head) {
673                 warning(_("remote HEAD refers to nonexistent ref, "
674                           "unable to checkout.\n"));
675                 return 0;
676         }
677         if (!strcmp(head, "HEAD")) {
678                 if (advice_detached_head)
679                         detach_advice(sha1_to_hex(sha1));
680         } else {
681                 if (!starts_with(head, "refs/heads/"))
682                         die(_("HEAD not found below refs/heads!"));
683         }
684         free(head);
685
686         /* We need to be in the new work tree for the checkout */
687         setup_work_tree();
688
689         lock_file = xcalloc(1, sizeof(struct lock_file));
690         hold_locked_index(lock_file, 1);
691
692         memset(&opts, 0, sizeof opts);
693         opts.update = 1;
694         opts.merge = 1;
695         opts.fn = oneway_merge;
696         opts.verbose_update = (option_verbosity >= 0);
697         opts.src_index = &the_index;
698         opts.dst_index = &the_index;
699
700         tree = parse_tree_indirect(sha1);
701         parse_tree(tree);
702         init_tree_desc(&t, tree->buffer, tree->size);
703         if (unpack_trees(1, &t, &opts) < 0)
704                 die(_("unable to checkout working tree"));
705
706         if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
707                 die(_("unable to write new index file"));
708
709         err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
710                            sha1_to_hex(sha1), "1", NULL);
711
712         if (!err && option_recursive) {
713                 struct argv_array args = ARGV_ARRAY_INIT;
714                 argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
715
716                 if (option_shallow_submodules == 1)
717                         argv_array_push(&args, "--depth=1");
718
719                 if (max_jobs != -1)
720                         argv_array_pushf(&args, "--jobs=%d", max_jobs);
721
722                 err = run_command_v_opt(args.argv, RUN_GIT_CMD);
723                 argv_array_clear(&args);
724         }
725
726         return err;
727 }
728
729 static int write_one_config(const char *key, const char *value, void *data)
730 {
731         return git_config_set_multivar_gently(key, value ? value : "true", "^$", 0);
732 }
733
734 static void write_config(struct string_list *config)
735 {
736         int i;
737
738         for (i = 0; i < config->nr; i++) {
739                 if (git_config_parse_parameter(config->items[i].string,
740                                                write_one_config, NULL) < 0)
741                         die(_("unable to write parameters to config file"));
742         }
743 }
744
745 static void write_refspec_config(const char *src_ref_prefix,
746                 const struct ref *our_head_points_at,
747                 const struct ref *remote_head_points_at,
748                 struct strbuf *branch_top)
749 {
750         struct strbuf key = STRBUF_INIT;
751         struct strbuf value = STRBUF_INIT;
752
753         if (option_mirror || !option_bare) {
754                 if (option_single_branch && !option_mirror) {
755                         if (option_branch) {
756                                 if (starts_with(our_head_points_at->name, "refs/tags/"))
757                                         strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
758                                                 our_head_points_at->name);
759                                 else
760                                         strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
761                                                 branch_top->buf, option_branch);
762                         } else if (remote_head_points_at) {
763                                 const char *head = remote_head_points_at->name;
764                                 if (!skip_prefix(head, "refs/heads/", &head))
765                                         die("BUG: remote HEAD points at non-head?");
766
767                                 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
768                                                 branch_top->buf, head);
769                         }
770                         /*
771                          * otherwise, the next "git fetch" will
772                          * simply fetch from HEAD without updating
773                          * any remote-tracking branch, which is what
774                          * we want.
775                          */
776                 } else {
777                         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
778                 }
779                 /* Configure the remote */
780                 if (value.len) {
781                         strbuf_addf(&key, "remote.%s.fetch", option_origin);
782                         git_config_set_multivar(key.buf, value.buf, "^$", 0);
783                         strbuf_reset(&key);
784
785                         if (option_mirror) {
786                                 strbuf_addf(&key, "remote.%s.mirror", option_origin);
787                                 git_config_set(key.buf, "true");
788                                 strbuf_reset(&key);
789                         }
790                 }
791         }
792
793         strbuf_release(&key);
794         strbuf_release(&value);
795 }
796
797 static void dissociate_from_references(void)
798 {
799         static const char* argv[] = { "repack", "-a", "-d", NULL };
800         char *alternates = git_pathdup("objects/info/alternates");
801
802         if (!access(alternates, F_OK)) {
803                 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
804                         die(_("cannot repack to clean up"));
805                 if (unlink(alternates) && errno != ENOENT)
806                         die_errno(_("cannot unlink temporary alternates file"));
807         }
808         free(alternates);
809 }
810
811 int cmd_clone(int argc, const char **argv, const char *prefix)
812 {
813         int is_bundle = 0, is_local;
814         struct stat buf;
815         const char *repo_name, *repo, *work_tree, *git_dir;
816         char *path, *dir;
817         int dest_exists;
818         const struct ref *refs, *remote_head;
819         const struct ref *remote_head_points_at;
820         const struct ref *our_head_points_at;
821         struct ref *mapped_refs;
822         const struct ref *ref;
823         struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
824         struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
825         struct transport *transport = NULL;
826         const char *src_ref_prefix = "refs/heads/";
827         struct remote *remote;
828         int err = 0, complete_refs_before_fetch = 1;
829
830         struct refspec *refspec;
831         const char *fetch_pattern;
832
833         packet_trace_identity("clone");
834         argc = parse_options(argc, argv, prefix, builtin_clone_options,
835                              builtin_clone_usage, 0);
836
837         if (argc > 2)
838                 usage_msg_opt(_("Too many arguments."),
839                         builtin_clone_usage, builtin_clone_options);
840
841         if (argc == 0)
842                 usage_msg_opt(_("You must specify a repository to clone."),
843                         builtin_clone_usage, builtin_clone_options);
844
845         if (option_single_branch == -1)
846                 option_single_branch = option_depth ? 1 : 0;
847
848         if (option_mirror)
849                 option_bare = 1;
850
851         if (option_bare) {
852                 if (option_origin)
853                         die(_("--bare and --origin %s options are incompatible."),
854                             option_origin);
855                 if (real_git_dir)
856                         die(_("--bare and --separate-git-dir are incompatible."));
857                 option_no_checkout = 1;
858         }
859
860         if (!option_origin)
861                 option_origin = "origin";
862
863         repo_name = argv[0];
864
865         path = get_repo_path(repo_name, &is_bundle);
866         if (path)
867                 repo = xstrdup(absolute_path(repo_name));
868         else if (!strchr(repo_name, ':'))
869                 die(_("repository '%s' does not exist"), repo_name);
870         else
871                 repo = repo_name;
872
873         /* no need to be strict, transport_set_option() will validate it again */
874         if (option_depth && atoi(option_depth) < 1)
875                 die(_("depth %s is not a positive number"), option_depth);
876
877         if (argc == 2)
878                 dir = xstrdup(argv[1]);
879         else
880                 dir = guess_dir_name(repo_name, is_bundle, option_bare);
881         strip_trailing_slashes(dir);
882
883         dest_exists = !stat(dir, &buf);
884         if (dest_exists && !is_empty_dir(dir))
885                 die(_("destination path '%s' already exists and is not "
886                         "an empty directory."), dir);
887
888         strbuf_addf(&reflog_msg, "clone: from %s", repo);
889
890         if (option_bare)
891                 work_tree = NULL;
892         else {
893                 work_tree = getenv("GIT_WORK_TREE");
894                 if (work_tree && !stat(work_tree, &buf))
895                         die(_("working tree '%s' already exists."), work_tree);
896         }
897
898         if (option_bare || work_tree)
899                 git_dir = xstrdup(dir);
900         else {
901                 work_tree = dir;
902                 git_dir = mkpathdup("%s/.git", dir);
903         }
904
905         atexit(remove_junk);
906         sigchain_push_common(remove_junk_on_signal);
907
908         if (!option_bare) {
909                 if (safe_create_leading_directories_const(work_tree) < 0)
910                         die_errno(_("could not create leading directories of '%s'"),
911                                   work_tree);
912                 if (!dest_exists && mkdir(work_tree, 0777))
913                         die_errno(_("could not create work tree dir '%s'"),
914                                   work_tree);
915                 junk_work_tree = work_tree;
916                 set_git_work_tree(work_tree);
917         }
918
919         junk_git_dir = git_dir;
920         if (safe_create_leading_directories_const(git_dir) < 0)
921                 die(_("could not create leading directories of '%s'"), git_dir);
922
923         set_git_dir_init(git_dir, real_git_dir, 0);
924         if (real_git_dir) {
925                 git_dir = real_git_dir;
926                 junk_git_dir = real_git_dir;
927         }
928
929         if (0 <= option_verbosity) {
930                 if (option_bare)
931                         fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
932                 else
933                         fprintf(stderr, _("Cloning into '%s'...\n"), dir);
934         }
935         init_db(option_template, INIT_DB_QUIET);
936         write_config(&option_config);
937
938         git_config(git_default_config, NULL);
939
940         if (option_bare) {
941                 if (option_mirror)
942                         src_ref_prefix = "refs/";
943                 strbuf_addstr(&branch_top, src_ref_prefix);
944
945                 git_config_set("core.bare", "true");
946         } else {
947                 strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
948         }
949
950         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
951         strbuf_addf(&key, "remote.%s.url", option_origin);
952         git_config_set(key.buf, repo);
953         strbuf_reset(&key);
954
955         if (option_required_reference.nr)
956                 setup_reference();
957
958         fetch_pattern = value.buf;
959         refspec = parse_fetch_refspec(1, &fetch_pattern);
960
961         strbuf_reset(&value);
962
963         remote = remote_get(option_origin);
964         transport = transport_get(remote, remote->url[0]);
965         transport_set_verbosity(transport, option_verbosity, option_progress);
966         transport->family = family;
967
968         path = get_repo_path(remote->url[0], &is_bundle);
969         is_local = option_local != 0 && path && !is_bundle;
970         if (is_local) {
971                 if (option_depth)
972                         warning(_("--depth is ignored in local clones; use file:// instead."));
973                 if (!access(mkpath("%s/shallow", path), F_OK)) {
974                         if (option_local > 0)
975                                 warning(_("source repository is shallow, ignoring --local"));
976                         is_local = 0;
977                 }
978         }
979         if (option_local > 0 && !is_local)
980                 warning(_("--local is ignored"));
981         transport->cloning = 1;
982
983         if (!transport->get_refs_list || (!is_local && !transport->fetch))
984                 die(_("Don't know how to clone %s"), transport->url);
985
986         transport_set_option(transport, TRANS_OPT_KEEP, "yes");
987
988         if (option_depth)
989                 transport_set_option(transport, TRANS_OPT_DEPTH,
990                                      option_depth);
991         if (option_single_branch)
992                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
993
994         if (option_upload_pack)
995                 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
996                                      option_upload_pack);
997
998         if (transport->smart_options && !option_depth)
999                 transport->smart_options->check_self_contained_and_connected = 1;
1000
1001         refs = transport_get_remote_refs(transport);
1002
1003         if (refs) {
1004                 mapped_refs = wanted_peer_refs(refs, refspec);
1005                 /*
1006                  * transport_get_remote_refs() may return refs with null sha-1
1007                  * in mapped_refs (see struct transport->get_refs_list
1008                  * comment). In that case we need fetch it early because
1009                  * remote_head code below relies on it.
1010                  *
1011                  * for normal clones, transport_get_remote_refs() should
1012                  * return reliable ref set, we can delay cloning until after
1013                  * remote HEAD check.
1014                  */
1015                 for (ref = refs; ref; ref = ref->next)
1016                         if (is_null_oid(&ref->old_oid)) {
1017                                 complete_refs_before_fetch = 0;
1018                                 break;
1019                         }
1020
1021                 if (!is_local && !complete_refs_before_fetch)
1022                         transport_fetch_refs(transport, mapped_refs);
1023
1024                 remote_head = find_ref_by_name(refs, "HEAD");
1025                 remote_head_points_at =
1026                         guess_remote_head(remote_head, mapped_refs, 0);
1027
1028                 if (option_branch) {
1029                         our_head_points_at =
1030                                 find_remote_branch(mapped_refs, option_branch);
1031
1032                         if (!our_head_points_at)
1033                                 die(_("Remote branch %s not found in upstream %s"),
1034                                     option_branch, option_origin);
1035                 }
1036                 else
1037                         our_head_points_at = remote_head_points_at;
1038         }
1039         else {
1040                 if (option_branch)
1041                         die(_("Remote branch %s not found in upstream %s"),
1042                                         option_branch, option_origin);
1043
1044                 warning(_("You appear to have cloned an empty repository."));
1045                 mapped_refs = NULL;
1046                 our_head_points_at = NULL;
1047                 remote_head_points_at = NULL;
1048                 remote_head = NULL;
1049                 option_no_checkout = 1;
1050                 if (!option_bare)
1051                         install_branch_config(0, "master", option_origin,
1052                                               "refs/heads/master");
1053         }
1054
1055         write_refspec_config(src_ref_prefix, our_head_points_at,
1056                         remote_head_points_at, &branch_top);
1057
1058         if (is_local)
1059                 clone_local(path, git_dir);
1060         else if (refs && complete_refs_before_fetch)
1061                 transport_fetch_refs(transport, mapped_refs);
1062
1063         update_remote_refs(refs, mapped_refs, remote_head_points_at,
1064                            branch_top.buf, reflog_msg.buf, transport, !is_local);
1065
1066         update_head(our_head_points_at, remote_head, reflog_msg.buf);
1067
1068         transport_unlock_pack(transport);
1069         transport_disconnect(transport);
1070
1071         if (option_dissociate) {
1072                 close_all_packs();
1073                 dissociate_from_references();
1074         }
1075
1076         junk_mode = JUNK_LEAVE_REPO;
1077         err = checkout();
1078
1079         strbuf_release(&reflog_msg);
1080         strbuf_release(&branch_top);
1081         strbuf_release(&key);
1082         strbuf_release(&value);
1083         junk_mode = JUNK_LEAVE_ALL;
1084
1085         free(refspec);
1086         return err;
1087 }