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