git

Форк
0
/
clone.c 
1563 строки · 46.5 Кб
1
/*
2
 * Builtin "git clone"
3
 *
4
 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>,
5
 *		 2008 Daniel Barkalow <barkalow@iabervon.org>
6
 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
7
 *
8
 * Clone a repository into a different directory that does not yet exist.
9
 */
10

11
#include "builtin.h"
12
#include "abspath.h"
13
#include "advice.h"
14
#include "config.h"
15
#include "copy.h"
16
#include "environment.h"
17
#include "gettext.h"
18
#include "hex.h"
19
#include "lockfile.h"
20
#include "parse-options.h"
21
#include "refs.h"
22
#include "refspec.h"
23
#include "object-file.h"
24
#include "object-store-ll.h"
25
#include "tree.h"
26
#include "tree-walk.h"
27
#include "unpack-trees.h"
28
#include "transport.h"
29
#include "strbuf.h"
30
#include "dir.h"
31
#include "dir-iterator.h"
32
#include "iterator.h"
33
#include "sigchain.h"
34
#include "branch.h"
35
#include "remote.h"
36
#include "run-command.h"
37
#include "setup.h"
38
#include "connected.h"
39
#include "packfile.h"
40
#include "path.h"
41
#include "pkt-line.h"
42
#include "list-objects-filter-options.h"
43
#include "hook.h"
44
#include "bundle.h"
45
#include "bundle-uri.h"
46

47
/*
48
 * Overall FIXMEs:
49
 *  - respect DB_ENVIRONMENT for .git/objects.
50
 *
51
 * Implementation notes:
52
 *  - dropping use-separate-remote and no-separate-remote compatibility
53
 *
54
 */
55
static const char * const builtin_clone_usage[] = {
56
	N_("git clone [<options>] [--] <repo> [<dir>]"),
57
	NULL
58
};
59

60
static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
61
static int option_local = -1, option_no_hardlinks, option_shared;
62
static int option_no_tags;
63
static int option_shallow_submodules;
64
static int option_reject_shallow = -1;    /* unspecified */
65
static int config_reject_shallow = -1;    /* unspecified */
66
static int deepen;
67
static char *option_template, *option_depth, *option_since;
68
static char *option_origin = NULL;
69
static char *remote_name = NULL;
70
static char *option_branch = NULL;
71
static struct string_list option_not = STRING_LIST_INIT_NODUP;
72
static const char *real_git_dir;
73
static const char *ref_format;
74
static const char *option_upload_pack = "git-upload-pack";
75
static int option_verbosity;
76
static int option_progress = -1;
77
static int option_sparse_checkout;
78
static enum transport_family family;
79
static struct string_list option_config = STRING_LIST_INIT_NODUP;
80
static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
81
static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
82
static int option_dissociate;
83
static int max_jobs = -1;
84
static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
85
static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
86
static int option_filter_submodules = -1;    /* unspecified */
87
static int config_filter_submodules = -1;    /* unspecified */
88
static struct string_list server_options = STRING_LIST_INIT_NODUP;
89
static int option_remote_submodules;
90
static const char *bundle_uri;
91

92
static int recurse_submodules_cb(const struct option *opt,
93
				 const char *arg, int unset)
94
{
95
	if (unset)
96
		string_list_clear((struct string_list *)opt->value, 0);
97
	else if (arg)
98
		string_list_append((struct string_list *)opt->value, arg);
99
	else
100
		string_list_append((struct string_list *)opt->value,
101
				   (const char *)opt->defval);
102

103
	return 0;
104
}
105

106
static struct option builtin_clone_options[] = {
107
	OPT__VERBOSITY(&option_verbosity),
108
	OPT_BOOL(0, "progress", &option_progress,
109
		 N_("force progress reporting")),
110
	OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
111
		 N_("don't clone shallow repository")),
112
	OPT_BOOL('n', "no-checkout", &option_no_checkout,
113
		 N_("don't create a checkout")),
114
	OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
115
	OPT_HIDDEN_BOOL(0, "naked", &option_bare,
116
			N_("create a bare repository")),
117
	OPT_BOOL(0, "mirror", &option_mirror,
118
		 N_("create a mirror repository (implies --bare)")),
119
	OPT_BOOL('l', "local", &option_local,
120
		N_("to clone from a local repository")),
121
	OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
122
		    N_("don't use local hardlinks, always copy")),
123
	OPT_BOOL('s', "shared", &option_shared,
124
		    N_("setup as shared repository")),
125
	{ OPTION_CALLBACK, 0, "recurse-submodules", &option_recurse_submodules,
126
	  N_("pathspec"), N_("initialize submodules in the clone"),
127
	  PARSE_OPT_OPTARG, recurse_submodules_cb, (intptr_t)"." },
128
	OPT_ALIAS(0, "recursive", "recurse-submodules"),
129
	OPT_INTEGER('j', "jobs", &max_jobs,
130
		    N_("number of submodules cloned in parallel")),
131
	OPT_STRING(0, "template", &option_template, N_("template-directory"),
132
		   N_("directory from which templates will be used")),
133
	OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
134
			N_("reference repository")),
135
	OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
136
			N_("repo"), N_("reference repository")),
137
	OPT_BOOL(0, "dissociate", &option_dissociate,
138
		 N_("use --reference only while cloning")),
139
	OPT_STRING('o', "origin", &option_origin, N_("name"),
140
		   N_("use <name> instead of 'origin' to track upstream")),
141
	OPT_STRING('b', "branch", &option_branch, N_("branch"),
142
		   N_("checkout <branch> instead of the remote's HEAD")),
143
	OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
144
		   N_("path to git-upload-pack on the remote")),
145
	OPT_STRING(0, "depth", &option_depth, N_("depth"),
146
		    N_("create a shallow clone of that depth")),
147
	OPT_STRING(0, "shallow-since", &option_since, N_("time"),
148
		    N_("create a shallow clone since a specific time")),
149
	OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("revision"),
150
			N_("deepen history of shallow clone, excluding rev")),
151
	OPT_BOOL(0, "single-branch", &option_single_branch,
152
		    N_("clone only one branch, HEAD or --branch")),
153
	OPT_BOOL(0, "no-tags", &option_no_tags,
154
		 N_("don't clone any tags, and make later fetches not to follow them")),
155
	OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
156
		    N_("any cloned submodules will be shallow")),
157
	OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
158
		   N_("separate git dir from working tree")),
159
	OPT_STRING(0, "ref-format", &ref_format, N_("format"),
160
		   N_("specify the reference format to use")),
161
	OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
162
			N_("set config inside the new repository")),
163
	OPT_STRING_LIST(0, "server-option", &server_options,
164
			N_("server-specific"), N_("option to transmit")),
165
	OPT_IPVERSION(&family),
166
	OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
167
	OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
168
		    N_("apply partial clone filters to submodules")),
169
	OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
170
		    N_("any cloned submodules will use their remote-tracking branch")),
171
	OPT_BOOL(0, "sparse", &option_sparse_checkout,
172
		    N_("initialize sparse-checkout file to include only files at root")),
173
	OPT_STRING(0, "bundle-uri", &bundle_uri,
174
		   N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
175
	OPT_END()
176
};
177

