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