Merge branch 'ab/config-based-hooks-base' into seen
[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 #define USE_THE_INDEX_COMPATIBILITY_MACROS
12 #include "builtin.h"
13 #include "config.h"
14 #include "lockfile.h"
15 #include "parse-options.h"
16 #include "fetch-pack.h"
17 #include "refs.h"
18 #include "refspec.h"
19 #include "object-store.h"
20 #include "tree.h"
21 #include "tree-walk.h"
22 #include "unpack-trees.h"
23 #include "transport.h"
24 #include "strbuf.h"
25 #include "dir.h"
26 #include "dir-iterator.h"
27 #include "iterator.h"
28 #include "sigchain.h"
29 #include "branch.h"
30 #include "remote.h"
31 #include "run-command.h"
32 #include "connected.h"
33 #include "packfile.h"
34 #include "list-objects-filter-options.h"
35 #include "hook.h"
36
37 /*
38  * Overall FIXMEs:
39  *  - respect DB_ENVIRONMENT for .git/objects.
40  *
41  * Implementation notes:
42  *  - dropping use-separate-remote and no-separate-remote compatibility
43  *
44  */
45 static const char * const builtin_clone_usage[] = {
46         N_("git clone [<options>] [--] <repo> [<dir>]"),
47         NULL
48 };
49
50 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
51 static int option_local = -1, option_no_hardlinks, option_shared;
52 static int option_no_tags;
53 static int option_shallow_submodules;
54 static int option_reject_shallow = -1;    /* unspecified */
55 static int config_reject_shallow = -1;    /* unspecified */
56 static int deepen;
57 static char *option_template, *option_depth, *option_since;
58 static char *option_origin = NULL;
59 static char *remote_name = NULL;
60 static char *option_branch = NULL;
61 static struct string_list option_not = STRING_LIST_INIT_NODUP;
62 static const char *real_git_dir;
63 static char *option_upload_pack = "git-upload-pack";
64 static int option_verbosity;
65 static int option_progress = -1;
66 static int option_sparse_checkout;
67 static enum transport_family family;
68 static struct string_list option_config = STRING_LIST_INIT_NODUP;
69 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
70 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
71 static int option_dissociate;
72 static int max_jobs = -1;
73 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
74 static struct list_objects_filter_options filter_options;
75 static struct string_list server_options = STRING_LIST_INIT_NODUP;
76 static int option_remote_submodules;
77
78 static int recurse_submodules_cb(const struct option *opt,
79                                  const char *arg, int unset)
80 {
81         if (unset)
82                 string_list_clear((struct string_list *)opt->value, 0);
83         else if (arg)
84                 string_list_append((struct string_list *)opt->value, arg);
85         else
86                 string_list_append((struct string_list *)opt->value,
87                                    (const char *)opt->defval);
88
89         return 0;
90 }
91
92 static struct option builtin_clone_options[] = {
93         OPT__VERBOSITY(&option_verbosity),
94         OPT_BOOL(0, "progress", &option_progress,
95                  N_("force progress reporting")),
96         OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
97                  N_("don't clone shallow repository")),
98         OPT_BOOL('n', "no-checkout", &option_no_checkout,
99                  N_("don't create a checkout")),
100         OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
101         OPT_HIDDEN_BOOL(0, "naked", &option_bare,
102                         N_("create a bare repository")),
103         OPT_BOOL(0, "mirror", &option_mirror,
104                  N_("create a mirror repository (implies bare)")),
105         OPT_BOOL('l', "local", &option_local,
106                 N_("to clone from a local repository")),
107         OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
108                     N_("don't use local hardlinks, always copy")),
109         OPT_BOOL('s', "shared", &option_shared,
110                     N_("setup as shared repository")),
111         { OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
112           N_("pathspec"), N_("initialize submodules in the clone"),
113           PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
114         OPT_ALIAS(0, "recursive", "recurse-submodules"),
115         OPT_INTEGER('j', "jobs", &max_jobs,
116                     N_("number of submodules cloned in parallel")),
117         OPT_STRING(0, "template", &option_template, N_("template-directory"),
118                    N_("directory from which templates will be used")),
119         OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
120                         N_("reference repository")),
121         OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
122                         N_("repo"), N_("reference repository")),
123         OPT_BOOL(0, "dissociate", &option_dissociate,
124                  N_("use --reference only while cloning")),
125         OPT_STRING('o', "origin", &option_origin, N_("name"),
126                    N_("use <name> instead of 'origin' to track upstream")),
127         OPT_STRING('b', "branch", &option_branch, N_("branch"),
128                    N_("checkout <branch> instead of the remote's HEAD")),
129         OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
130                    N_("path to git-upload-pack on the remote")),
131         OPT_STRING(0, "depth", &option_depth, N_("depth"),
132                     N_("create a shallow clone of that depth")),
133         OPT_STRING(0, "shallow-since", &option_since, N_("time"),
134                     N_("create a shallow clone since a specific time")),
135         OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
136                         N_("deepen history of shallow clone, excluding rev")),
137         OPT_BOOL(0, "single-branch", &option_single_branch,
138                     N_("clone only one branch, HEAD or --branch")),
139         OPT_BOOL(0, "no-tags", &option_no_tags,
140                  N_("don't clone any tags, and make later fetches not to follow them")),
141         OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
142                     N_("any cloned submodules will be shallow")),
143         OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
144                    N_("separate git dir from working tree")),
145         OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
146                         N_("set config inside the new repository")),
147         OPT_STRING_LIST(0, "server-option", &server_options,
148                         N_("server-specific"), N_("option to transmit")),
149         OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
150                         TRANSPORT_FAMILY_IPV4),
151         OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
152                         TRANSPORT_FAMILY_IPV6),
153         OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
154         OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
155                     N_("any cloned submodules will use their remote-tracking branch")),
156         OPT_BOOL(0, "sparse", &option_sparse_checkout,
157                     N_("initialize sparse-checkout file to include only files at root")),
158         OPT_END()
159 };
160
161 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
162 {
163         static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
164         static char *bundle_suffix[] = { ".bundle", "" };
165         size_t baselen = path->len;
166         struct stat st;
167         int i;
168
169         for (i = 0; i < ARRAY_SIZE(suffix); i++) {
170                 strbuf_setlen(path, baselen);
171                 strbuf_addstr(path, suffix[i]);
172                 if (stat(path->buf, &st))
173                         continue;
174                 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
175                         *is_bundle = 0;
176                         return path->buf;
177                 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
178                         /* Is it a "gitfile"? */
179                         char signature[8];
180                         const char *dst;
181                         int len, fd = open(path->buf, O_RDONLY);
182                         if (fd < 0)
183                                 continue;
184                         len = read_in_full(fd, signature, 8);
185                         close(fd);
186                         if (len != 8 || strncmp(signature, "gitdir: ", 8))
187                                 continue;
188                         dst = read_gitfile(path->buf);
189                         if (dst) {
190                                 *is_bundle = 0;
191                                 return dst;
192                         }
193                 }
194         }
195
196         for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
197                 strbuf_setlen(path, baselen);
198                 strbuf_addstr(path, bundle_suffix[i]);
199                 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
200                         *is_bundle = 1;
201                         return path->buf;
202                 }
203         }
204
205         return NULL;
206 }
207
208 static char *get_repo_path(const char *repo, int *is_bundle)
209 {
210         struct strbuf path = STRBUF_INIT;
211         const char *raw;
212         char *canon;
213
214         strbuf_addstr(&path, repo);
215         raw = get_repo_path_1(&path, is_bundle);
216         canon = raw ? absolute_pathdup(raw) : NULL;
217         strbuf_release(&path);
218         return canon;
219 }
220
221 static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
222 {
223         const char *end = repo + strlen(repo), *start, *ptr;
224         size_t len;
225         char *dir;
226
227         /*
228          * Skip scheme.
229          */
230         start = strstr(repo, "://");
231         if (start == NULL)
232                 start = repo;
233         else
234                 start += 3;
235
236         /*
237          * Skip authentication data. The stripping does happen
238          * greedily, such that we strip up to the last '@' inside
239          * the host part.
240          */
241         for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
242                 if (*ptr == '@')
243                         start = ptr + 1;
244         }
245
246         /*
247          * Strip trailing spaces, slashes and /.git
248          */
249         while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
250                 end--;
251         if (end - start > 5 && is_dir_sep(end[-5]) &&
252             !strncmp(end - 4, ".git", 4)) {
253                 end -= 5;
254                 while (start < end && is_dir_sep(end[-1]))
255                         end--;
256         }
257
258         /*
259          * Strip trailing port number if we've got only a
260          * hostname (that is, there is no dir separator but a
261          * colon). This check is required such that we do not
262          * strip URI's like '/foo/bar:2222.git', which should
263          * result in a dir '2222' being guessed due to backwards
264          * compatibility.
265          */
266         if (memchr(start, '/', end - start) == NULL
267             && memchr(start, ':', end - start) != NULL) {
268                 ptr = end;
269                 while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
270                         ptr--;
271                 if (start < ptr && ptr[-1] == ':')
272                         end = ptr - 1;
273         }
274
275         /*
276          * Find last component. To remain backwards compatible we
277          * also regard colons as path separators, such that
278          * cloning a repository 'foo:bar.git' would result in a
279          * directory 'bar' being guessed.
280          */
281         ptr = end;
282         while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
283                 ptr--;
284         start = ptr;
285
286         /*
287          * Strip .{bundle,git}.
288          */
289         len = end - start;
290         strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
291
292         if (!len || (len == 1 && *start == '/'))
293                 die(_("No directory name could be guessed.\n"
294                       "Please specify a directory on the command line"));
295
296         if (is_bare)
297                 dir = xstrfmt("%.*s.git", (int)len, start);
298         else
299                 dir = xstrndup(start, len);
300         /*
301          * Replace sequences of 'control' characters and whitespace
302          * with one ascii space, remove leading and trailing spaces.
303          */
304         if (*dir) {
305                 char *out = dir;
306                 int prev_space = 1 /* strip leading whitespace */;
307                 for (end = dir; *end; ++end) {
308                         char ch = *end;
309                         if ((unsigned char)ch < '\x20')
310                                 ch = '\x20';
311                         if (isspace(ch)) {
312                                 if (prev_space)
313                                         continue;
314                                 prev_space = 1;
315                         } else
316                                 prev_space = 0;
317                         *out++ = ch;
318                 }
319                 *out = '\0';
320                 if (out > dir && prev_space)
321                         out[-1] = '\0';
322         }
323         return dir;
324 }
325
326 static void strip_trailing_slashes(char *dir)
327 {
328         char *end = dir + strlen(dir);
329
330         while (dir < end - 1 && is_dir_sep(end[-1]))
331                 end--;
332         *end = '\0';
333 }
334
335 static int add_one_reference(struct string_list_item *item, void *cb_data)
336 {
337         struct strbuf err = STRBUF_INIT;
338         int *required = cb_data;
339         char *ref_git = compute_alternate_path(item->string, &err);
340
341         if (!ref_git) {
342                 if (*required)
343                         die("%s", err.buf);
344                 else
345                         fprintf(stderr,
346                                 _("info: Could not add alternate for '%s': %s\n"),
347                                 item->string, err.buf);
348         } else {
349                 struct strbuf sb = STRBUF_INIT;
350                 strbuf_addf(&sb, "%s/objects", ref_git);
351                 add_to_alternates_file(sb.buf);
352                 strbuf_release(&sb);
353         }
354
355         strbuf_release(&err);
356         free(ref_git);
357         return 0;
358 }
359
360 static void setup_reference(void)
361 {
362         int required = 1;
363         for_each_string_list(&option_required_reference,
364                              add_one_reference, &required);
365         required = 0;
366         for_each_string_list(&option_optional_reference,
367                              add_one_reference, &required);
368 }
369
370 static void copy_alternates(struct strbuf *src, const char *src_repo)
371 {
372         /*
373          * Read from the source objects/info/alternates file
374          * and copy the entries to corresponding file in the
375          * destination repository with add_to_alternates_file().
376          * Both src and dst have "$path/objects/info/alternates".
377          *
378          * Instead of copying bit-for-bit from the original,
379          * we need to append to existing one so that the already
380          * created entry via "clone -s" is not lost, and also
381          * to turn entries with paths relative to the original
382          * absolute, so that they can be used in the new repository.
383          */
384         FILE *in = xfopen(src->buf, "r");
385         struct strbuf line = STRBUF_INIT;
386
387         while (strbuf_getline(&line, in) != EOF) {
388                 char *abs_path;
389                 if (!line.len || line.buf[0] == '#')
390                         continue;
391                 if (is_absolute_path(line.buf)) {
392                         add_to_alternates_file(line.buf);
393                         continue;
394                 }
395                 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
396                 if (!normalize_path_copy(abs_path, abs_path))
397                         add_to_alternates_file(abs_path);
398                 else
399                         warning("skipping invalid relative alternate: %s/%s",
400                                 src_repo, line.buf);
401                 free(abs_path);
402         }
403         strbuf_release(&line);
404         fclose(in);
405 }
406
407 static void mkdir_if_missing(const char *pathname, mode_t mode)
408 {
409         struct stat st;
410
411         if (!mkdir(pathname, mode))
412                 return;
413
414         if (errno != EEXIST)
415                 die_errno(_("failed to create directory '%s'"), pathname);
416         else if (stat(pathname, &st))
417                 die_errno(_("failed to stat '%s'"), pathname);
418         else if (!S_ISDIR(st.st_mode))
419                 die(_("%s exists and is not a directory"), pathname);
420 }
421
422 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
423                                    const char *src_repo)
424 {
425         int src_len, dest_len;
426         struct dir_iterator *iter;
427         int iter_status;
428         unsigned int flags;
429         struct strbuf realpath = STRBUF_INIT;
430
431         mkdir_if_missing(dest->buf, 0777);
432
433         flags = DIR_ITERATOR_PEDANTIC | DIR_ITERATOR_FOLLOW_SYMLINKS;
434         iter = dir_iterator_begin(src->buf, flags);
435
436         if (!iter)
437                 die_errno(_("failed to start iterator over '%s'"), src->buf);
438
439         strbuf_addch(src, '/');
440         src_len = src->len;
441         strbuf_addch(dest, '/');
442         dest_len = dest->len;
443
444         while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
445                 strbuf_setlen(src, src_len);
446                 strbuf_addstr(src, iter->relative_path);
447                 strbuf_setlen(dest, dest_len);
448                 strbuf_addstr(dest, iter->relative_path);
449
450                 if (S_ISDIR(iter->st.st_mode)) {
451                         mkdir_if_missing(dest->buf, 0777);
452                         continue;
453                 }
454
455                 /* Files that cannot be copied bit-for-bit... */
456                 if (!fspathcmp(iter->relative_path, "info/alternates")) {
457                         copy_alternates(src, src_repo);
458                         continue;
459                 }
460
461                 if (unlink(dest->buf) && errno != ENOENT)
462                         die_errno(_("failed to unlink '%s'"), dest->buf);
463                 if (!option_no_hardlinks) {
464                         strbuf_realpath(&realpath, src->buf, 1);
465                         if (!link(realpath.buf, dest->buf))
466                                 continue;
467                         if (option_local > 0)
468                                 die_errno(_("failed to create link '%s'"), dest->buf);
469                         option_no_hardlinks = 1;
470                 }
471                 if (copy_file_with_time(dest->buf, src->buf, 0666))
472                         die_errno(_("failed to copy file to '%s'"), dest->buf);
473         }
474
475         if (iter_status != ITER_DONE) {
476                 strbuf_setlen(src, src_len);
477                 die(_("failed to iterate over '%s'"), src->buf);
478         }
479
480         strbuf_release(&realpath);
481 }
482
483 static void clone_local(const char *src_repo, const char *dest_repo)
484 {
485         if (option_shared) {
486                 struct strbuf alt = STRBUF_INIT;
487                 get_common_dir(&alt, src_repo);
488                 strbuf_addstr(&alt, "/objects");
489                 add_to_alternates_file(alt.buf);
490                 strbuf_release(&alt);
491         } else {
492                 struct strbuf src = STRBUF_INIT;
493                 struct strbuf dest = STRBUF_INIT;
494                 get_common_dir(&src, src_repo);
495                 get_common_dir(&dest, dest_repo);
496                 strbuf_addstr(&src, "/objects");
497                 strbuf_addstr(&dest, "/objects");
498                 copy_or_link_directory(&src, &dest, src_repo);
499                 strbuf_release(&src);
500                 strbuf_release(&dest);
501         }
502
503         if (0 <= option_verbosity)
504                 fprintf(stderr, _("done.\n"));
505 }
506
507 static const char *junk_work_tree;
508 static int junk_work_tree_flags;
509 static const char *junk_git_dir;
510 static int junk_git_dir_flags;
511 static enum {
512         JUNK_LEAVE_NONE,
513         JUNK_LEAVE_REPO,
514         JUNK_LEAVE_ALL
515 } junk_mode = JUNK_LEAVE_NONE;
516
517 static const char junk_leave_repo_msg[] =
518 N_("Clone succeeded, but checkout failed.\n"
519    "You can inspect what was checked out with 'git status'\n"
520    "and retry with 'git restore --source=HEAD :/'\n");
521
522 static void remove_junk(void)
523 {
524         struct strbuf sb = STRBUF_INIT;
525
526         switch (junk_mode) {
527         case JUNK_LEAVE_REPO:
528                 warning("%s", _(junk_leave_repo_msg));
529                 /* fall-through */
530         case JUNK_LEAVE_ALL:
531                 return;
532         default:
533                 /* proceed to removal */
534                 break;
535         }
536
537         if (junk_git_dir) {
538                 strbuf_addstr(&sb, junk_git_dir);
539                 remove_dir_recursively(&sb, junk_git_dir_flags);
540                 strbuf_reset(&sb);
541         }
542         if (junk_work_tree) {
543                 strbuf_addstr(&sb, junk_work_tree);
544                 remove_dir_recursively(&sb, junk_work_tree_flags);
545         }
546         strbuf_release(&sb);
547 }
548
549 static void remove_junk_on_signal(int signo)
550 {
551         remove_junk();
552         sigchain_pop(signo);
553         raise(signo);
554 }
555
556 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
557 {
558         struct ref *ref;
559         struct strbuf head = STRBUF_INIT;
560         strbuf_addstr(&head, "refs/heads/");
561         strbuf_addstr(&head, branch);
562         ref = find_ref_by_name(refs, head.buf);
563         strbuf_release(&head);
564
565         if (ref)
566                 return ref;
567
568         strbuf_addstr(&head, "refs/tags/");
569         strbuf_addstr(&head, branch);
570         ref = find_ref_by_name(refs, head.buf);
571         strbuf_release(&head);
572
573         return ref;
574 }
575
576 static struct ref *wanted_peer_refs(const struct ref *refs,
577                 struct refspec *refspec)
578 {
579         struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
580         struct ref *local_refs = head;
581         struct ref **tail = head ? &head->next : &local_refs;
582
583         if (option_single_branch) {
584                 struct ref *remote_head = NULL;
585
586                 if (!option_branch)
587                         remote_head = guess_remote_head(head, refs, 0);
588                 else {
589                         local_refs = NULL;
590                         tail = &local_refs;
591                         remote_head = copy_ref(find_remote_branch(refs, option_branch));
592                 }
593
594                 if (!remote_head && option_branch)
595                         warning(_("Could not find remote branch %s to clone."),
596                                 option_branch);
597                 else {
598                         int i;
599                         for (i = 0; i < refspec->nr; i++)
600                                 get_fetch_map(remote_head, &refspec->items[i],
601                                               &tail, 0);
602
603                         /* if --branch=tag, pull the requested tag explicitly */
604                         get_fetch_map(remote_head, tag_refspec, &tail, 0);
605                 }
606         } else {
607                 int i;
608                 for (i = 0; i < refspec->nr; i++)
609                         get_fetch_map(refs, &refspec->items[i], &tail, 0);
610         }
611
612         if (!option_mirror && !option_single_branch && !option_no_tags)
613                 get_fetch_map(refs, tag_refspec, &tail, 0);
614
615         return local_refs;
616 }
617
618 static void write_remote_refs(const struct ref *local_refs)
619 {
620         const struct ref *r;
621
622         struct ref_transaction *t;
623         struct strbuf err = STRBUF_INIT;
624
625         t = ref_transaction_begin(&err);
626         if (!t)
627                 die("%s", err.buf);
628
629         for (r = local_refs; r; r = r->next) {
630                 if (!r->peer_ref)
631                         continue;
632                 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
633                                            0, NULL, &err))
634                         die("%s", err.buf);
635         }
636
637         if (initial_ref_transaction_commit(t, &err))
638                 die("%s", err.buf);
639
640         strbuf_release(&err);
641         ref_transaction_free(t);
642 }
643
644 static void write_followtags(const struct ref *refs, const char *msg)
645 {
646         const struct ref *ref;
647         for (ref = refs; ref; ref = ref->next) {
648                 if (!starts_with(ref->name, "refs/tags/"))
649                         continue;
650                 if (ends_with(ref->name, "^{}"))
651                         continue;
652                 if (!has_object_file_with_flags(&ref->old_oid,
653                                                 OBJECT_INFO_QUICK |
654                                                 OBJECT_INFO_SKIP_FETCH_OBJECT))
655                         continue;
656                 update_ref(msg, ref->name, &ref->old_oid, NULL, 0,
657                            UPDATE_REFS_DIE_ON_ERR);
658         }
659 }
660
661 static int iterate_ref_map(void *cb_data, struct object_id *oid)
662 {
663         struct ref **rm = cb_data;
664         struct ref *ref = *rm;
665
666         /*
667          * Skip anything missing a peer_ref, which we are not
668          * actually going to write a ref for.
669          */
670         while (ref && !ref->peer_ref)
671                 ref = ref->next;
672         /* Returning -1 notes "end of list" to the caller. */
673         if (!ref)
674                 return -1;
675
676         oidcpy(oid, &ref->old_oid);
677         *rm = ref->next;
678         return 0;
679 }
680
681 static void update_remote_refs(const struct ref *refs,
682                                const struct ref *mapped_refs,
683                                const struct ref *remote_head_points_at,
684                                const char *branch_top,
685                                const char *msg,
686                                struct transport *transport,
687                                int check_connectivity)
688 {
689         const struct ref *rm = mapped_refs;
690
691         if (check_connectivity) {
692                 struct check_connected_options opt = CHECK_CONNECTED_INIT;
693
694                 opt.transport = transport;
695                 opt.progress = transport->progress;
696
697                 if (check_connected(iterate_ref_map, &rm, &opt))
698                         die(_("remote did not send all necessary objects"));
699         }
700
701         if (refs) {
702                 write_remote_refs(mapped_refs);
703                 if (option_single_branch && !option_no_tags)
704                         write_followtags(refs, msg);
705         }
706
707         if (remote_head_points_at && !option_bare) {
708                 struct strbuf head_ref = STRBUF_INIT;
709                 strbuf_addstr(&head_ref, branch_top);
710                 strbuf_addstr(&head_ref, "HEAD");
711                 if (create_symref(head_ref.buf,
712                                   remote_head_points_at->peer_ref->name,
713                                   msg) < 0)
714                         die(_("unable to update %s"), head_ref.buf);
715                 strbuf_release(&head_ref);
716         }
717 }
718
719 static void update_head(const struct ref *our, const struct ref *remote,
720                         const char *msg)
721 {
722         const char *head;
723         if (our && skip_prefix(our->name, "refs/heads/", &head)) {
724                 /* Local default branch link */
725                 if (create_symref("HEAD", our->name, NULL) < 0)
726                         die(_("unable to update HEAD"));
727                 if (!option_bare) {
728                         update_ref(msg, "HEAD", &our->old_oid, NULL, 0,
729                                    UPDATE_REFS_DIE_ON_ERR);
730                         install_branch_config(0, head, remote_name, our->name);
731                 }
732         } else if (our) {
733                 struct commit *c = lookup_commit_reference(the_repository,
734                                                            &our->old_oid);
735                 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
736                 update_ref(msg, "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
737                            UPDATE_REFS_DIE_ON_ERR);
738         } else if (remote) {
739                 /*
740                  * We know remote HEAD points to a non-branch, or
741                  * HEAD points to a branch but we don't know which one.
742                  * Detach HEAD in all these cases.
743                  */
744                 update_ref(msg, "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
745                            UPDATE_REFS_DIE_ON_ERR);
746         }
747 }
748
749 static int git_sparse_checkout_init(const char *repo)
750 {
751         struct strvec argv = STRVEC_INIT;
752         int result = 0;
753         strvec_pushl(&argv, "-C", repo, "sparse-checkout", "init", NULL);
754
755         /*
756          * We must apply the setting in the current process
757          * for the later checkout to use the sparse-checkout file.
758          */
759         core_apply_sparse_checkout = 1;
760
761         if (run_command_v_opt(argv.v, RUN_GIT_CMD)) {
762                 error(_("failed to initialize sparse-checkout"));
763                 result = 1;
764         }
765
766         strvec_clear(&argv);
767         return result;
768 }
769
770 static int checkout(int submodule_progress)
771 {
772         struct object_id oid;
773         char *head;
774         struct lock_file lock_file = LOCK_INIT;
775         struct unpack_trees_options opts;
776         struct tree *tree;
777         struct tree_desc t;
778         int err = 0;
779         struct run_hooks_opt hook_opt = RUN_HOOKS_OPT_INIT;
780
781         if (option_no_checkout)
782                 return 0;
783
784         head = resolve_refdup("HEAD", RESOLVE_REF_READING, &oid, NULL);
785         if (!head) {
786                 warning(_("remote HEAD refers to nonexistent ref, "
787                           "unable to checkout.\n"));
788                 return 0;
789         }
790         if (!strcmp(head, "HEAD")) {
791                 if (advice_detached_head)
792                         detach_advice(oid_to_hex(&oid));
793                 FREE_AND_NULL(head);
794         } else {
795                 if (!starts_with(head, "refs/heads/"))
796                         die(_("HEAD not found below refs/heads!"));
797         }
798
799         /* We need to be in the new work tree for the checkout */
800         setup_work_tree();
801
802         hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
803
804         memset(&opts, 0, sizeof opts);
805         opts.update = 1;
806         opts.merge = 1;
807         opts.clone = 1;
808         opts.fn = oneway_merge;
809         opts.verbose_update = (option_verbosity >= 0);
810         opts.src_index = &the_index;
811         opts.dst_index = &the_index;
812         init_checkout_metadata(&opts.meta, head, &oid, NULL);
813
814         tree = parse_tree_indirect(&oid);
815         parse_tree(tree);
816         init_tree_desc(&t, tree->buffer, tree->size);
817         if (unpack_trees(1, &t, &opts) < 0)
818                 die(_("unable to checkout working tree"));
819
820         free(head);
821
822         if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
823                 die(_("unable to write new index file"));
824
825         strvec_pushl(&hook_opt.args, oid_to_hex(null_oid()), oid_to_hex(&oid), "1", NULL);
826         err |= run_hooks("post-checkout", &hook_opt);
827         run_hooks_opt_clear(&hook_opt);
828
829         if (!err && (option_recurse_submodules.nr > 0)) {
830                 struct strvec args = STRVEC_INIT;
831                 strvec_pushl(&args, "submodule", "update", "--require-init", "--recursive", NULL);
832
833                 if (option_shallow_submodules == 1)
834                         strvec_push(&args, "--depth=1");
835
836                 if (max_jobs != -1)
837                         strvec_pushf(&args, "--jobs=%d", max_jobs);
838
839                 if (submodule_progress)
840                         strvec_push(&args, "--progress");
841
842                 if (option_verbosity < 0)
843                         strvec_push(&args, "--quiet");
844
845                 if (option_remote_submodules) {
846                         strvec_push(&args, "--remote");
847                         strvec_push(&args, "--no-fetch");
848                 }
849
850                 if (option_single_branch >= 0)
851                         strvec_push(&args, option_single_branch ?
852                                                "--single-branch" :
853                                                "--no-single-branch");
854
855                 err = run_command_v_opt(args.v, RUN_GIT_CMD);
856                 strvec_clear(&args);
857         }
858
859         return err;
860 }
861
862 static int git_clone_config(const char *k, const char *v, void *cb)
863 {
864         if (!strcmp(k, "clone.defaultremotename")) {
865                 free(remote_name);
866                 remote_name = xstrdup(v);
867         }
868         if (!strcmp(k, "clone.rejectshallow"))
869                 config_reject_shallow = git_config_bool(k, v);
870
871         return git_default_config(k, v, cb);
872 }
873
874 static int write_one_config(const char *key, const char *value, void *data)
875 {
876         /*
877          * give git_clone_config a chance to write config values back to the
878          * environment, since git_config_set_multivar_gently only deals with
879          * config-file writes
880          */
881         int apply_failed = git_clone_config(key, value, data);
882         if (apply_failed)
883                 return apply_failed;
884
885         return git_config_set_multivar_gently(key,
886                                               value ? value : "true",
887                                               CONFIG_REGEX_NONE, 0);
888 }
889
890 static void write_config(struct string_list *config)
891 {
892         int i;
893
894         for (i = 0; i < config->nr; i++) {
895                 if (git_config_parse_parameter(config->items[i].string,
896                                                write_one_config, NULL) < 0)
897                         die(_("unable to write parameters to config file"));
898         }
899 }
900
901 static void write_refspec_config(const char *src_ref_prefix,
902                 const struct ref *our_head_points_at,
903                 const struct ref *remote_head_points_at,
904                 struct strbuf *branch_top)
905 {
906         struct strbuf key = STRBUF_INIT;
907         struct strbuf value = STRBUF_INIT;
908
909         if (option_mirror || !option_bare) {
910                 if (option_single_branch && !option_mirror) {
911                         if (option_branch) {
912                                 if (starts_with(our_head_points_at->name, "refs/tags/"))
913                                         strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
914                                                 our_head_points_at->name);
915                                 else
916                                         strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
917                                                 branch_top->buf, option_branch);
918                         } else if (remote_head_points_at) {
919                                 const char *head = remote_head_points_at->name;
920                                 if (!skip_prefix(head, "refs/heads/", &head))
921                                         BUG("remote HEAD points at non-head?");
922
923                                 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
924                                                 branch_top->buf, head);
925                         }
926                         /*
927                          * otherwise, the next "git fetch" will
928                          * simply fetch from HEAD without updating
929                          * any remote-tracking branch, which is what
930                          * we want.
931                          */
932                 } else {
933                         strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
934                 }
935                 /* Configure the remote */
936                 if (value.len) {
937                         strbuf_addf(&key, "remote.%s.fetch", remote_name);
938                         git_config_set_multivar(key.buf, value.buf, "^$", 0);
939                         strbuf_reset(&key);
940
941                         if (option_mirror) {
942                                 strbuf_addf(&key, "remote.%s.mirror", remote_name);
943                                 git_config_set(key.buf, "true");
944                                 strbuf_reset(&key);
945                         }
946                 }
947         }
948
949         strbuf_release(&key);
950         strbuf_release(&value);
951 }
952
953 static void dissociate_from_references(void)
954 {
955         static const char* argv[] = { "repack", "-a", "-d", NULL };
956         char *alternates = git_pathdup("objects/info/alternates");
957
958         if (!access(alternates, F_OK)) {
959                 if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
960                         die(_("cannot repack to clean up"));
961                 if (unlink(alternates) && errno != ENOENT)
962                         die_errno(_("cannot unlink temporary alternates file"));
963         }
964         free(alternates);
965 }
966
967 static int path_exists(const char *path)
968 {
969         struct stat sb;
970         return !stat(path, &sb);
971 }
972
973 int cmd_clone(int argc, const char **argv, const char *prefix)
974 {
975         int is_bundle = 0, is_local;
976         int reject_shallow = 0;
977         const char *repo_name, *repo, *work_tree, *git_dir;
978         char *path = NULL, *dir, *display_repo = NULL;
979         int dest_exists, real_dest_exists = 0;
980         const struct ref *refs, *remote_head;
981         struct ref *remote_head_points_at = NULL;
982         const struct ref *our_head_points_at;
983         struct ref *mapped_refs;
984         const struct ref *ref;
985         struct strbuf key = STRBUF_INIT;
986         struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
987         struct transport *transport = NULL;
988         const char *src_ref_prefix = "refs/heads/";
989         struct remote *remote;
990         int err = 0, complete_refs_before_fetch = 1;
991         int submodule_progress;
992
993         struct transport_ls_refs_options transport_ls_refs_options =
994                 TRANSPORT_LS_REFS_OPTIONS_INIT;
995
996         packet_trace_identity("clone");
997
998         git_config(git_clone_config, NULL);
999
1000         argc = parse_options(argc, argv, prefix, builtin_clone_options,
1001                              builtin_clone_usage, 0);
1002
1003         if (argc > 2)
1004                 usage_msg_opt(_("Too many arguments."),
1005                         builtin_clone_usage, builtin_clone_options);
1006
1007         if (argc == 0)
1008                 usage_msg_opt(_("You must specify a repository to clone."),
1009                         builtin_clone_usage, builtin_clone_options);
1010
1011         if (option_depth || option_since || option_not.nr)
1012                 deepen = 1;
1013         if (option_single_branch == -1)
1014                 option_single_branch = deepen ? 1 : 0;
1015
1016         if (option_mirror)
1017                 option_bare = 1;
1018
1019         if (option_bare) {
1020                 if (option_origin)
1021                         die(_("--bare and --origin %s options are incompatible."),
1022                             option_origin);
1023                 if (real_git_dir)
1024                         die(_("--bare and --separate-git-dir are incompatible."));
1025                 option_no_checkout = 1;
1026         }
1027
1028         repo_name = argv[0];
1029
1030         path = get_repo_path(repo_name, &is_bundle);
1031         if (path) {
1032                 FREE_AND_NULL(path);
1033                 repo = absolute_pathdup(repo_name);
1034         } else if (strchr(repo_name, ':')) {
1035                 repo = repo_name;
1036                 display_repo = transport_anonymize_url(repo);
1037         } else
1038                 die(_("repository '%s' does not exist"), repo_name);
1039
1040         /* no need to be strict, transport_set_option() will validate it again */
1041         if (option_depth && atoi(option_depth) < 1)
1042                 die(_("depth %s is not a positive number"), option_depth);
1043
1044         if (argc == 2)
1045                 dir = xstrdup(argv[1]);
1046         else
1047                 dir = guess_dir_name(repo_name, is_bundle, option_bare);
1048         strip_trailing_slashes(dir);
1049
1050         dest_exists = path_exists(dir);
1051         if (dest_exists && !is_empty_dir(dir))
1052                 die(_("destination path '%s' already exists and is not "
1053                         "an empty directory."), dir);
1054
1055         if (real_git_dir) {
1056                 real_dest_exists = path_exists(real_git_dir);
1057                 if (real_dest_exists && !is_empty_dir(real_git_dir))
1058                         die(_("repository path '%s' already exists and is not "
1059                                 "an empty directory."), real_git_dir);
1060         }
1061
1062
1063         strbuf_addf(&reflog_msg, "clone: from %s",
1064                     display_repo ? display_repo : repo);
1065         free(display_repo);
1066
1067         if (option_bare)
1068                 work_tree = NULL;
1069         else {
1070                 work_tree = getenv("GIT_WORK_TREE");
1071                 if (work_tree && path_exists(work_tree))
1072                         die(_("working tree '%s' already exists."), work_tree);
1073         }
1074
1075         if (option_bare || work_tree)
1076                 git_dir = xstrdup(dir);
1077         else {
1078                 work_tree = dir;
1079                 git_dir = mkpathdup("%s/.git", dir);
1080         }
1081
1082         atexit(remove_junk);
1083         sigchain_push_common(remove_junk_on_signal);
1084
1085         if (!option_bare) {
1086                 if (safe_create_leading_directories_const(work_tree) < 0)
1087                         die_errno(_("could not create leading directories of '%s'"),
1088                                   work_tree);
1089                 if (dest_exists)
1090                         junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1091                 else if (mkdir(work_tree, 0777))
1092                         die_errno(_("could not create work tree dir '%s'"),
1093                                   work_tree);
1094                 junk_work_tree = work_tree;
1095                 set_git_work_tree(work_tree);
1096         }
1097
1098         if (real_git_dir) {
1099                 if (real_dest_exists)
1100                         junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1101                 junk_git_dir = real_git_dir;
1102         } else {
1103                 if (dest_exists)
1104                         junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1105                 junk_git_dir = git_dir;
1106         }
1107         if (safe_create_leading_directories_const(git_dir) < 0)
1108                 die(_("could not create leading directories of '%s'"), git_dir);
1109
1110         if (0 <= option_verbosity) {
1111                 if (option_bare)
1112                         fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1113                 else
1114                         fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1115         }
1116
1117         if (option_recurse_submodules.nr > 0) {
1118                 struct string_list_item *item;
1119                 struct strbuf sb = STRBUF_INIT;
1120
1121                 /* remove duplicates */
1122                 string_list_sort(&option_recurse_submodules);
1123                 string_list_remove_duplicates(&option_recurse_submodules, 0);
1124
1125                 /*
1126                  * NEEDSWORK: In a multi-working-tree world, this needs to be
1127                  * set in the per-worktree config.
1128                  */
1129                 for_each_string_list_item(item, &option_recurse_submodules) {
1130                         strbuf_addf(&sb, "submodule.active=%s",
1131                                     item->string);
1132                         string_list_append(&option_config,
1133                                            strbuf_detach(&sb, NULL));
1134                 }
1135
1136                 if (option_required_reference.nr &&
1137                     option_optional_reference.nr)
1138                         die(_("clone --recursive is not compatible with "
1139                               "both --reference and --reference-if-able"));
1140                 else if (option_required_reference.nr) {
1141                         string_list_append(&option_config,
1142                                 "submodule.alternateLocation=superproject");
1143                         string_list_append(&option_config,
1144                                 "submodule.alternateErrorStrategy=die");
1145                 } else if (option_optional_reference.nr) {
1146                         string_list_append(&option_config,
1147                                 "submodule.alternateLocation=superproject");
1148                         string_list_append(&option_config,
1149                                 "submodule.alternateErrorStrategy=info");
1150                 }
1151         }
1152
1153         init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN, NULL,
1154                 INIT_DB_QUIET);
1155
1156         if (real_git_dir)
1157                 git_dir = real_git_dir;
1158
1159         /*
1160          * additional config can be injected with -c, make sure it's included
1161          * after init_db, which clears the entire config environment.
1162          */
1163         write_config(&option_config);
1164
1165         /*
1166          * re-read config after init_db and write_config to pick up any config
1167          * injected by --template and --config, respectively.
1168          */
1169         git_config(git_clone_config, NULL);
1170
1171         /*
1172          * If option_reject_shallow is specified from CLI option,
1173          * ignore config_reject_shallow from git_clone_config.
1174          */
1175         if (config_reject_shallow != -1)
1176                 reject_shallow = config_reject_shallow;
1177         if (option_reject_shallow != -1)
1178                 reject_shallow = option_reject_shallow;
1179
1180         /*
1181          * apply the remote name provided by --origin only after this second
1182          * call to git_config, to ensure it overrides all config-based values.
1183          */
1184         if (option_origin != NULL)
1185                 remote_name = xstrdup(option_origin);
1186
1187         if (remote_name == NULL)
1188                 remote_name = xstrdup("origin");
1189
1190         if (!valid_remote_name(remote_name))
1191                 die(_("'%s' is not a valid remote name"), remote_name);
1192
1193         if (option_bare) {
1194                 if (option_mirror)
1195                         src_ref_prefix = "refs/";
1196                 strbuf_addstr(&branch_top, src_ref_prefix);
1197
1198                 git_config_set("core.bare", "true");
1199         } else {
1200                 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1201         }
1202
1203         strbuf_addf(&key, "remote.%s.url", remote_name);
1204         git_config_set(key.buf, repo);
1205         strbuf_reset(&key);
1206
1207         if (option_no_tags) {
1208                 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1209                 git_config_set(key.buf, "--no-tags");
1210                 strbuf_reset(&key);
1211         }
1212
1213         if (option_required_reference.nr || option_optional_reference.nr)
1214                 setup_reference();
1215
1216         if (option_sparse_checkout && git_sparse_checkout_init(dir))
1217                 return 1;
1218
1219         remote = remote_get(remote_name);
1220
1221         refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1222                         branch_top.buf);
1223
1224         transport = transport_get(remote, remote->url[0]);
1225         transport_set_verbosity(transport, option_verbosity, option_progress);
1226         transport->family = family;
1227
1228         path = get_repo_path(remote->url[0], &is_bundle);
1229         is_local = option_local != 0 && path && !is_bundle;
1230         if (is_local) {
1231                 if (option_depth)
1232                         warning(_("--depth is ignored in local clones; use file:// instead."));
1233                 if (option_since)
1234                         warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1235                 if (option_not.nr)
1236                         warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1237                 if (filter_options.choice)
1238                         warning(_("--filter is ignored in local clones; use file:// instead."));
1239                 if (!access(mkpath("%s/shallow", path), F_OK)) {
1240                         if (reject_shallow)
1241                                 die(_("source repository is shallow, reject to clone."));
1242                         if (option_local > 0)
1243                                 warning(_("source repository is shallow, ignoring --local"));
1244                         is_local = 0;
1245                 }
1246         }
1247         if (option_local > 0 && !is_local)
1248                 warning(_("--local is ignored"));
1249         transport->cloning = 1;
1250
1251         transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1252
1253         if (reject_shallow)
1254                 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1255         if (option_depth)
1256                 transport_set_option(transport, TRANS_OPT_DEPTH,
1257                                      option_depth);
1258         if (option_since)
1259                 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1260                                      option_since);
1261         if (option_not.nr)
1262                 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1263                                      (const char *)&option_not);
1264         if (option_single_branch)
1265                 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1266
1267         if (option_upload_pack)
1268                 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1269                                      option_upload_pack);
1270
1271         if (server_options.nr)
1272                 transport->server_options = &server_options;
1273
1274         if (filter_options.choice) {
1275                 const char *spec =
1276                         expand_list_objects_filter_spec(&filter_options);
1277                 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1278                                      spec);
1279                 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1280         }
1281
1282         if (transport->smart_options && !deepen && !filter_options.choice)
1283                 transport->smart_options->check_self_contained_and_connected = 1;
1284
1285
1286         strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1287         refspec_ref_prefixes(&remote->fetch,
1288                              &transport_ls_refs_options.ref_prefixes);
1289         if (option_branch)
1290                 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1291                                   option_branch);
1292         if (!option_no_tags)
1293                 strvec_push(&transport_ls_refs_options.ref_prefixes,
1294                             "refs/tags/");
1295
1296         refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1297
1298         if (refs) {
1299                 int hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1300
1301                 /*
1302                  * Now that we know what algorithm the remote side is using,
1303                  * let's set ours to the same thing.
1304                  */
1305                 initialize_repository_version(hash_algo, 1);
1306                 repo_set_hash_algo(the_repository, hash_algo);
1307
1308                 mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1309                 /*
1310                  * transport_get_remote_refs() may return refs with null sha-1
1311                  * in mapped_refs (see struct transport->get_refs_list
1312                  * comment). In that case we need fetch it early because
1313                  * remote_head code below relies on it.
1314                  *
1315                  * for normal clones, transport_get_remote_refs() should
1316                  * return reliable ref set, we can delay cloning until after
1317                  * remote HEAD check.
1318                  */
1319                 for (ref = refs; ref; ref = ref->next)
1320                         if (is_null_oid(&ref->old_oid)) {
1321                                 complete_refs_before_fetch = 0;
1322                                 break;
1323                         }
1324
1325                 if (!is_local && !complete_refs_before_fetch) {
1326                         if (transport_fetch_refs(transport, mapped_refs))
1327                                 die(_("remote transport reported error"));
1328                 }
1329
1330                 remote_head = find_ref_by_name(refs, "HEAD");
1331                 remote_head_points_at =
1332                         guess_remote_head(remote_head, mapped_refs, 0);
1333
1334                 if (option_branch) {
1335                         our_head_points_at =
1336                                 find_remote_branch(mapped_refs, option_branch);
1337
1338                         if (!our_head_points_at)
1339                                 die(_("Remote branch %s not found in upstream %s"),
1340                                     option_branch, remote_name);
1341                 }
1342                 else
1343                         our_head_points_at = remote_head_points_at;
1344         }
1345         else {
1346                 if (option_branch)
1347                         die(_("Remote branch %s not found in upstream %s"),
1348                                         option_branch, remote_name);
1349
1350                 warning(_("You appear to have cloned an empty repository."));
1351                 mapped_refs = NULL;
1352                 our_head_points_at = NULL;
1353                 remote_head_points_at = NULL;
1354                 remote_head = NULL;
1355                 option_no_checkout = 1;
1356                 if (!option_bare) {
1357                         const char *branch;
1358                         char *ref;
1359
1360                         if (transport_ls_refs_options.unborn_head_target &&
1361                             skip_prefix(transport_ls_refs_options.unborn_head_target,
1362                                         "refs/heads/", &branch)) {
1363                                 ref = transport_ls_refs_options.unborn_head_target;
1364                                 transport_ls_refs_options.unborn_head_target = NULL;
1365                                 create_symref("HEAD", ref, reflog_msg.buf);
1366                         } else {
1367                                 branch = git_default_branch_name(0);
1368                                 ref = xstrfmt("refs/heads/%s", branch);
1369                         }
1370
1371                         install_branch_config(0, branch, remote_name, ref);
1372                         free(ref);
1373                 }
1374         }
1375
1376         write_refspec_config(src_ref_prefix, our_head_points_at,
1377                         remote_head_points_at, &branch_top);
1378
1379         if (filter_options.choice)
1380                 partial_clone_register(remote_name, &filter_options);
1381
1382         if (is_local)
1383                 clone_local(path, git_dir);
1384         else if (refs && complete_refs_before_fetch) {
1385                 if (transport_fetch_refs(transport, mapped_refs))
1386                         die(_("remote transport reported error"));
1387         }
1388
1389         update_remote_refs(refs, mapped_refs, remote_head_points_at,
1390                            branch_top.buf, reflog_msg.buf, transport,
1391                            !is_local);
1392
1393         update_head(our_head_points_at, remote_head, reflog_msg.buf);
1394
1395         /*
1396          * We want to show progress for recursive submodule clones iff
1397          * we did so for the main clone. But only the transport knows
1398          * the final decision for this flag, so we need to rescue the value
1399          * before we free the transport.
1400          */
1401         submodule_progress = transport->progress;
1402
1403         transport_unlock_pack(transport);
1404         transport_disconnect(transport);
1405
1406         if (option_dissociate) {
1407                 close_object_store(the_repository->objects);
1408                 dissociate_from_references();
1409         }
1410
1411         junk_mode = JUNK_LEAVE_REPO;
1412         err = checkout(submodule_progress);
1413
1414         free(remote_name);
1415         strbuf_release(&reflog_msg);
1416         strbuf_release(&branch_top);
1417         strbuf_release(&key);
1418         free_refs(mapped_refs);
1419         free_refs(remote_head_points_at);
1420         free(dir);
1421         free(path);
1422         UNLEAK(repo);
1423         junk_mode = JUNK_LEAVE_ALL;
1424
1425         strvec_clear(&transport_ls_refs_options.ref_prefixes);
1426         free(transport_ls_refs_options.unborn_head_target);
1427         return err;
1428 }