178
static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
179
{
180
	static const char *suffix[] = { "/.git", "", ".git/.git", ".git" };
181
	static const char *bundle_suffix[] = { ".bundle", "" };
182
	size_t baselen = path->len;
183
	struct stat st;
184
	int i;
185

186
	for (i = 0; i < ARRAY_SIZE(suffix); i++) {
187
		strbuf_setlen(path, baselen);
188
		strbuf_addstr(path, suffix[i]);
189
		if (stat(path->buf, &st))
190
			continue;
191
		if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
192
			*is_bundle = 0;
193
			return path->buf;
194
		} else if (S_ISREG(st.st_mode) && st.st_size > 8) {
195
			/* Is it a "gitfile"? */
196
			char signature[8];
197
			const char *dst;
198
			int len, fd = open(path->buf, O_RDONLY);
199
			if (fd < 0)
200
				continue;
201
			len = read_in_full(fd, signature, 8);
202
			close(fd);
203
			if (len != 8 || strncmp(signature, "gitdir: ", 8))
204
				continue;
205
			dst = read_gitfile(path->buf);
206
			if (dst) {
207
				*is_bundle = 0;
208
				return dst;
209
			}
210
		}
211
	}
212

213
	for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
214
		strbuf_setlen(path, baselen);
215
		strbuf_addstr(path, bundle_suffix[i]);
216
		if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
217
			*is_bundle = 1;
218
			return path->buf;
219
		}
220
	}
221

222
	return NULL;
223
}
224

225
static char *get_repo_path(const char *repo, int *is_bundle)
226
{
227
	struct strbuf path = STRBUF_INIT;
228
	const char *raw;
229
	char *canon;
230

231
	strbuf_addstr(&path, repo);
232
	raw = get_repo_path_1(&path, is_bundle);
233
	canon = raw ? absolute_pathdup(raw) : NULL;
234
	strbuf_release(&path);
235
	return canon;
236
}
237

238
static int add_one_reference(struct string_list_item *item, void *cb_data)
239
{
240
	struct strbuf err = STRBUF_INIT;
241
	int *required = cb_data;
242
	char *ref_git = compute_alternate_path(item->string, &err);
243

244
	if (!ref_git) {
245
		if (*required)
246
			die("%s", err.buf);
247
		else
248
			fprintf(stderr,
249
				_("info: Could not add alternate for '%s': %s\n"),
250
				item->string, err.buf);
251
	} else {
252
		struct strbuf sb = STRBUF_INIT;
253
		strbuf_addf(&sb, "%s/objects", ref_git);
254
		add_to_alternates_file(sb.buf);
255
		strbuf_release(&sb);
256
	}
257

258
	strbuf_release(&err);
259
	free(ref_git);
260
	return 0;
261
}
262

263
static void setup_reference(void)
264
{
265
	int required = 1;
266
	for_each_string_list(&option_required_reference,
267
			     add_one_reference, &required);
268
	required = 0;
269
	for_each_string_list(&option_optional_reference,
270
			     add_one_reference, &required);
271
}
272

273
static void copy_alternates(struct strbuf *src, const char *src_repo)
274
{
275
	/*
276
	 * Read from the source objects/info/alternates file
277
	 * and copy the entries to corresponding file in the
278
	 * destination repository with add_to_alternates_file().
279
	 * Both src and dst have "$path/objects/info/alternates".
280
	 *
281
	 * Instead of copying bit-for-bit from the original,
282
	 * we need to append to existing one so that the already
283
	 * created entry via "clone -s" is not lost, and also
284
	 * to turn entries with paths relative to the original
285
	 * absolute, so that they can be used in the new repository.
286
	 */
287
	FILE *in = xfopen(src->buf, "r");
288
	struct strbuf line = STRBUF_INIT;
289

290
	while (strbuf_getline(&line, in) != EOF) {
291
		char *abs_path;
292
		if (!line.len || line.buf[0] == '#')
293
			continue;
294
		if (is_absolute_path(line.buf)) {
295
			add_to_alternates_file(line.buf);
296
			continue;
297
		}
298
		abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
299
		if (!normalize_path_copy(abs_path, abs_path))
300
			add_to_alternates_file(abs_path);
301
		else
302
			warning("skipping invalid relative alternate: %s/%s",
303
				src_repo, line.buf);
304
		free(abs_path);
305
	}
306
	strbuf_release(&line);
307
	fclose(in);
308
}
309

310
static void mkdir_if_missing(const char *pathname, mode_t mode)
311
{
312
	struct stat st;
313

314
	if (!mkdir(pathname, mode))
315
		return;
316

317
	if (errno != EEXIST)
318
		die_errno(_("failed to create directory '%s'"), pathname);
319
	else if (stat(pathname, &st))
320
		die_errno(_("failed to stat '%s'"), pathname);
321
	else if (!S_ISDIR(st.st_mode))
322
		die(_("%s exists and is not a directory"), pathname);
323
}
324

325
static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
326
				   const char *src_repo)
327
{
328
	int src_len, dest_len;
329
	struct dir_iterator *iter;
330
	int iter_status;
331

332
	/*
333
	 * Refuse copying directories by default which aren't owned by us. The
334
	 * code that performs either the copying or hardlinking is not prepared
335
	 * to handle various edge cases where an adversary may for example
336
	 * racily swap out files for symlinks. This can cause us to
337
	 * inadvertently use the wrong source file.
338
	 *
339
	 * Furthermore, even if we were prepared to handle such races safely,
340
	 * creating hardlinks across user boundaries is an inherently unsafe
341
	 * operation as the hardlinked files can be rewritten at will by the
342
	 * potentially-untrusted user. We thus refuse to do so by default.
343
	 */
344
	die_upon_dubious_ownership(NULL, NULL, src_repo);
345

346
	mkdir_if_missing(dest->buf, 0777);
347

348
	iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
349

350
	if (!iter) {
351
		if (errno == ENOTDIR) {
352
			int saved_errno = errno;
353
			struct stat st;
354

355
			if (!lstat(src->buf, &st) && S_ISLNK(st.st_mode))
356
				die(_("'%s' is a symlink, refusing to clone with --local"),
357
				    src->buf);
358
			errno = saved_errno;
359
		}
360
		die_errno(_("failed to start iterator over '%s'"), src->buf);
361
	}
362

363
	strbuf_addch(src, '/');
364
	src_len = src->len;
365
	strbuf_addch(dest, '/');
366
	dest_len = dest->len;
367

368
	while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
369
		strbuf_setlen(src, src_len);
370
		strbuf_addstr(src, iter->relative_path);
371
		strbuf_setlen(dest, dest_len);
372
		strbuf_addstr(dest, iter->relative_path);
373

374
		if (S_ISLNK(iter->st.st_mode))
375
			die(_("symlink '%s' exists, refusing to clone with --local"),
376
			    iter->relative_path);
377

378
		if (S_ISDIR(iter->st.st_mode)) {
379
			mkdir_if_missing(dest->buf, 0777);
380
			continue;
381
		}
382

383
		/* Files that cannot be copied bit-for-bit... */
384
		if (!fspathcmp(iter->relative_path, "info/alternates")) {
385
			copy_alternates(src, src_repo);
386
			continue;
387
		}
388

389
		if (unlink(dest->buf) && errno != ENOENT)
390
			die_errno(_("failed to unlink '%s'"), dest->buf);
391
		if (!option_no_hardlinks) {
392
			if (!link(src->buf, dest->buf)) {
393
				struct stat st;
394

395
				/*
396
				 * Sanity-check whether the created hardlink
397
				 * actually links to the expected file now. This
398
				 * catches time-of-check-time-of-use bugs in
399
				 * case the source file was meanwhile swapped.
400
				 */
401
				if (lstat(dest->buf, &st))
402
					die(_("hardlink cannot be checked at '%s'"), dest->buf);
403
				if (st.st_mode != iter->st.st_mode ||
404
				    st.st_ino != iter->st.st_ino ||
405
				    st.st_dev != iter->st.st_dev ||
406
				    st.st_size != iter->st.st_size ||
407
				    st.st_uid != iter->st.st_uid ||
408
				    st.st_gid != iter->st.st_gid)
409
					die(_("hardlink different from source at '%s'"), dest->buf);
410

411
				continue;
412
			}
413
			if (option_local > 0)
414
				die_errno(_("failed to create link '%s'"), dest->buf);
415
			option_no_hardlinks = 1;
416
		}
417
		if (copy_file_with_time(dest->buf, src->buf, 0666))
418
			die_errno(_("failed to copy file to '%s'"), dest->buf);
419
	}
