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