420

421
	if (iter_status != ITER_DONE) {
422
		strbuf_setlen(src, src_len);
423
		die(_("failed to iterate over '%s'"), src->buf);
424
	}
425
}
426

427
static void clone_local(const char *src_repo, const char *dest_repo)
428
{
429
	if (option_shared) {
430
		struct strbuf alt = STRBUF_INIT;
431
		get_common_dir(&alt, src_repo);
432
		strbuf_addstr(&alt, "/objects");
433
		add_to_alternates_file(alt.buf);
434
		strbuf_release(&alt);
435
	} else {
436
		struct strbuf src = STRBUF_INIT;
437
		struct strbuf dest = STRBUF_INIT;
438
		get_common_dir(&src, src_repo);
439
		get_common_dir(&dest, dest_repo);
440
		strbuf_addstr(&src, "/objects");
441
		strbuf_addstr(&dest, "/objects");
442
		copy_or_link_directory(&src, &dest, src_repo);
443
		strbuf_release(&src);
444
		strbuf_release(&dest);
445
	}
446

447
	if (0 <= option_verbosity)
448
		fprintf(stderr, _("done.\n"));
449
}
450

451
static const char *junk_work_tree;
452
static int junk_work_tree_flags;
453
static const char *junk_git_dir;
454
static int junk_git_dir_flags;
455
static enum {
456
	JUNK_LEAVE_NONE,
457
	JUNK_LEAVE_REPO,
458
	JUNK_LEAVE_ALL
459
} junk_mode = JUNK_LEAVE_NONE;
460

461
static const char junk_leave_repo_msg[] =
462
N_("Clone succeeded, but checkout failed.\n"
463
   "You can inspect what was checked out with 'git status'\n"
464
   "and retry with 'git restore --source=HEAD :/'\n");
465

466
static void remove_junk(void)
467
{
468
	struct strbuf sb = STRBUF_INIT;
469

470
	switch (junk_mode) {
471
	case JUNK_LEAVE_REPO:
472
		warning("%s", _(junk_leave_repo_msg));
473
		/* fall-through */
474
	case JUNK_LEAVE_ALL:
475
		return;
476
	default:
477
		/* proceed to removal */
478
		break;
479
	}
480

481
	if (junk_git_dir) {
482
		strbuf_addstr(&sb, junk_git_dir);
483
		remove_dir_recursively(&sb, junk_git_dir_flags);
484
		strbuf_reset(&sb);
485
	}
486
	if (junk_work_tree) {
487
		strbuf_addstr(&sb, junk_work_tree);
488
		remove_dir_recursively(&sb, junk_work_tree_flags);
489
	}
490
	strbuf_release(&sb);
491
}
492

493
static void remove_junk_on_signal(int signo)
494
{
495
	remove_junk();
496
	sigchain_pop(signo);
497
	raise(signo);
498
}
499

500
static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
501
{
502
	struct ref *ref;
503
	struct strbuf head = STRBUF_INIT;
504
	strbuf_addstr(&head, "refs/heads/");
505
	strbuf_addstr(&head, branch);
506
	ref = find_ref_by_name(refs, head.buf);
507
	strbuf_release(&head);
508

509
	if (ref)
510
		return ref;
511

512
	strbuf_addstr(&head, "refs/tags/");
513
	strbuf_addstr(&head, branch);
514
	ref = find_ref_by_name(refs, head.buf);
515
	strbuf_release(&head);
516

517
	return ref;
518
}
519

520
static struct ref *wanted_peer_refs(const struct ref *refs,
521
		struct refspec *refspec)
522
{
523
	struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
524
	struct ref *local_refs = head;
525
	struct ref **tail = head ? &head->next : &local_refs;
526
	struct refspec_item tag_refspec;
527

528
	refspec_item_init(&tag_refspec, TAG_REFSPEC, 0);
529

530
	if (option_single_branch) {
531
		struct ref *remote_head = NULL;
532

533
		if (!option_branch)
534
			remote_head = guess_remote_head(head, refs, 0);
535
		else {
536
			free_one_ref(head);
537
			local_refs = head = NULL;
538
			tail = &local_refs;
539
			remote_head = copy_ref(find_remote_branch(refs, option_branch));
540
		}
541

542
		if (!remote_head && option_branch)
543
			warning(_("Could not find remote branch %s to clone."),
544
				option_branch);
545
		else {
546
			int i;
547
			for (i = 0; i < refspec->nr; i++)
548
				get_fetch_map(remote_head, &refspec->items[i],
549
					      &tail, 0);
550

551
			/* if --branch=tag, pull the requested tag explicitly */
552
			get_fetch_map(remote_head, &tag_refspec, &tail, 0);
553
		}
554
		free_refs(remote_head);
555
	} else {
556
		int i;
557
		for (i = 0; i < refspec->nr; i++)
558
			get_fetch_map(refs, &refspec->items[i], &tail, 0);
559
	}
560

561
	if (!option_mirror && !option_single_branch && !option_no_tags)
562
		get_fetch_map(refs, &tag_refspec, &tail, 0);
563

564
	refspec_item_clear(&tag_refspec);
565
	return local_refs;
566
}
567

568
static void write_remote_refs(const struct ref *local_refs)
569
{
570
	const struct ref *r;
571

572
	struct ref_transaction *t;
573
	struct strbuf err = STRBUF_INIT;
574

575
	t = ref_store_transaction_begin(get_main_ref_store(the_repository),
576
					&err);
577
	if (!t)
578
		die("%s", err.buf);
579

580
	for (r = local_refs; r; r = r->next) {
581
		if (!r->peer_ref)
582
			continue;
583
		if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
584
					   NULL, 0, NULL, &err))
585
			die("%s", err.buf);
586
	}
587

588
	if (initial_ref_transaction_commit(t, &err))
589
		die("%s", err.buf);
590

591
	strbuf_release(&err);
592
	ref_transaction_free(t);
593
}
594

595
static void write_followtags(const struct ref *refs, const char *msg)
596
{
597
	const struct ref *ref;
598
	for (ref = refs; ref; ref = ref->next) {
599
		if (!starts_with(ref->name, "refs/tags/"))
600
			continue;
601
		if (ends_with(ref->name, "^{}"))
602
			continue;
603
		if (!repo_has_object_file_with_flags(the_repository, &ref->old_oid,
604
						     OBJECT_INFO_QUICK |
605
						     OBJECT_INFO_SKIP_FETCH_OBJECT))
606
			continue;
607
		refs_update_ref(get_main_ref_store(the_repository), msg,
608
				ref->name, &ref->old_oid, NULL, 0,
609
				UPDATE_REFS_DIE_ON_ERR);
610
	}
611
}
612

613
static const struct object_id *iterate_ref_map(void *cb_data)
614
{
615
	struct ref **rm = cb_data;
616
	struct ref *ref = *rm;
617

618
	/*
619
	 * Skip anything missing a peer_ref, which we are not
620
	 * actually going to write a ref for.
621
	 */
622
	while (ref && !ref->peer_ref)
623
		ref = ref->next;
624
	if (!ref)
625
		return NULL;
626

627
	*rm = ref->next;
628
	return &ref->old_oid;
629
}
630

631
static void update_remote_refs(const struct ref *refs,
632
			       const struct ref *mapped_refs,
633
			       const struct ref *remote_head_points_at,
634
			       const char *branch_top,
635
			       const char *msg,
636
			       struct transport *transport,
637
			       int check_connectivity)
638
{
639
	const struct ref *rm = mapped_refs;
640

641
	if (check_connectivity) {
642
		struct check_connected_options opt = CHECK_CONNECTED_INIT;
643

644
		opt.transport = transport;
645
		opt.progress = transport->progress;
646

647
		if (check_connected(iterate_ref_map, &rm, &opt))
648
			die(_("remote did not send all necessary objects"));
649
	}
650

651
	if (refs) {
652
		write_remote_refs(mapped_refs);
653
		if (option_single_branch && !option_no_tags)
654
			write_followtags(refs, msg);
655
	}
656

657
	if (remote_head_points_at && !option_bare) {
658
		struct strbuf head_ref = STRBUF_INIT;
659
		strbuf_addstr(&head_ref, branch_top);
660
		strbuf_addstr(&head_ref, "HEAD");
661
		if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
662
				       remote_head_points_at->peer_ref->name,
663
				       msg) < 0)
664
			die(_("unable to update %s"), head_ref.buf);
665
		strbuf_release(&head_ref);
666
	}
667
}
668

669
static void update_head(const struct ref *our, const struct ref *remote,
670
			const char *unborn, const char *msg)
671
{
672
	const char *head;
673
	if (our && skip_prefix(our->name, "refs/heads/", &head)) {
674
		/* Local default branch link */
675
		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
676
			die(_("unable to update HEAD"));
677
		if (!option_bare) {
678
			refs_update_ref(get_main_ref_store(the_repository),
679
					msg, "HEAD", &our->old_oid, NULL, 0,
680
					UPDATE_REFS_DIE_ON_ERR);
681
			install_branch_config(0, head, remote_name, our->name);
682
		}
683
	} else if (our) {
684
		struct commit *c = lookup_commit_reference(the_repository,
685
							   &our->old_oid);
686
		/* --branch specifies a non-branch (i.e. tags), detach HEAD */
687
		refs_update_ref(get_main_ref_store(the_repository), msg,
688
				"HEAD", &c->object.oid, NULL, REF_NO_DEREF,
689
				UPDATE_REFS_DIE_ON_ERR);
690
	} else if (remote) {
691
		/*
692
		 * We know remote HEAD points to a non-branch, or
693
		 * HEAD points to a branch but we don't know which one.
694
		 * Detach HEAD in all these cases.
695
		 */
696
		refs_update_ref(get_main_ref_store(the_repository), msg,
697
				"HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
698
				UPDATE_REFS_DIE_ON_ERR);
699
	} else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
700
		/*
701
		 * Unborn head from remote; same as "our" case above except
702
		 * that we have no ref to update.
703
		 */
704
		if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
705
			die(_("unable to update HEAD"));
706
		if (!option_bare)
707
			install_branch_config(0, head, remote_name, unborn);
708
	}
709
}
710

711
static int git_sparse_checkout_init(const char *repo)
712
{
713
	struct child_process cmd = CHILD_PROCESS_INIT;
714
	int result = 0;
715
	strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
716

717
	/*
718
	 * We must apply the setting in the current process
719
	 * for the later checkout to use the sparse-checkout file.
720
	 */
721
	core_apply_sparse_checkout = 1;
722

723
	cmd.git_cmd = 1;
724
	if (run_command(&cmd)) {
725
		error(_("failed to initialize sparse-checkout"));
726
		result = 1;
727
	}
728

729
	return result;
730
}
731

732
static int checkout(int submodule_progress, int filter_submodules,
733
		    enum ref_storage_format ref_storage_format)
734
{
735
	struct object_id oid;
736
	char *head;
737
	struct lock_file lock_file = LOCK_INIT;
738
	struct unpack_trees_options opts;
739
	struct tree *tree;
740
	struct tree_desc t;
741
	int err = 0;
742

743
	if (option_no_checkout)
744
		return 0;
745

746
	head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
747
				   RESOLVE_REF_READING, &oid, NULL);
748
	if (!head) {
749
		warning(_("remote HEAD refers to nonexistent ref, "
750
			  "unable to checkout"));
751
		return 0;
752
	}
753
	if (!strcmp(head, "HEAD")) {
754
		if (advice_enabled(ADVICE_DETACHED_HEAD))
755
			detach_advice(oid_to_hex(&oid));
756
		FREE_AND_NULL(head);
757
	} else {
758
		if (!starts_with(head, "refs/heads/"))
759
			die(_("HEAD not found below refs/heads!"));
760
	}
761

762
	/* We need to be in the new work tree for the checkout */
763
	setup_work_tree();
764

765
	repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
766

767
	memset(&opts, 0, sizeof opts);
768
	opts.update = 1;
769
	opts.merge = 1;
770
	opts.clone = 1;
771
	opts.preserve_ignored = 0;
772
	opts.fn = oneway_merge;
773
	opts.verbose_update = (option_verbosity >= 0);
774
	opts.src_index = the_repository->index;
775
	opts.dst_index = the_repository->index;
776
	init_checkout_metadata(&opts.meta, head, &oid, NULL);
777

778
	tree = parse_tree_indirect(&oid);
779
	if (!tree)
780
		die(_("unable to parse commit %s"), oid_to_hex(&oid));
781
	if (parse_tree(tree) < 0)
782
		exit(128);
783
	init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
784
	if (unpack_trees(1, &t, &opts) < 0)
785
		die(_("unable to checkout working tree"));
786

787
	free(head);
788

789
	if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
790
		die(_("unable to write new index file"));
791

792
	err |= run_hooks_l(the_repository, "post-checkout", oid_to_hex(null_oid()),
793
			   oid_to_hex(&oid), "1", NULL);
794

795
	if (!err && (option_recurse_submodules.nr > 0)) {
796
		struct child_process cmd = CHILD_PROCESS_INIT;
797
		strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
798
			     "--recursive", NULL);
799

800
		if (option_shallow_submodules == 1)
801
			strvec_push(&cmd.args, "--depth=1");
802

803
		if (max_jobs != -1)
804
			strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
805

806
		if (submodule_progress)
807
			strvec_push(&cmd.args, "--progress");
808

809
		if (option_verbosity < 0)
810
			strvec_push(&cmd.args, "--quiet");
811

812
		if (option_remote_submodules) {
813
			strvec_push(&cmd.args, "--remote");
814
			strvec_push(&cmd.args, "--no-fetch");
815
		}
816

817
		if (ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
818
			strvec_pushf(&cmd.args, "--ref-format=%s",
819
				     ref_storage_format_to_name(ref_storage_format));
820

821
		if (filter_submodules && filter_options.choice)
822
			strvec_pushf(&cmd.args, "--filter=%s",
823
				     expand_list_objects_filter_spec(&filter_options));
824

825
		if (option_single_branch >= 0)
826
			strvec_push(&cmd.args, option_single_branch ?
827
					       "--single-branch" :
828
					       "--no-single-branch");
829

830
		cmd.git_cmd = 1;
831
		err = run_command(&cmd);
832
	}
833

834
	return err;
835
}
836

837
static int git_clone_config(const char *k, const char *v,
838
			    const struct config_context *ctx, void *cb)
839
{
840
	if (!strcmp(k, "clone.defaultremotename")) {
841
		if (!v)
842
			return config_error_nonbool(k);
843
		free(remote_name);
844
		remote_name = xstrdup(v);
845
	}
846
	if (!strcmp(k, "clone.rejectshallow"))
847
		config_reject_shallow = git_config_bool(k, v);
848
	if (!strcmp(k, "clone.filtersubmodules"))
849
		config_filter_submodules = git_config_bool(k, v);
850

851
	return git_default_config(k, v, ctx, cb);
852
}
853

854
static int write_one_config(const char *key, const char *value,
855
			    const struct config_context *ctx,
856
			    void *data)
857
{
858
	/*
859
	 * give git_clone_config a chance to write config values back to the
860
	 * environment, since git_config_set_multivar_gently only deals with
861
	 * config-file writes
862
	 */
863
	int apply_failed = git_clone_config(key, value, ctx, data);
864
	if (apply_failed)
865
		return apply_failed;
866

867
	return git_config_set_multivar_gently(key,
868
					      value ? value : "true",
869
					      CONFIG_REGEX_NONE, 0);
870
}
871

872
static void write_config(struct string_list *config)
873
{
874
	int i;
875

876
	for (i = 0; i < config->nr; i++) {
877
		if (git_config_parse_parameter(config->items[i].string,
878
					       write_one_config, NULL) < 0)
879
			die(_("unable to write parameters to config file"));
880
	}
881
}
882

883
static void write_refspec_config(const char *src_ref_prefix,
884
		const struct ref *our_head_points_at,
885
		const struct ref *remote_head_points_at,
886
		struct strbuf *branch_top)
887
{
888
	struct strbuf key = STRBUF_INIT;
889
	struct strbuf value = STRBUF_INIT;
890

891
	if (option_mirror || !option_bare) {
892
		if (option_single_branch && !option_mirror) {
893
			if (option_branch) {
894
				if (starts_with(our_head_points_at->name, "refs/tags/"))
895
					strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
896
						our_head_points_at->name);
897
				else
898
					strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
899
						branch_top->buf, option_branch);
900
			} else if (remote_head_points_at) {
901
				const char *head = remote_head_points_at->name;
902
				if (!skip_prefix(head, "refs/heads/", &head))
903
					BUG("remote HEAD points at non-head?");
904

905
				strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
906
						branch_top->buf, head);
907
			}
908
			/*
909
			 * otherwise, the next "git fetch" will
910
			 * simply fetch from HEAD without updating
911
			 * any remote-tracking branch, which is what
912
			 * we want.
913
			 */
914
		} else {
915
			strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
916
		}
917
		/* Configure the remote */
918
		if (value.len) {
919
			strbuf_addf(&key, "remote.%s.fetch", remote_name);
920
			git_config_set_multivar(key.buf, value.buf, "^$", 0);
921
			strbuf_reset(&key);
922

923
			if (option_mirror) {
924
				strbuf_addf(&key, "remote.%s.mirror", remote_name);
925
				git_config_set(key.buf, "true");
926
				strbuf_reset(&key);
927
			}
928
		}
929
	}
930

931
	strbuf_release(&key);
932
	strbuf_release(&value);
933
}
934

935
static void dissociate_from_references(void)
936
{
937
	char *alternates = git_pathdup("objects/info/alternates");
938

939
	if (!access(alternates, F_OK)) {
940
		struct child_process cmd = CHILD_PROCESS_INIT;
941

942
		cmd.git_cmd = 1;
943
		cmd.no_stdin = 1;
944
		strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
945
		if (run_command(&cmd))
946
			die(_("cannot repack to clean up"));
947
		if (unlink(alternates) && errno != ENOENT)
948
			die_errno(_("cannot unlink temporary alternates file"));
949
	}
950
	free(alternates);
951
}
952

953
static int path_exists(const char *path)
954
{
955
	struct stat sb;
956
	return !stat(path, &sb);
957
}
958

959
int cmd_clone(int argc, const char **argv, const char *prefix)
960
{
961
	int is_bundle = 0, is_local;
962
	int reject_shallow = 0;
963
	const char *repo_name, *repo, *work_tree, *git_dir;
964
	char *repo_to_free = NULL;
965
	char *path = NULL, *dir, *display_repo = NULL;
966
	int dest_exists, real_dest_exists = 0;
967
	const struct ref *refs, *remote_head;
968
	struct ref *remote_head_points_at = NULL;
969
	const struct ref *our_head_points_at;
970
	char *unborn_head = NULL;
971
	struct ref *mapped_refs = NULL;
972
	const struct ref *ref;
973
	struct strbuf key = STRBUF_INIT;
974
	struct strbuf buf = STRBUF_INIT;
975
	struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
976
	struct transport *transport = NULL;
977
	const char *src_ref_prefix = "refs/heads/";
978
	struct remote *remote;
979
	int err = 0, complete_refs_before_fetch = 1;
980
	int submodule_progress;
981
	int filter_submodules = 0;
982
	int hash_algo;
983
	enum ref_storage_format ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
984
	const int do_not_override_repo_unix_permissions = -1;
985

986
	struct transport_ls_refs_options transport_ls_refs_options =
987
		TRANSPORT_LS_REFS_OPTIONS_INIT;
988

989
	packet_trace_identity("clone");
990

991
	git_config(git_clone_config, NULL);
992

993
	argc = parse_options(argc, argv, prefix, builtin_clone_options,
994
			     builtin_clone_usage, 0);
995

996
	if (argc > 2)
997
		usage_msg_opt(_("Too many arguments."),
998
			builtin_clone_usage, builtin_clone_options);
999

1000
	if (argc == 0)
1001
		usage_msg_opt(_("You must specify a repository to clone."),
1002
			builtin_clone_usage, builtin_clone_options);
1003

1004
	if (option_depth || option_since || option_not.nr)
1005
		deepen = 1;
1006
	if (option_single_branch == -1)
1007
		option_single_branch = deepen ? 1 : 0;
1008

1009
	if (ref_format) {
1010
		ref_storage_format = ref_storage_format_by_name(ref_format);
1011
		if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1012
			die(_("unknown ref storage format '%s'"), ref_format);
1013
	}
1014

1015
	if (option_mirror)
1016
		option_bare = 1;
1017

1018
	if (option_bare) {
1019
		if (real_git_dir)
1020
			die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1021
		option_no_checkout = 1;
1022
	}
1023

1024
	if (bundle_uri && deepen)
1025
		die(_("options '%s' and '%s' cannot be used together"),
1026
		    "--bundle-uri",
1027
		    "--depth/--shallow-since/--shallow-exclude");
1028

1029
	repo_name = argv[0];
1030

1031
	path = get_repo_path(repo_name, &is_bundle);
1032
	if (path) {
1033
		FREE_AND_NULL(path);
1034
		repo = repo_to_free = absolute_pathdup(repo_name);
1035
	} else if (strchr(repo_name, ':')) {
1036
		repo = repo_name;
1037
		display_repo = transport_anonymize_url(repo);
1038
	} else
1039
		die(_("repository '%s' does not exist"), repo_name);
1040

1041
	/* no need to be strict, transport_set_option() will validate it again */
1042
	if (option_depth && atoi(option_depth) < 1)
1043
		die(_("depth %s is not a positive number"), option_depth);
1044

1045
	if (argc == 2)
1046
		dir = xstrdup(argv[1]);
1047
	else
1048
		dir = git_url_basename(repo_name, is_bundle, option_bare);
1049
	strip_dir_trailing_slashes(dir);
1050

1051
	dest_exists = path_exists(dir);
1052
	if (dest_exists && !is_empty_dir(dir))
1053
		die(_("destination path '%s' already exists and is not "
1054
			"an empty directory."), dir);
1055

1056
	if (real_git_dir) {
1057
		real_dest_exists = path_exists(real_git_dir);
1058
		if (real_dest_exists && !is_empty_dir(real_git_dir))
1059
			die(_("repository path '%s' already exists and is not "
1060
				"an empty directory."), real_git_dir);
1061
	}
1062

1063

1064
	strbuf_addf(&reflog_msg, "clone: from %s",
1065
		    display_repo ? display_repo : repo);
1066
	free(display_repo);
1067

1068
	if (option_bare)
1069
		work_tree = NULL;
1070
	else {
1071
		work_tree = getenv("GIT_WORK_TREE");
1072
		if (work_tree && path_exists(work_tree))
1073
			die(_("working tree '%s' already exists."), work_tree);
1074
	}
1075

1076
	if (option_bare || work_tree)
1077
		git_dir = xstrdup(dir);
1078
	else {
1079
		work_tree = dir;
1080
		git_dir = mkpathdup("%s/.git", dir);
1081
	}
1082

1083
	atexit(remove_junk);
1084
	sigchain_push_common(remove_junk_on_signal);
1085

1086
	if (!option_bare) {
1087
		if (safe_create_leading_directories_const(work_tree) < 0)
1088
			die_errno(_("could not create leading directories of '%s'"),
1089
				  work_tree);
1090
		if (dest_exists)
1091
			junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1092
		else if (mkdir(work_tree, 0777))
1093
			die_errno(_("could not create work tree dir '%s'"),
1094
				  work_tree);
1095
		junk_work_tree = work_tree;
1096
		set_git_work_tree(work_tree);
1097
	}
1098

1099
	if (real_git_dir) {
1100
		if (real_dest_exists)
1101
			junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1102
		junk_git_dir = real_git_dir;
1103
	} else {
1104
		if (dest_exists)
1105
			junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1106
		junk_git_dir = git_dir;
1107
	}
1108
	if (safe_create_leading_directories_const(git_dir) < 0)
1109
		die(_("could not create leading directories of '%s'"), git_dir);
1110

1111
	if (0 <= option_verbosity) {
1112
		if (option_bare)
1113
			fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1114
		else
1115
			fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1116
	}
1117

1118
	if (option_recurse_submodules.nr > 0) {
1119
		struct string_list_item *item;
1120
		struct strbuf sb = STRBUF_INIT;
1121
		int val;
1122

1123
		/* remove duplicates */
1124
		string_list_sort(&option_recurse_submodules);
1125
		string_list_remove_duplicates(&option_recurse_submodules, 0);
1126

1127
		/*
1128
		 * NEEDSWORK: In a multi-working-tree world, this needs to be
1129
		 * set in the per-worktree config.
1130
		 */
1131
		for_each_string_list_item(item, &option_recurse_submodules) {
1132
			strbuf_addf(&sb, "submodule.active=%s",
1133
				    item->string);
1134
			string_list_append(&option_config,
1135
					   strbuf_detach(&sb, NULL));
1136
		}
1137

1138
		if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1139
		    val)
1140
			string_list_append(&option_config, "submodule.recurse=true");
1141

1142
		if (option_required_reference.nr &&
1143
		    option_optional_reference.nr)
1144
			die(_("clone --recursive is not compatible with "
1145
			      "both --reference and --reference-if-able"));
1146
		else if (option_required_reference.nr) {
1147
			string_list_append(&option_config,
1148
				"submodule.alternateLocation=superproject");
1149
			string_list_append(&option_config,
1150
				"submodule.alternateErrorStrategy=die");
1151
		} else if (option_optional_reference.nr) {
1152
			string_list_append(&option_config,
1153
				"submodule.alternateLocation=superproject");
1154
			string_list_append(&option_config,
1155
				"submodule.alternateErrorStrategy=info");
1156
		}
1157
	}
1158

1159
	/*
1160
	 * Initialize the repository, but skip initializing the reference
1161
	 * database. We do not yet know about the object format of the
1162
	 * repository, and reference backends may persist that information into
1163
	 * their on-disk data structures.
1164
	 */
1165
	init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN,
1166
		ref_storage_format, NULL,
1167
		do_not_override_repo_unix_permissions, INIT_DB_QUIET | INIT_DB_SKIP_REFDB);
1168

1169
	if (real_git_dir) {
1170
		free((char *)git_dir);
1171
		git_dir = real_git_dir;
1172
	}
1173

1174
	/*
1175
	 * We have a chicken-and-egg situation between initializing the refdb
1176
	 * and spawning transport helpers:
1177
	 *
1178
	 *   - Initializing the refdb requires us to know about the object
1179
	 *     format. We thus have to spawn the transport helper to learn
1180
	 *     about it.
1181
	 *
1182
	 *   - The transport helper may want to access the Git repository. But
1183
	 *     because the refdb has not been initialized, we don't have "HEAD"
1184
	 *     or "refs/". Thus, the helper cannot find the Git repository.
1185
	 *
1186
	 * Ideally, we would have structured the helper protocol such that it's
1187
	 * mandatory for the helper to first announce its capabilities without
1188
	 * yet assuming a fully initialized repository. Like that, we could
1189
	 * have added a "lazy-refdb-init" capability that announces whether the
1190
	 * helper is ready to handle not-yet-initialized refdbs. If any helper
1191
	 * didn't support them, we would have fully initialized the refdb with
1192
	 * the SHA1 object format, but later on bailed out if we found out that
1193
	 * the remote repository used a different object format.
1194
	 *
1195
	 * But we didn't, and thus we use the following workaround to partially
1196
	 * initialize the repository's refdb such that it can be discovered by
1197
	 * Git commands. To do so, we:
1198
	 *
1199
	 *   - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1200
	 *
1201
	 *   - Create the "refs/" directory.
1202
	 *
1203
	 *   - Set up the ref storage format and repository version as
1204
	 *     required.
1205
	 *
1206
	 * This is sufficient for Git commands to discover the Git directory.
1207
	 */
1208
	initialize_repository_version(GIT_HASH_UNKNOWN,
1209
				      the_repository->ref_storage_format, 1);
1210

1211
	strbuf_addf(&buf, "%s/HEAD", git_dir);
1212
	write_file(buf.buf, "ref: refs/heads/.invalid");
1213

1214
	strbuf_reset(&buf);
1215
	strbuf_addf(&buf, "%s/refs", git_dir);
1216
	safe_create_dir(buf.buf, 1);
1217

1218
	/*
1219
	 * additional config can be injected with -c, make sure it's included
1220
	 * after init_db, which clears the entire config environment.
1221
	 */
1222
	write_config(&option_config);
1223

1224
	/*
1225
	 * re-read config after init_db and write_config to pick up any config
1226
	 * injected by --template and --config, respectively.
1227
	 */
1228
	git_config(git_clone_config, NULL);
1229

1230
	/*
1231
	 * If option_reject_shallow is specified from CLI option,
1232
	 * ignore config_reject_shallow from git_clone_config.
1233
	 */
1234
	if (config_reject_shallow != -1)
1235
		reject_shallow = config_reject_shallow;
1236
	if (option_reject_shallow != -1)
1237
		reject_shallow = option_reject_shallow;
1238

1239
	/*
1240
	 * If option_filter_submodules is specified from CLI option,
1241
	 * ignore config_filter_submodules from git_clone_config.
1242
	 */
1243
	if (config_filter_submodules != -1)
1244
		filter_submodules = config_filter_submodules;
1245
	if (option_filter_submodules != -1)
1246
		filter_submodules = option_filter_submodules;
1247

1248
	/*
1249
	 * Exit if the user seems to be doing something silly with submodule
1250
	 * filter flags (but not with filter configs, as those should be
1251
	 * set-and-forget).
1252
	 */
1253
	if (option_filter_submodules > 0 && !filter_options.choice)
1254
		die(_("the option '%s' requires '%s'"),
1255
		    "--also-filter-submodules", "--filter");
1256
	if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1257
		die(_("the option '%s' requires '%s'"),
1258
		    "--also-filter-submodules", "--recurse-submodules");
1259

1260
	/*
1261
	 * apply the remote name provided by --origin only after this second
1262
	 * call to git_config, to ensure it overrides all config-based values.
1263
	 */
1264
	if (option_origin) {
1265
		free(remote_name);
1266
		remote_name = xstrdup(option_origin);
1267
	}
1268

1269
	if (!remote_name)
1270
		remote_name = xstrdup("origin");
1271

1272
	if (!valid_remote_name(remote_name))
1273
		die(_("'%s' is not a valid remote name"), remote_name);
1274

1275
	if (option_bare) {
1276
		if (option_mirror)
1277
			src_ref_prefix = "refs/";
1278
		strbuf_addstr(&branch_top, src_ref_prefix);
1279

1280
		git_config_set("core.bare", "true");
1281
	} else {
1282
		strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1283
	}
1284

1285
	strbuf_addf(&key, "remote.%s.url", remote_name);
1286
	git_config_set(key.buf, repo);
1287
	strbuf_reset(&key);
1288

1289
	if (option_no_tags) {
1290
		strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1291
		git_config_set(key.buf, "--no-tags");
1292
		strbuf_reset(&key);
1293
	}
1294

1295
	if (option_required_reference.nr || option_optional_reference.nr)
1296
		setup_reference();
1297

1298
	remote = remote_get_early(remote_name);
1299

1300
	refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1301
			branch_top.buf);
1302

1303
	path = get_repo_path(remote->url.v[0], &is_bundle);
1304
	is_local = option_local != 0 && path && !is_bundle;
1305
	if (is_local) {
1306
		if (option_depth)
1307
			warning(_("--depth is ignored in local clones; use file:// instead."));
1308
		if (option_since)
1309
			warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1310
		if (option_not.nr)
1311
			warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1312
		if (filter_options.choice)
1313
			warning(_("--filter is ignored in local clones; use file:// instead."));
1314
		if (!access(mkpath("%s/shallow", path), F_OK)) {
1315
			if (reject_shallow)
1316
				die(_("source repository is shallow, reject to clone."));
1317
			if (option_local > 0)
1318
				warning(_("source repository is shallow, ignoring --local"));
1319
			is_local = 0;
1320
		}
1321
	}
1322
	if (option_local > 0 && !is_local)
1323
		warning(_("--local is ignored"));
1324

1325
	transport = transport_get(remote, path ? path : remote->url.v[0]);
1326
	transport_set_verbosity(transport, option_verbosity, option_progress);
1327
	transport->family = family;
1328
	transport->cloning = 1;
1329

1330
	if (is_bundle) {
1331
		struct bundle_header header = BUNDLE_HEADER_INIT;
1332
		int fd = read_bundle_header(path, &header);
1333
		int has_filter = header.filter.choice != LOFC_DISABLED;
1334

1335
		if (fd > 0)
1336
			close(fd);
1337
		bundle_header_release(&header);
1338
		if (has_filter)
1339
			die(_("cannot clone from filtered bundle"));
1340
	}
1341

1342
	transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1343

1344
	if (reject_shallow)
1345
		transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1346
	if (option_depth)
1347
		transport_set_option(transport, TRANS_OPT_DEPTH,
1348
				     option_depth);
1349
	if (option_since)
1350
		transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1351
				     option_since);
1352
	if (option_not.nr)
1353
		transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1354
				     (const char *)&option_not);
1355
	if (option_single_branch)
1356
		transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1357

1358
	if (option_upload_pack)
1359
		transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1360
				     option_upload_pack);
1361

1362
	if (server_options.nr)
1363
		transport->server_options = &server_options;
1364

1365
	if (filter_options.choice) {
1366
		const char *spec =
1367
			expand_list_objects_filter_spec(&filter_options);
1368
		transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1369
				     spec);
1370
		transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1371
	}
1372

1373
	if (transport->smart_options && !deepen && !filter_options.choice)
1374
		transport->smart_options->check_self_contained_and_connected = 1;
1375

1376
	strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1377
	refspec_ref_prefixes(&remote->fetch,
1378
			     &transport_ls_refs_options.ref_prefixes);
1379
	if (option_branch)
1380
		expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1381
				  option_branch);
1382
	if (!option_no_tags)
1383
		strvec_push(&transport_ls_refs_options.ref_prefixes,
1384
			    "refs/tags/");
1385

1386
	refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1387

1388
	/*
1389
	 * Now that we know what algorithm the remote side is using, let's set
1390
	 * ours to the same thing.
1391
	 */
1392
	hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1393
	initialize_repository_version(hash_algo, the_repository->ref_storage_format, 1);
1394
	repo_set_hash_algo(the_repository, hash_algo);
1395
	create_reference_database(the_repository->ref_storage_format, NULL, 1);
1396

1397
	/*
1398
	 * Before fetching from the remote, download and install bundle
1399
	 * data from the --bundle-uri option.
1400
	 */
1401
	if (bundle_uri) {
1402
		int has_heuristic = 0;
1403

1404
		/* At this point, we need the_repository to match the cloned repo. */
1405
		if (repo_init(the_repository, git_dir, work_tree))
1406
			warning(_("failed to initialize the repo, skipping bundle URI"));
1407
		else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1408
			warning(_("failed to fetch objects from bundle URI '%s'"),
1409
				bundle_uri);
1410
		else if (has_heuristic)
1411
			git_config_set_gently("fetch.bundleuri", bundle_uri);
1412
	} else {
1413
		/*
1414
		* Populate transport->got_remote_bundle_uri and
1415
		* transport->bundle_uri. We might get nothing.
1416
		*/
1417
		transport_get_remote_bundle_uri(transport);
1418

1419
		if (transport->bundles &&
1420
		    hashmap_get_size(&transport->bundles->bundles)) {
1421
			/* At this point, we need the_repository to match the cloned repo. */
1422
			if (repo_init(the_repository, git_dir, work_tree))
1423
				warning(_("failed to initialize the repo, skipping bundle URI"));
1424
			else if (fetch_bundle_list(the_repository,
1425
						   transport->bundles))
1426
				warning(_("failed to fetch advertised bundles"));
1427
		} else {
1428
			clear_bundle_list(transport->bundles);
1429
			FREE_AND_NULL(transport->bundles);
1430
		}
1431
	}
1432

1433
	if (refs)
1434
		mapped_refs = wanted_peer_refs(refs, &remote->fetch);
1435

1436
	if (mapped_refs) {
1437
		/*
1438
		 * transport_get_remote_refs() may return refs with null sha-1
1439
		 * in mapped_refs (see struct transport->get_refs_list
1440
		 * comment). In that case we need fetch it early because
1441
		 * remote_head code below relies on it.
1442
		 *
1443
		 * for normal clones, transport_get_remote_refs() should
1444
		 * return reliable ref set, we can delay cloning until after
1445
		 * remote HEAD check.
1446
		 */
1447
		for (ref = refs; ref; ref = ref->next)
1448
			if (is_null_oid(&ref->old_oid)) {
1449
				complete_refs_before_fetch = 0;
1450
				break;
1451
			}
1452

1453
		if (!is_local && !complete_refs_before_fetch) {
1454
			if (transport_fetch_refs(transport, mapped_refs))
1455
				die(_("remote transport reported error"));
1456
		}
1457
	}
1458

1459
	remote_head = find_ref_by_name(refs, "HEAD");
1460
	remote_head_points_at = guess_remote_head(remote_head, mapped_refs, 0);
1461

1462
	if (option_branch) {
1463
		our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1464
		if (!our_head_points_at)
1465
			die(_("Remote branch %s not found in upstream %s"),
1466
			    option_branch, remote_name);
1467
	} else if (remote_head_points_at) {
1468
		our_head_points_at = remote_head_points_at;
1469
	} else if (remote_head) {
1470
		our_head_points_at = NULL;
1471
	} else {
1472
		char *to_free = NULL;
1473
		const char *branch;
1474

1475
		if (!mapped_refs) {
1476
			warning(_("You appear to have cloned an empty repository."));
1477
			option_no_checkout = 1;
1478
		}
1479

1480
		if (transport_ls_refs_options.unborn_head_target &&
1481
		    skip_prefix(transport_ls_refs_options.unborn_head_target,
1482
				"refs/heads/", &branch)) {
1483
			unborn_head  = xstrdup(transport_ls_refs_options.unborn_head_target);
1484
		} else {
1485
			branch = to_free = repo_default_branch_name(the_repository, 0);
1486
			unborn_head = xstrfmt("refs/heads/%s", branch);
1487
		}
1488

1489
		/*
1490
		 * We may have selected a local default branch name "foo",
1491
		 * and even though the remote's HEAD does not point there,
1492
		 * it may still have a "foo" branch. If so, set it up so
1493
		 * that we can follow the usual checkout code later.
1494
		 *
1495
		 * Note that for an empty repo we'll already have set
1496
		 * option_no_checkout above, which would work against us here.
1497
		 * But for an empty repo, find_remote_branch() can never find
1498
		 * a match.
1499
		 */
1500
		our_head_points_at = find_remote_branch(mapped_refs, branch);
1501

1502
		free(to_free);
1503
	}
1504

1505
	write_refspec_config(src_ref_prefix, our_head_points_at,
1506
			remote_head_points_at, &branch_top);
1507

1508
	if (filter_options.choice)
1509
		partial_clone_register(remote_name, &filter_options);
1510

1511
	if (is_local)
1512
		clone_local(path, git_dir);
1513
	else if (mapped_refs && complete_refs_before_fetch) {
1514
		if (transport_fetch_refs(transport, mapped_refs))
1515
			die(_("remote transport reported error"));
1516
	}
1517

1518
	update_remote_refs(refs, mapped_refs, remote_head_points_at,
1519
			   branch_top.buf, reflog_msg.buf, transport,
1520
			   !is_local);
1521

1522
	update_head(our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1523

1524
	/*
1525
	 * We want to show progress for recursive submodule clones iff
1526
	 * we did so for the main clone. But only the transport knows
1527
	 * the final decision for this flag, so we need to rescue the value
1528
	 * before we free the transport.
1529
	 */
1530
	submodule_progress = transport->progress;
1531

1532
	transport_unlock_pack(transport, 0);
1533
	transport_disconnect(transport);
1534

1535
	if (option_dissociate) {
1536
		close_object_store(the_repository->objects);
1537
		dissociate_from_references();
1538
	}
1539

1540
	if (option_sparse_checkout && git_sparse_checkout_init(dir))
1541
		return 1;
1542

1543
	junk_mode = JUNK_LEAVE_REPO;
1544
	err = checkout(submodule_progress, filter_submodules,
1545
		       ref_storage_format);
1546

1547
	free(remote_name);
1548
	strbuf_release(&reflog_msg);
1549
	strbuf_release(&branch_top);
1550
	strbuf_release(&buf);
1551
	strbuf_release(&key);
1552
	free_refs(mapped_refs);
1553
	free_refs(remote_head_points_at);
1554
	free(unborn_head);
1555
	free(dir);
1556
	free(path);
1557
	free(repo_to_free);
1558
	UNLEAK(repo);
1559
	junk_mode = JUNK_LEAVE_ALL;
1560

1561
	transport_ls_refs_options_release(&transport_ls_refs_options);
1562
	return err;
1563
}
1564

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.