]> git.ipfire.org Git - thirdparty/git.git/blob - builtin/clone.c
91b9cd0d16419852bfe3e10dd99d68b92a2a37ec
[thirdparty/git.git] / builtin / clone.c
1 /*
2 * Builtin "git clone"
3 *
4 * Copyright (c) 2007 Kristian Høgsberg <krh@redhat.com>,
5 * 2008 Daniel Barkalow <barkalow@iabervon.org>
6 * Based on git-commit.sh by Junio C Hamano and Linus Torvalds
7 *
8 * Clone a repository into a different directory that does not yet exist.
9 */
10
11 #define USE_THE_REPOSITORY_VARIABLE
12 #define DISABLE_SIGN_COMPARE_WARNINGS
13
14 #include "builtin.h"
15
16 #include "abspath.h"
17 #include "advice.h"
18 #include "config.h"
19 #include "copy.h"
20 #include "environment.h"
21 #include "gettext.h"
22 #include "hex.h"
23 #include "lockfile.h"
24 #include "parse-options.h"
25 #include "refs.h"
26 #include "refspec.h"
27 #include "object-file.h"
28 #include "object-store.h"
29 #include "tree.h"
30 #include "tree-walk.h"
31 #include "unpack-trees.h"
32 #include "transport.h"
33 #include "strbuf.h"
34 #include "dir.h"
35 #include "dir-iterator.h"
36 #include "iterator.h"
37 #include "sigchain.h"
38 #include "branch.h"
39 #include "remote.h"
40 #include "run-command.h"
41 #include "setup.h"
42 #include "connected.h"
43 #include "packfile.h"
44 #include "path.h"
45 #include "pkt-line.h"
46 #include "list-objects-filter-options.h"
47 #include "hook.h"
48 #include "bundle.h"
49 #include "bundle-uri.h"
50
51 /*
52 * Overall FIXMEs:
53 * - respect DB_ENVIRONMENT for .git/objects.
54 *
55 * Implementation notes:
56 * - dropping use-separate-remote and no-separate-remote compatibility
57 *
58 */
59
60 struct clone_opts {
61 int wants_head;
62 int detach;
63 };
64 #define CLONE_OPTS_INIT { \
65 .wants_head = 1 /* default enabled */ \
66 }
67
68 static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
69 static int option_local = -1, option_no_hardlinks, option_shared;
70 static int option_tags = 1; /* default enabled */
71 static int option_shallow_submodules;
72 static int config_reject_shallow = -1; /* unspecified */
73 static char *remote_name = NULL;
74 static char *option_branch = NULL;
75 static int option_verbosity;
76 static struct string_list option_required_reference = STRING_LIST_INIT_NODUP;
77 static struct string_list option_optional_reference = STRING_LIST_INIT_NODUP;
78 static int max_jobs = -1;
79 static struct string_list option_recurse_submodules = STRING_LIST_INIT_NODUP;
80 static struct list_objects_filter_options filter_options = LIST_OBJECTS_FILTER_INIT;
81 static int config_filter_submodules = -1; /* unspecified */
82 static int option_remote_submodules;
83
84 static int recurse_submodules_cb(const struct option *opt,
85 const char *arg, int unset)
86 {
87 if (unset)
88 string_list_clear((struct string_list *)opt->value, 0);
89 else if (arg)
90 string_list_append((struct string_list *)opt->value, arg);
91 else
92 string_list_append((struct string_list *)opt->value,
93 (const char *)opt->defval);
94
95 return 0;
96 }
97
98 static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
99 {
100 static const char *suffix[] = { "/.git", "", ".git/.git", ".git" };
101 static const char *bundle_suffix[] = { ".bundle", "" };
102 size_t baselen = path->len;
103 struct stat st;
104 int i;
105
106 for (i = 0; i < ARRAY_SIZE(suffix); i++) {
107 strbuf_setlen(path, baselen);
108 strbuf_addstr(path, suffix[i]);
109 if (stat(path->buf, &st))
110 continue;
111 if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
112 *is_bundle = 0;
113 return path->buf;
114 } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
115 /* Is it a "gitfile"? */
116 char signature[8];
117 const char *dst;
118 int len, fd = open(path->buf, O_RDONLY);
119 if (fd < 0)
120 continue;
121 len = read_in_full(fd, signature, 8);
122 close(fd);
123 if (len != 8 || strncmp(signature, "gitdir: ", 8))
124 continue;
125 dst = read_gitfile(path->buf);
126 if (dst) {
127 *is_bundle = 0;
128 return dst;
129 }
130 }
131 }
132
133 for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
134 strbuf_setlen(path, baselen);
135 strbuf_addstr(path, bundle_suffix[i]);
136 if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
137 *is_bundle = 1;
138 return path->buf;
139 }
140 }
141
142 return NULL;
143 }
144
145 static char *get_repo_path(const char *repo, int *is_bundle)
146 {
147 struct strbuf path = STRBUF_INIT;
148 const char *raw;
149 char *canon;
150
151 strbuf_addstr(&path, repo);
152 raw = get_repo_path_1(&path, is_bundle);
153 canon = raw ? absolute_pathdup(raw) : NULL;
154 strbuf_release(&path);
155 return canon;
156 }
157
158 static int add_one_reference(struct string_list_item *item, void *cb_data)
159 {
160 struct strbuf err = STRBUF_INIT;
161 int *required = cb_data;
162 char *ref_git = compute_alternate_path(item->string, &err);
163
164 if (!ref_git) {
165 if (*required)
166 die("%s", err.buf);
167 else
168 fprintf(stderr,
169 _("info: Could not add alternate for '%s': %s\n"),
170 item->string, err.buf);
171 } else {
172 struct strbuf sb = STRBUF_INIT;
173 strbuf_addf(&sb, "%s/objects", ref_git);
174 add_to_alternates_file(sb.buf);
175 strbuf_release(&sb);
176 }
177
178 strbuf_release(&err);
179 free(ref_git);
180 return 0;
181 }
182
183 static void setup_reference(void)
184 {
185 int required = 1;
186 for_each_string_list(&option_required_reference,
187 add_one_reference, &required);
188 required = 0;
189 for_each_string_list(&option_optional_reference,
190 add_one_reference, &required);
191 }
192
193 static void copy_alternates(struct strbuf *src, const char *src_repo)
194 {
195 /*
196 * Read from the source objects/info/alternates file
197 * and copy the entries to corresponding file in the
198 * destination repository with add_to_alternates_file().
199 * Both src and dst have "$path/objects/info/alternates".
200 *
201 * Instead of copying bit-for-bit from the original,
202 * we need to append to existing one so that the already
203 * created entry via "clone -s" is not lost, and also
204 * to turn entries with paths relative to the original
205 * absolute, so that they can be used in the new repository.
206 */
207 FILE *in = xfopen(src->buf, "r");
208 struct strbuf line = STRBUF_INIT;
209
210 while (strbuf_getline(&line, in) != EOF) {
211 char *abs_path;
212 if (!line.len || line.buf[0] == '#')
213 continue;
214 if (is_absolute_path(line.buf)) {
215 add_to_alternates_file(line.buf);
216 continue;
217 }
218 abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
219 if (!normalize_path_copy(abs_path, abs_path))
220 add_to_alternates_file(abs_path);
221 else
222 warning("skipping invalid relative alternate: %s/%s",
223 src_repo, line.buf);
224 free(abs_path);
225 }
226 strbuf_release(&line);
227 fclose(in);
228 }
229
230 static void mkdir_if_missing(const char *pathname, mode_t mode)
231 {
232 struct stat st;
233
234 if (!mkdir(pathname, mode))
235 return;
236
237 if (errno != EEXIST)
238 die_errno(_("failed to create directory '%s'"), pathname);
239 else if (stat(pathname, &st))
240 die_errno(_("failed to stat '%s'"), pathname);
241 else if (!S_ISDIR(st.st_mode))
242 die(_("%s exists and is not a directory"), pathname);
243 }
244
245 static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
246 const char *src_repo)
247 {
248 int src_len, dest_len;
249 struct dir_iterator *iter;
250 int iter_status;
251
252 /*
253 * Refuse copying directories by default which aren't owned by us. The
254 * code that performs either the copying or hardlinking is not prepared
255 * to handle various edge cases where an adversary may for example
256 * racily swap out files for symlinks. This can cause us to
257 * inadvertently use the wrong source file.
258 *
259 * Furthermore, even if we were prepared to handle such races safely,
260 * creating hardlinks across user boundaries is an inherently unsafe
261 * operation as the hardlinked files can be rewritten at will by the
262 * potentially-untrusted user. We thus refuse to do so by default.
263 */
264 die_upon_dubious_ownership(NULL, NULL, src_repo);
265
266 mkdir_if_missing(dest->buf, 0777);
267
268 iter = dir_iterator_begin(src->buf, DIR_ITERATOR_PEDANTIC);
269
270 if (!iter) {
271 if (errno == ENOTDIR) {
272 int saved_errno = errno;
273 struct stat st;
274
275 if (!lstat(src->buf, &st) && S_ISLNK(st.st_mode))
276 die(_("'%s' is a symlink, refusing to clone with --local"),
277 src->buf);
278 errno = saved_errno;
279 }
280 die_errno(_("failed to start iterator over '%s'"), src->buf);
281 }
282
283 strbuf_addch(src, '/');
284 src_len = src->len;
285 strbuf_addch(dest, '/');
286 dest_len = dest->len;
287
288 while ((iter_status = dir_iterator_advance(iter)) == ITER_OK) {
289 strbuf_setlen(src, src_len);
290 strbuf_addstr(src, iter->relative_path);
291 strbuf_setlen(dest, dest_len);
292 strbuf_addstr(dest, iter->relative_path);
293
294 if (S_ISLNK(iter->st.st_mode))
295 die(_("symlink '%s' exists, refusing to clone with --local"),
296 iter->relative_path);
297
298 if (S_ISDIR(iter->st.st_mode)) {
299 mkdir_if_missing(dest->buf, 0777);
300 continue;
301 }
302
303 /* Files that cannot be copied bit-for-bit... */
304 if (!fspathcmp(iter->relative_path, "info/alternates")) {
305 copy_alternates(src, src_repo);
306 continue;
307 }
308
309 if (unlink(dest->buf) && errno != ENOENT)
310 die_errno(_("failed to unlink '%s'"), dest->buf);
311 if (!option_no_hardlinks) {
312 if (!link(src->buf, dest->buf)) {
313 struct stat st;
314
315 /*
316 * Sanity-check whether the created hardlink
317 * actually links to the expected file now. This
318 * catches time-of-check-time-of-use bugs in
319 * case the source file was meanwhile swapped.
320 */
321 if (lstat(dest->buf, &st))
322 die(_("hardlink cannot be checked at '%s'"), dest->buf);
323 if (st.st_mode != iter->st.st_mode ||
324 st.st_ino != iter->st.st_ino ||
325 st.st_dev != iter->st.st_dev ||
326 st.st_size != iter->st.st_size ||
327 st.st_uid != iter->st.st_uid ||
328 st.st_gid != iter->st.st_gid)
329 die(_("hardlink different from source at '%s'"), dest->buf);
330
331 continue;
332 }
333 if (option_local > 0)
334 die_errno(_("failed to create link '%s'"), dest->buf);
335 option_no_hardlinks = 1;
336 }
337 if (copy_file_with_time(dest->buf, src->buf, 0666))
338 die_errno(_("failed to copy file to '%s'"), dest->buf);
339 }
340
341 if (iter_status != ITER_DONE) {
342 strbuf_setlen(src, src_len);
343 die(_("failed to iterate over '%s'"), src->buf);
344 }
345
346 dir_iterator_free(iter);
347 }
348
349 static void clone_local(const char *src_repo, const char *dest_repo)
350 {
351 if (option_shared) {
352 struct strbuf alt = STRBUF_INIT;
353 get_common_dir(&alt, src_repo);
354 strbuf_addstr(&alt, "/objects");
355 add_to_alternates_file(alt.buf);
356 strbuf_release(&alt);
357 } else {
358 struct strbuf src = STRBUF_INIT;
359 struct strbuf dest = STRBUF_INIT;
360 get_common_dir(&src, src_repo);
361 get_common_dir(&dest, dest_repo);
362 strbuf_addstr(&src, "/objects");
363 strbuf_addstr(&dest, "/objects");
364 copy_or_link_directory(&src, &dest, src_repo);
365 strbuf_release(&src);
366 strbuf_release(&dest);
367 }
368
369 if (0 <= option_verbosity)
370 fprintf(stderr, _("done.\n"));
371 }
372
373 static const char *junk_work_tree;
374 static int junk_work_tree_flags;
375 static const char *junk_git_dir;
376 static int junk_git_dir_flags;
377 static enum {
378 JUNK_LEAVE_NONE,
379 JUNK_LEAVE_REPO,
380 JUNK_LEAVE_ALL
381 } junk_mode = JUNK_LEAVE_NONE;
382
383 static const char junk_leave_repo_msg[] =
384 N_("Clone succeeded, but checkout failed.\n"
385 "You can inspect what was checked out with 'git status'\n"
386 "and retry with 'git restore --source=HEAD :/'\n");
387
388 static void remove_junk(void)
389 {
390 struct strbuf sb = STRBUF_INIT;
391
392 switch (junk_mode) {
393 case JUNK_LEAVE_REPO:
394 warning("%s", _(junk_leave_repo_msg));
395 /* fall-through */
396 case JUNK_LEAVE_ALL:
397 return;
398 default:
399 /* proceed to removal */
400 break;
401 }
402
403 if (junk_git_dir) {
404 strbuf_addstr(&sb, junk_git_dir);
405 remove_dir_recursively(&sb, junk_git_dir_flags);
406 strbuf_reset(&sb);
407 }
408 if (junk_work_tree) {
409 strbuf_addstr(&sb, junk_work_tree);
410 remove_dir_recursively(&sb, junk_work_tree_flags);
411 }
412 strbuf_release(&sb);
413 }
414
415 static void remove_junk_on_signal(int signo)
416 {
417 remove_junk();
418 sigchain_pop(signo);
419 raise(signo);
420 }
421
422 static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
423 {
424 struct ref *ref;
425 struct strbuf head = STRBUF_INIT;
426 strbuf_addstr(&head, "refs/heads/");
427 strbuf_addstr(&head, branch);
428 ref = find_ref_by_name(refs, head.buf);
429 strbuf_release(&head);
430
431 if (ref)
432 return ref;
433
434 strbuf_addstr(&head, "refs/tags/");
435 strbuf_addstr(&head, branch);
436 ref = find_ref_by_name(refs, head.buf);
437 strbuf_release(&head);
438
439 return ref;
440 }
441
442 static struct ref *wanted_peer_refs(struct clone_opts *opts,
443 const struct ref *refs,
444 struct refspec *refspec)
445 {
446 struct ref *local_refs = NULL;
447 struct ref **tail = &local_refs;
448 struct ref *to_free = NULL;
449
450 if (opts->wants_head) {
451 struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
452 if (head)
453 tail_link_ref(head, &tail);
454 if (option_single_branch)
455 refs = to_free =
456 guess_remote_head(head, refs,
457 REMOTE_GUESS_HEAD_QUIET);
458 } else if (option_single_branch) {
459 local_refs = NULL;
460 tail = &local_refs;
461 refs = to_free = copy_ref(find_remote_branch(refs, option_branch));
462 }
463
464 for (size_t i = 0; i < refspec->nr; i++)
465 get_fetch_map(refs, &refspec->items[i], &tail, 0);
466
467 free_one_ref(to_free);
468
469 return local_refs;
470 }
471
472 static void write_remote_refs(const struct ref *local_refs)
473 {
474 const struct ref *r;
475
476 struct ref_transaction *t;
477 struct strbuf err = STRBUF_INIT;
478
479 t = ref_store_transaction_begin(get_main_ref_store(the_repository),
480 REF_TRANSACTION_FLAG_INITIAL, &err);
481 if (!t)
482 die("%s", err.buf);
483
484 for (r = local_refs; r; r = r->next) {
485 if (!r->peer_ref)
486 continue;
487 if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
488 NULL, 0, NULL, &err))
489 die("%s", err.buf);
490 }
491
492 if (ref_transaction_commit(t, &err))
493 die("%s", err.buf);
494
495 strbuf_release(&err);
496 ref_transaction_free(t);
497 }
498
499 static void write_followtags(const struct ref *refs, const char *msg)
500 {
501 const struct ref *ref;
502 for (ref = refs; ref; ref = ref->next) {
503 if (!starts_with(ref->name, "refs/tags/"))
504 continue;
505 if (ends_with(ref->name, "^{}"))
506 continue;
507 if (!has_object(the_repository, &ref->old_oid, 0))
508 continue;
509 refs_update_ref(get_main_ref_store(the_repository), msg,
510 ref->name, &ref->old_oid, NULL, 0,
511 UPDATE_REFS_DIE_ON_ERR);
512 }
513 }
514
515 static const struct object_id *iterate_ref_map(void *cb_data)
516 {
517 struct ref **rm = cb_data;
518 struct ref *ref = *rm;
519
520 /*
521 * Skip anything missing a peer_ref, which we are not
522 * actually going to write a ref for.
523 */
524 while (ref && !ref->peer_ref)
525 ref = ref->next;
526 if (!ref)
527 return NULL;
528
529 *rm = ref->next;
530 return &ref->old_oid;
531 }
532
533 static void update_remote_refs(const struct ref *refs,
534 const struct ref *mapped_refs,
535 const struct ref *remote_head_points_at,
536 const char *branch_top,
537 const char *msg,
538 struct transport *transport,
539 int check_connectivity)
540 {
541 const struct ref *rm = mapped_refs;
542
543 if (check_connectivity) {
544 struct check_connected_options opt = CHECK_CONNECTED_INIT;
545
546 opt.transport = transport;
547 opt.progress = transport->progress;
548
549 if (check_connected(iterate_ref_map, &rm, &opt))
550 die(_("remote did not send all necessary objects"));
551 }
552
553 if (refs) {
554 write_remote_refs(mapped_refs);
555 if (option_single_branch && option_tags)
556 write_followtags(refs, msg);
557 }
558
559 if (remote_head_points_at && !option_bare) {
560 struct strbuf head_ref = STRBUF_INIT;
561 strbuf_addstr(&head_ref, branch_top);
562 strbuf_addstr(&head_ref, "HEAD");
563 if (refs_update_symref(get_main_ref_store(the_repository), head_ref.buf,
564 remote_head_points_at->peer_ref->name,
565 msg) < 0)
566 die(_("unable to update %s"), head_ref.buf);
567 strbuf_release(&head_ref);
568 }
569 }
570
571 static void update_head(struct clone_opts *opts, const struct ref *our, const struct ref *remote,
572 const char *unborn, const char *msg)
573 {
574 const char *head;
575 if (our && !opts->detach && skip_prefix(our->name, "refs/heads/", &head)) {
576 /* Local default branch link */
577 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", our->name, NULL) < 0)
578 die(_("unable to update HEAD"));
579 if (!option_bare) {
580 refs_update_ref(get_main_ref_store(the_repository),
581 msg, "HEAD", &our->old_oid, NULL, 0,
582 UPDATE_REFS_DIE_ON_ERR);
583 install_branch_config(0, head, remote_name, our->name);
584 }
585 } else if (our) {
586 struct commit *c = lookup_commit_or_die(&our->old_oid,
587 our->name);
588
589 /* --branch specifies a non-branch (i.e. tags), detach HEAD */
590 refs_update_ref(get_main_ref_store(the_repository), msg,
591 "HEAD", &c->object.oid, NULL, REF_NO_DEREF,
592 UPDATE_REFS_DIE_ON_ERR);
593 } else if (remote) {
594 /*
595 * We know remote HEAD points to a non-branch, or
596 * HEAD points to a branch but we don't know which one.
597 * Detach HEAD in all these cases.
598 */
599 refs_update_ref(get_main_ref_store(the_repository), msg,
600 "HEAD", &remote->old_oid, NULL, REF_NO_DEREF,
601 UPDATE_REFS_DIE_ON_ERR);
602 } else if (unborn && skip_prefix(unborn, "refs/heads/", &head)) {
603 /*
604 * Unborn head from remote; same as "our" case above except
605 * that we have no ref to update.
606 */
607 if (refs_update_symref(get_main_ref_store(the_repository), "HEAD", unborn, NULL) < 0)
608 die(_("unable to update HEAD"));
609 if (!option_bare)
610 install_branch_config(0, head, remote_name, unborn);
611 }
612 }
613
614 static int git_sparse_checkout_init(const char *repo)
615 {
616 struct child_process cmd = CHILD_PROCESS_INIT;
617 int result = 0;
618 strvec_pushl(&cmd.args, "-C", repo, "sparse-checkout", "set", NULL);
619
620 /*
621 * We must apply the setting in the current process
622 * for the later checkout to use the sparse-checkout file.
623 */
624 core_apply_sparse_checkout = 1;
625
626 cmd.git_cmd = 1;
627 if (run_command(&cmd)) {
628 error(_("failed to initialize sparse-checkout"));
629 result = 1;
630 }
631
632 return result;
633 }
634
635 static int checkout(int submodule_progress, int filter_submodules,
636 enum ref_storage_format ref_storage_format)
637 {
638 struct object_id oid;
639 char *head;
640 struct lock_file lock_file = LOCK_INIT;
641 struct unpack_trees_options opts;
642 struct tree *tree;
643 struct tree_desc t;
644 int err = 0;
645
646 if (option_no_checkout)
647 return 0;
648
649 head = refs_resolve_refdup(get_main_ref_store(the_repository), "HEAD",
650 RESOLVE_REF_READING, &oid, NULL);
651 if (!head) {
652 warning(_("remote HEAD refers to nonexistent ref, "
653 "unable to checkout"));
654 return 0;
655 }
656 if (!strcmp(head, "HEAD")) {
657 if (advice_enabled(ADVICE_DETACHED_HEAD))
658 detach_advice(oid_to_hex(&oid));
659 FREE_AND_NULL(head);
660 } else {
661 if (!starts_with(head, "refs/heads/"))
662 die(_("HEAD not found below refs/heads!"));
663 }
664
665 /* We need to be in the new work tree for the checkout */
666 setup_work_tree();
667
668 repo_hold_locked_index(the_repository, &lock_file, LOCK_DIE_ON_ERROR);
669
670 memset(&opts, 0, sizeof opts);
671 opts.update = 1;
672 opts.merge = 1;
673 opts.clone = 1;
674 opts.preserve_ignored = 0;
675 opts.fn = oneway_merge;
676 opts.verbose_update = (option_verbosity >= 0);
677 opts.src_index = the_repository->index;
678 opts.dst_index = the_repository->index;
679 init_checkout_metadata(&opts.meta, head, &oid, NULL);
680
681 tree = parse_tree_indirect(&oid);
682 if (!tree)
683 die(_("unable to parse commit %s"), oid_to_hex(&oid));
684 if (parse_tree(tree) < 0)
685 exit(128);
686 init_tree_desc(&t, &tree->object.oid, tree->buffer, tree->size);
687 if (unpack_trees(1, &t, &opts) < 0)
688 die(_("unable to checkout working tree"));
689
690 free(head);
691
692 if (write_locked_index(the_repository->index, &lock_file, COMMIT_LOCK))
693 die(_("unable to write new index file"));
694
695 err |= run_hooks_l(the_repository, "post-checkout", oid_to_hex(null_oid(the_hash_algo)),
696 oid_to_hex(&oid), "1", NULL);
697
698 if (!err && (option_recurse_submodules.nr > 0)) {
699 struct child_process cmd = CHILD_PROCESS_INIT;
700 strvec_pushl(&cmd.args, "submodule", "update", "--require-init",
701 "--recursive", NULL);
702
703 if (option_shallow_submodules == 1)
704 strvec_push(&cmd.args, "--depth=1");
705
706 if (max_jobs != -1)
707 strvec_pushf(&cmd.args, "--jobs=%d", max_jobs);
708
709 if (submodule_progress)
710 strvec_push(&cmd.args, "--progress");
711
712 if (option_verbosity < 0)
713 strvec_push(&cmd.args, "--quiet");
714
715 if (option_remote_submodules) {
716 strvec_push(&cmd.args, "--remote");
717 strvec_push(&cmd.args, "--no-fetch");
718 }
719
720 if (ref_storage_format != REF_STORAGE_FORMAT_UNKNOWN)
721 strvec_pushf(&cmd.args, "--ref-format=%s",
722 ref_storage_format_to_name(ref_storage_format));
723
724 if (filter_submodules && filter_options.choice)
725 strvec_pushf(&cmd.args, "--filter=%s",
726 expand_list_objects_filter_spec(&filter_options));
727
728 if (option_single_branch >= 0)
729 strvec_push(&cmd.args, option_single_branch ?
730 "--single-branch" :
731 "--no-single-branch");
732
733 cmd.git_cmd = 1;
734 err = run_command(&cmd);
735 }
736
737 return err;
738 }
739
740 static int git_clone_config(const char *k, const char *v,
741 const struct config_context *ctx, void *cb)
742 {
743 if (!strcmp(k, "clone.defaultremotename")) {
744 if (!v)
745 return config_error_nonbool(k);
746 free(remote_name);
747 remote_name = xstrdup(v);
748 }
749 if (!strcmp(k, "clone.rejectshallow"))
750 config_reject_shallow = git_config_bool(k, v);
751 if (!strcmp(k, "clone.filtersubmodules"))
752 config_filter_submodules = git_config_bool(k, v);
753
754 return git_default_config(k, v, ctx, cb);
755 }
756
757 static int write_one_config(const char *key, const char *value,
758 const struct config_context *ctx,
759 void *data)
760 {
761 /*
762 * give git_clone_config a chance to write config values back to the
763 * environment, since git_config_set_multivar_gently only deals with
764 * config-file writes
765 */
766 int apply_failed = git_clone_config(key, value, ctx, data);
767 if (apply_failed)
768 return apply_failed;
769
770 return git_config_set_multivar_gently(key,
771 value ? value : "true",
772 CONFIG_REGEX_NONE, 0);
773 }
774
775 static void write_config(struct string_list *config)
776 {
777 int i;
778
779 for (i = 0; i < config->nr; i++) {
780 if (git_config_parse_parameter(config->items[i].string,
781 write_one_config, NULL) < 0)
782 die(_("unable to write parameters to config file"));
783 }
784 }
785
786 static void write_refspec_config(const char *src_ref_prefix,
787 const struct ref *our_head_points_at,
788 const struct ref *remote_head_points_at,
789 struct strbuf *branch_top)
790 {
791 struct strbuf key = STRBUF_INIT;
792 struct strbuf value = STRBUF_INIT;
793
794 if (option_mirror || !option_bare) {
795 if (option_single_branch && !option_mirror) {
796 if (option_branch) {
797 if (starts_with(our_head_points_at->name, "refs/tags/"))
798 strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
799 our_head_points_at->name);
800 else
801 strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
802 branch_top->buf, option_branch);
803 } else if (remote_head_points_at) {
804 const char *head = remote_head_points_at->name;
805 if (!skip_prefix(head, "refs/heads/", &head))
806 BUG("remote HEAD points at non-head?");
807
808 strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
809 branch_top->buf, head);
810 }
811 /*
812 * otherwise, the next "git fetch" will
813 * simply fetch from HEAD without updating
814 * any remote-tracking branch, which is what
815 * we want.
816 */
817 } else {
818 strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
819 }
820 /* Configure the remote */
821 if (value.len) {
822 strbuf_addf(&key, "remote.%s.fetch", remote_name);
823 git_config_set_multivar(key.buf, value.buf, "^$", 0);
824 strbuf_reset(&key);
825
826 if (option_mirror) {
827 strbuf_addf(&key, "remote.%s.mirror", remote_name);
828 git_config_set(key.buf, "true");
829 strbuf_reset(&key);
830 }
831 }
832 }
833
834 strbuf_release(&key);
835 strbuf_release(&value);
836 }
837
838 static void dissociate_from_references(void)
839 {
840 char *alternates = repo_git_path(the_repository, "objects/info/alternates");
841
842 if (!access(alternates, F_OK)) {
843 struct child_process cmd = CHILD_PROCESS_INIT;
844
845 cmd.git_cmd = 1;
846 cmd.no_stdin = 1;
847 strvec_pushl(&cmd.args, "repack", "-a", "-d", NULL);
848 if (run_command(&cmd))
849 die(_("cannot repack to clean up"));
850 if (unlink(alternates) && errno != ENOENT)
851 die_errno(_("cannot unlink temporary alternates file"));
852 }
853 free(alternates);
854 }
855
856 static int path_exists(const char *path)
857 {
858 struct stat sb;
859 return !stat(path, &sb);
860 }
861
862 int cmd_clone(int argc,
863 const char **argv,
864 const char *prefix,
865 struct repository *repository UNUSED)
866 {
867 int is_bundle = 0, is_local;
868 int reject_shallow = 0;
869 const char *repo_name, *repo, *work_tree, *git_dir;
870 char *repo_to_free = NULL;
871 char *path = NULL, *dir, *display_repo = NULL;
872 int dest_exists, real_dest_exists = 0;
873 const struct ref *refs, *remote_head;
874 struct ref *remote_head_points_at = NULL;
875 const struct ref *our_head_points_at;
876 char *unborn_head = NULL;
877 struct ref *mapped_refs = NULL;
878 const struct ref *ref;
879 struct strbuf key = STRBUF_INIT;
880 struct strbuf buf = STRBUF_INIT;
881 struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
882 struct transport *transport = NULL;
883 const char *src_ref_prefix = "refs/heads/";
884 struct remote *remote;
885 int err = 0, complete_refs_before_fetch = 1;
886 int submodule_progress;
887 int filter_submodules = 0;
888 int hash_algo;
889 enum ref_storage_format ref_storage_format = REF_STORAGE_FORMAT_UNKNOWN;
890 const int do_not_override_repo_unix_permissions = -1;
891 int option_reject_shallow = -1; /* unspecified */
892 int deepen = 0;
893 char *option_template = NULL, *option_depth = NULL, *option_since = NULL;
894 char *option_origin = NULL;
895 struct string_list option_not = STRING_LIST_INIT_NODUP;
896 const char *real_git_dir = NULL;
897 const char *ref_format = NULL;
898 const char *option_upload_pack = "git-upload-pack";
899 int option_progress = -1;
900 int option_sparse_checkout = 0;
901 enum transport_family family = TRANSPORT_FAMILY_ALL;
902 struct string_list option_config = STRING_LIST_INIT_DUP;
903 int option_dissociate = 0;
904 int option_filter_submodules = -1; /* unspecified */
905 struct string_list server_options = STRING_LIST_INIT_NODUP;
906 const char *bundle_uri = NULL;
907 char *option_rev = NULL;
908
909 struct clone_opts opts = CLONE_OPTS_INIT;
910
911 struct transport_ls_refs_options transport_ls_refs_options =
912 TRANSPORT_LS_REFS_OPTIONS_INIT;
913
914 struct option builtin_clone_options[] = {
915 OPT__VERBOSITY(&option_verbosity),
916 OPT_BOOL(0, "progress", &option_progress,
917 N_("force progress reporting")),
918 OPT_BOOL(0, "reject-shallow", &option_reject_shallow,
919 N_("don't clone shallow repository")),
920 OPT_BOOL('n', "no-checkout", &option_no_checkout,
921 N_("don't create a checkout")),
922 OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
923 OPT_HIDDEN_BOOL(0, "naked", &option_bare,
924 N_("create a bare repository")),
925 OPT_BOOL(0, "mirror", &option_mirror,
926 N_("create a mirror repository (implies --bare)")),
927 OPT_BOOL('l', "local", &option_local,
928 N_("to clone from a local repository")),
929 OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
930 N_("don't use local hardlinks, always copy")),
931 OPT_BOOL('s', "shared", &option_shared,
932 N_("setup as shared repository")),
933 {
934 .type = OPTION_CALLBACK,
935 .long_name = "recurse-submodules",
936 .value = &option_recurse_submodules,
937 .argh = N_("pathspec"),
938 .help = N_("initialize submodules in the clone"),
939 .flags = PARSE_OPT_OPTARG,
940 .callback = recurse_submodules_cb,
941 .defval = (intptr_t)".",
942 },
943 OPT_ALIAS(0, "recursive", "recurse-submodules"),
944 OPT_INTEGER('j', "jobs", &max_jobs,
945 N_("number of submodules cloned in parallel")),
946 OPT_STRING(0, "template", &option_template, N_("template-directory"),
947 N_("directory from which templates will be used")),
948 OPT_STRING_LIST(0, "reference", &option_required_reference, N_("repo"),
949 N_("reference repository")),
950 OPT_STRING_LIST(0, "reference-if-able", &option_optional_reference,
951 N_("repo"), N_("reference repository")),
952 OPT_BOOL(0, "dissociate", &option_dissociate,
953 N_("use --reference only while cloning")),
954 OPT_STRING('o', "origin", &option_origin, N_("name"),
955 N_("use <name> instead of 'origin' to track upstream")),
956 OPT_STRING('b', "branch", &option_branch, N_("branch"),
957 N_("checkout <branch> instead of the remote's HEAD")),
958 OPT_STRING(0, "revision", &option_rev, N_("rev"),
959 N_("clone single revision <rev> and check out")),
960 OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
961 N_("path to git-upload-pack on the remote")),
962 OPT_STRING(0, "depth", &option_depth, N_("depth"),
963 N_("create a shallow clone of that depth")),
964 OPT_STRING(0, "shallow-since", &option_since, N_("time"),
965 N_("create a shallow clone since a specific time")),
966 OPT_STRING_LIST(0, "shallow-exclude", &option_not, N_("ref"),
967 N_("deepen history of shallow clone, excluding ref")),
968 OPT_BOOL(0, "single-branch", &option_single_branch,
969 N_("clone only one branch, HEAD or --branch")),
970 OPT_BOOL(0, "tags", &option_tags,
971 N_("clone tags, and make later fetches not to follow them")),
972 OPT_BOOL(0, "shallow-submodules", &option_shallow_submodules,
973 N_("any cloned submodules will be shallow")),
974 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
975 N_("separate git dir from working tree")),
976 OPT_STRING(0, "ref-format", &ref_format, N_("format"),
977 N_("specify the reference format to use")),
978 OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
979 N_("set config inside the new repository")),
980 OPT_STRING_LIST(0, "server-option", &server_options,
981 N_("server-specific"), N_("option to transmit")),
982 OPT_IPVERSION(&family),
983 OPT_PARSE_LIST_OBJECTS_FILTER(&filter_options),
984 OPT_BOOL(0, "also-filter-submodules", &option_filter_submodules,
985 N_("apply partial clone filters to submodules")),
986 OPT_BOOL(0, "remote-submodules", &option_remote_submodules,
987 N_("any cloned submodules will use their remote-tracking branch")),
988 OPT_BOOL(0, "sparse", &option_sparse_checkout,
989 N_("initialize sparse-checkout file to include only files at root")),
990 OPT_STRING(0, "bundle-uri", &bundle_uri,
991 N_("uri"), N_("a URI for downloading bundles before fetching from origin remote")),
992 OPT_END()
993 };
994
995 const char * const builtin_clone_usage[] = {
996 N_("git clone [<options>] [--] <repo> [<dir>]"),
997 NULL
998 };
999
1000 packet_trace_identity("clone");
1001
1002 git_config(git_clone_config, NULL);
1003
1004 argc = parse_options(argc, argv, prefix, builtin_clone_options,
1005 builtin_clone_usage, 0);
1006
1007 if (argc > 2)
1008 usage_msg_opt(_("Too many arguments."),
1009 builtin_clone_usage, builtin_clone_options);
1010
1011 if (argc == 0)
1012 usage_msg_opt(_("You must specify a repository to clone."),
1013 builtin_clone_usage, builtin_clone_options);
1014
1015 if (option_depth || option_since || option_not.nr)
1016 deepen = 1;
1017 if (option_single_branch == -1)
1018 option_single_branch = deepen ? 1 : 0;
1019
1020 if (ref_format) {
1021 ref_storage_format = ref_storage_format_by_name(ref_format);
1022 if (ref_storage_format == REF_STORAGE_FORMAT_UNKNOWN)
1023 die(_("unknown ref storage format '%s'"), ref_format);
1024 }
1025
1026 if (option_mirror) {
1027 option_bare = 1;
1028 option_tags = 0;
1029 }
1030
1031 if (option_bare) {
1032 if (real_git_dir)
1033 die(_("options '%s' and '%s' cannot be used together"), "--bare", "--separate-git-dir");
1034 option_no_checkout = 1;
1035 }
1036
1037 if (bundle_uri && deepen)
1038 die(_("options '%s' and '%s' cannot be used together"),
1039 "--bundle-uri",
1040 "--depth/--shallow-since/--shallow-exclude");
1041
1042 repo_name = argv[0];
1043
1044 path = get_repo_path(repo_name, &is_bundle);
1045 if (path) {
1046 FREE_AND_NULL(path);
1047 repo = repo_to_free = absolute_pathdup(repo_name);
1048 } else if (strchr(repo_name, ':')) {
1049 repo = repo_name;
1050 display_repo = transport_anonymize_url(repo);
1051 } else
1052 die(_("repository '%s' does not exist"), repo_name);
1053
1054 /* no need to be strict, transport_set_option() will validate it again */
1055 if (option_depth && atoi(option_depth) < 1)
1056 die(_("depth %s is not a positive number"), option_depth);
1057
1058 if (argc == 2)
1059 dir = xstrdup(argv[1]);
1060 else
1061 dir = git_url_basename(repo_name, is_bundle, option_bare);
1062 strip_dir_trailing_slashes(dir);
1063
1064 dest_exists = path_exists(dir);
1065 if (dest_exists && !is_empty_dir(dir))
1066 die(_("destination path '%s' already exists and is not "
1067 "an empty directory."), dir);
1068
1069 if (real_git_dir) {
1070 real_dest_exists = path_exists(real_git_dir);
1071 if (real_dest_exists && !is_empty_dir(real_git_dir))
1072 die(_("repository path '%s' already exists and is not "
1073 "an empty directory."), real_git_dir);
1074 }
1075
1076
1077 strbuf_addf(&reflog_msg, "clone: from %s",
1078 display_repo ? display_repo : repo);
1079 free(display_repo);
1080
1081 if (option_bare)
1082 work_tree = NULL;
1083 else {
1084 work_tree = getenv("GIT_WORK_TREE");
1085 if (work_tree && path_exists(work_tree))
1086 die(_("working tree '%s' already exists."), work_tree);
1087 }
1088
1089 if (option_bare || work_tree)
1090 git_dir = xstrdup(dir);
1091 else {
1092 work_tree = dir;
1093 git_dir = mkpathdup("%s/.git", dir);
1094 }
1095
1096 atexit(remove_junk);
1097 sigchain_push_common(remove_junk_on_signal);
1098
1099 if (!option_bare) {
1100 if (safe_create_leading_directories_const(the_repository, work_tree) < 0)
1101 die_errno(_("could not create leading directories of '%s'"),
1102 work_tree);
1103 if (dest_exists)
1104 junk_work_tree_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1105 else if (mkdir(work_tree, 0777))
1106 die_errno(_("could not create work tree dir '%s'"),
1107 work_tree);
1108 junk_work_tree = work_tree;
1109 set_git_work_tree(work_tree);
1110 }
1111
1112 if (real_git_dir) {
1113 if (real_dest_exists)
1114 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1115 junk_git_dir = real_git_dir;
1116 } else {
1117 if (dest_exists)
1118 junk_git_dir_flags |= REMOVE_DIR_KEEP_TOPLEVEL;
1119 junk_git_dir = git_dir;
1120 }
1121 if (safe_create_leading_directories_const(the_repository, git_dir) < 0)
1122 die(_("could not create leading directories of '%s'"), git_dir);
1123
1124 if (0 <= option_verbosity) {
1125 if (option_bare)
1126 fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
1127 else
1128 fprintf(stderr, _("Cloning into '%s'...\n"), dir);
1129 }
1130
1131 if (option_recurse_submodules.nr > 0) {
1132 struct string_list_item *item;
1133 struct strbuf sb = STRBUF_INIT;
1134 int val;
1135
1136 /* remove duplicates */
1137 string_list_sort(&option_recurse_submodules);
1138 string_list_remove_duplicates(&option_recurse_submodules, 0);
1139
1140 /*
1141 * NEEDSWORK: In a multi-working-tree world, this needs to be
1142 * set in the per-worktree config.
1143 */
1144 for_each_string_list_item(item, &option_recurse_submodules) {
1145 strbuf_addf(&sb, "submodule.active=%s",
1146 item->string);
1147 string_list_append(&option_config, sb.buf);
1148 strbuf_reset(&sb);
1149 }
1150
1151 if (!git_config_get_bool("submodule.stickyRecursiveClone", &val) &&
1152 val)
1153 string_list_append(&option_config, "submodule.recurse=true");
1154
1155 if (option_required_reference.nr &&
1156 option_optional_reference.nr)
1157 die(_("clone --recursive is not compatible with "
1158 "both --reference and --reference-if-able"));
1159 else if (option_required_reference.nr) {
1160 string_list_append(&option_config,
1161 "submodule.alternateLocation=superproject");
1162 string_list_append(&option_config,
1163 "submodule.alternateErrorStrategy=die");
1164 } else if (option_optional_reference.nr) {
1165 string_list_append(&option_config,
1166 "submodule.alternateLocation=superproject");
1167 string_list_append(&option_config,
1168 "submodule.alternateErrorStrategy=info");
1169 }
1170
1171 strbuf_release(&sb);
1172 }
1173
1174 /*
1175 * Initialize the repository, but skip initializing the reference
1176 * database. We do not yet know about the object format of the
1177 * repository, and reference backends may persist that information into
1178 * their on-disk data structures.
1179 */
1180 init_db(git_dir, real_git_dir, option_template, GIT_HASH_UNKNOWN,
1181 ref_storage_format, NULL,
1182 do_not_override_repo_unix_permissions, INIT_DB_QUIET | INIT_DB_SKIP_REFDB);
1183
1184 if (real_git_dir) {
1185 free((char *)git_dir);
1186 git_dir = real_git_dir;
1187 }
1188
1189 /*
1190 * We have a chicken-and-egg situation between initializing the refdb
1191 * and spawning transport helpers:
1192 *
1193 * - Initializing the refdb requires us to know about the object
1194 * format. We thus have to spawn the transport helper to learn
1195 * about it.
1196 *
1197 * - The transport helper may want to access the Git repository. But
1198 * because the refdb has not been initialized, we don't have "HEAD"
1199 * or "refs/". Thus, the helper cannot find the Git repository.
1200 *
1201 * Ideally, we would have structured the helper protocol such that it's
1202 * mandatory for the helper to first announce its capabilities without
1203 * yet assuming a fully initialized repository. Like that, we could
1204 * have added a "lazy-refdb-init" capability that announces whether the
1205 * helper is ready to handle not-yet-initialized refdbs. If any helper
1206 * didn't support them, we would have fully initialized the refdb with
1207 * the SHA1 object format, but later on bailed out if we found out that
1208 * the remote repository used a different object format.
1209 *
1210 * But we didn't, and thus we use the following workaround to partially
1211 * initialize the repository's refdb such that it can be discovered by
1212 * Git commands. To do so, we:
1213 *
1214 * - Create an invalid HEAD ref pointing at "refs/heads/.invalid".
1215 *
1216 * - Create the "refs/" directory.
1217 *
1218 * - Set up the ref storage format and repository version as
1219 * required.
1220 *
1221 * This is sufficient for Git commands to discover the Git directory.
1222 */
1223 initialize_repository_version(GIT_HASH_UNKNOWN,
1224 the_repository->ref_storage_format, 1);
1225
1226 strbuf_addf(&buf, "%s/HEAD", git_dir);
1227 write_file(buf.buf, "ref: refs/heads/.invalid");
1228
1229 strbuf_reset(&buf);
1230 strbuf_addf(&buf, "%s/refs", git_dir);
1231 safe_create_dir(the_repository, buf.buf, 1);
1232
1233 /*
1234 * additional config can be injected with -c, make sure it's included
1235 * after init_db, which clears the entire config environment.
1236 */
1237 write_config(&option_config);
1238
1239 /*
1240 * re-read config after init_db and write_config to pick up any config
1241 * injected by --template and --config, respectively.
1242 */
1243 git_config(git_clone_config, NULL);
1244
1245 /*
1246 * If option_reject_shallow is specified from CLI option,
1247 * ignore config_reject_shallow from git_clone_config.
1248 */
1249 if (config_reject_shallow != -1)
1250 reject_shallow = config_reject_shallow;
1251 if (option_reject_shallow != -1)
1252 reject_shallow = option_reject_shallow;
1253
1254 /*
1255 * If option_filter_submodules is specified from CLI option,
1256 * ignore config_filter_submodules from git_clone_config.
1257 */
1258 if (config_filter_submodules != -1)
1259 filter_submodules = config_filter_submodules;
1260 if (option_filter_submodules != -1)
1261 filter_submodules = option_filter_submodules;
1262
1263 /*
1264 * Exit if the user seems to be doing something silly with submodule
1265 * filter flags (but not with filter configs, as those should be
1266 * set-and-forget).
1267 */
1268 if (option_filter_submodules > 0 && !filter_options.choice)
1269 die(_("the option '%s' requires '%s'"),
1270 "--also-filter-submodules", "--filter");
1271 if (option_filter_submodules > 0 && !option_recurse_submodules.nr)
1272 die(_("the option '%s' requires '%s'"),
1273 "--also-filter-submodules", "--recurse-submodules");
1274
1275 /*
1276 * apply the remote name provided by --origin only after this second
1277 * call to git_config, to ensure it overrides all config-based values.
1278 */
1279 if (option_origin) {
1280 free(remote_name);
1281 remote_name = xstrdup(option_origin);
1282 }
1283
1284 if (!remote_name)
1285 remote_name = xstrdup("origin");
1286
1287 if (!valid_remote_name(remote_name))
1288 die(_("'%s' is not a valid remote name"), remote_name);
1289
1290 if (option_bare) {
1291 if (option_mirror)
1292 src_ref_prefix = "refs/";
1293 strbuf_addstr(&branch_top, src_ref_prefix);
1294
1295 git_config_set("core.bare", "true");
1296 } else if (!option_rev) {
1297 strbuf_addf(&branch_top, "refs/remotes/%s/", remote_name);
1298 }
1299
1300 strbuf_addf(&key, "remote.%s.url", remote_name);
1301 git_config_set(key.buf, repo);
1302 strbuf_reset(&key);
1303
1304 if (!option_tags) {
1305 strbuf_addf(&key, "remote.%s.tagOpt", remote_name);
1306 git_config_set(key.buf, "--no-tags");
1307 strbuf_reset(&key);
1308 }
1309
1310 if (option_required_reference.nr || option_optional_reference.nr)
1311 setup_reference();
1312
1313 remote = remote_get_early(remote_name);
1314
1315 if (!option_rev)
1316 refspec_appendf(&remote->fetch, "+%s*:%s*", src_ref_prefix,
1317 branch_top.buf);
1318
1319 path = get_repo_path(remote->url.v[0], &is_bundle);
1320 is_local = option_local != 0 && path && !is_bundle;
1321 if (is_local) {
1322 if (option_depth)
1323 warning(_("--depth is ignored in local clones; use file:// instead."));
1324 if (option_since)
1325 warning(_("--shallow-since is ignored in local clones; use file:// instead."));
1326 if (option_not.nr)
1327 warning(_("--shallow-exclude is ignored in local clones; use file:// instead."));
1328 if (filter_options.choice)
1329 warning(_("--filter is ignored in local clones; use file:// instead."));
1330 if (!access(mkpath("%s/shallow", path), F_OK)) {
1331 if (reject_shallow)
1332 die(_("source repository is shallow, reject to clone."));
1333 if (option_local > 0)
1334 warning(_("source repository is shallow, ignoring --local"));
1335 is_local = 0;
1336 }
1337 }
1338 if (option_local > 0 && !is_local)
1339 warning(_("--local is ignored"));
1340
1341 transport = transport_get(remote, path ? path : remote->url.v[0]);
1342 transport_set_verbosity(transport, option_verbosity, option_progress);
1343 transport->family = family;
1344 transport->cloning = 1;
1345
1346 if (is_bundle) {
1347 struct bundle_header header = BUNDLE_HEADER_INIT;
1348 int fd = read_bundle_header(path, &header);
1349 int has_filter = header.filter.choice != LOFC_DISABLED;
1350
1351 if (fd > 0)
1352 close(fd);
1353 bundle_header_release(&header);
1354 if (has_filter)
1355 die(_("cannot clone from filtered bundle"));
1356 }
1357
1358 transport_set_option(transport, TRANS_OPT_KEEP, "yes");
1359
1360 die_for_incompatible_opt2(!!option_rev, "--revision",
1361 !!option_branch, "--branch");
1362 die_for_incompatible_opt2(!!option_rev, "--revision",
1363 option_mirror, "--mirror");
1364
1365 if (reject_shallow)
1366 transport_set_option(transport, TRANS_OPT_REJECT_SHALLOW, "1");
1367 if (option_depth)
1368 transport_set_option(transport, TRANS_OPT_DEPTH,
1369 option_depth);
1370 if (option_since)
1371 transport_set_option(transport, TRANS_OPT_DEEPEN_SINCE,
1372 option_since);
1373 if (option_not.nr)
1374 transport_set_option(transport, TRANS_OPT_DEEPEN_NOT,
1375 (const char *)&option_not);
1376 if (option_single_branch) {
1377 transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1378
1379 if (option_branch)
1380 opts.wants_head = 0;
1381 }
1382
1383 if (option_upload_pack)
1384 transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1385 option_upload_pack);
1386
1387 if (server_options.nr)
1388 transport->server_options = &server_options;
1389
1390 if (filter_options.choice) {
1391 const char *spec =
1392 expand_list_objects_filter_spec(&filter_options);
1393 transport_set_option(transport, TRANS_OPT_LIST_OBJECTS_FILTER,
1394 spec);
1395 transport_set_option(transport, TRANS_OPT_FROM_PROMISOR, "1");
1396 }
1397
1398 if (transport->smart_options && !deepen && !filter_options.choice)
1399 transport->smart_options->check_self_contained_and_connected = 1;
1400
1401 if (option_rev) {
1402 option_tags = 0;
1403 option_single_branch = 0;
1404 opts.wants_head = 0;
1405 opts.detach = 1;
1406
1407 refspec_append(&remote->fetch, option_rev);
1408 }
1409
1410 if (option_tags || option_branch)
1411 /*
1412 * Add tags refspec when user asked for tags (implicitly) or
1413 * specified --branch, whose argument might be a tag.
1414 */
1415 refspec_append(&remote->fetch, TAG_REFSPEC);
1416
1417 refspec_ref_prefixes(&remote->fetch,
1418 &transport_ls_refs_options.ref_prefixes);
1419 if (option_branch)
1420 expand_ref_prefix(&transport_ls_refs_options.ref_prefixes,
1421 option_branch);
1422
1423 /*
1424 * As part of transport_get_remote_refs() the server tells us the hash
1425 * algorithm, which we require to initialize the repo. But calling that
1426 * function without any ref prefix, will cause the server to announce
1427 * all known refs. If the argument passed to --revision was a hex oid,
1428 * ref_prefixes will be empty so we fall back to asking about HEAD to
1429 * reduce traffic from the server.
1430 */
1431 if (opts.wants_head || transport_ls_refs_options.ref_prefixes.nr == 0)
1432 strvec_push(&transport_ls_refs_options.ref_prefixes, "HEAD");
1433
1434 refs = transport_get_remote_refs(transport, &transport_ls_refs_options);
1435
1436 /*
1437 * Now that we know what algorithm the remote side is using, let's set
1438 * ours to the same thing.
1439 */
1440 hash_algo = hash_algo_by_ptr(transport_get_hash_algo(transport));
1441 initialize_repository_version(hash_algo, the_repository->ref_storage_format, 1);
1442 repo_set_hash_algo(the_repository, hash_algo);
1443 create_reference_database(the_repository->ref_storage_format, NULL, 1);
1444
1445 /*
1446 * Before fetching from the remote, download and install bundle
1447 * data from the --bundle-uri option.
1448 */
1449 if (bundle_uri) {
1450 struct remote_state *state;
1451 int has_heuristic = 0;
1452
1453 /*
1454 * We need to save the remote state as our remote's lifetime is
1455 * tied to it.
1456 */
1457 state = the_repository->remote_state;
1458 the_repository->remote_state = NULL;
1459 repo_clear(the_repository);
1460
1461 /* At this point, we need the_repository to match the cloned repo. */
1462 if (repo_init(the_repository, git_dir, work_tree))
1463 warning(_("failed to initialize the repo, skipping bundle URI"));
1464 else if (fetch_bundle_uri(the_repository, bundle_uri, &has_heuristic))
1465 warning(_("failed to fetch objects from bundle URI '%s'"),
1466 bundle_uri);
1467 else if (has_heuristic)
1468 git_config_set_gently("fetch.bundleuri", bundle_uri);
1469
1470 remote_state_clear(the_repository->remote_state);
1471 free(the_repository->remote_state);
1472 the_repository->remote_state = state;
1473 } else {
1474 /*
1475 * Populate transport->got_remote_bundle_uri and
1476 * transport->bundle_uri. We might get nothing.
1477 */
1478 transport_get_remote_bundle_uri(transport);
1479
1480 if (transport->bundles &&
1481 hashmap_get_size(&transport->bundles->bundles)) {
1482 struct remote_state *state;
1483
1484 /*
1485 * We need to save the remote state as our remote's
1486 * lifetime is tied to it.
1487 */
1488 state = the_repository->remote_state;
1489 the_repository->remote_state = NULL;
1490 repo_clear(the_repository);
1491
1492 /* At this point, we need the_repository to match the cloned repo. */
1493 if (repo_init(the_repository, git_dir, work_tree))
1494 warning(_("failed to initialize the repo, skipping bundle URI"));
1495 else if (fetch_bundle_list(the_repository,
1496 transport->bundles))
1497 warning(_("failed to fetch advertised bundles"));
1498
1499 remote_state_clear(the_repository->remote_state);
1500 free(the_repository->remote_state);
1501 the_repository->remote_state = state;
1502 } else {
1503 clear_bundle_list(transport->bundles);
1504 FREE_AND_NULL(transport->bundles);
1505 }
1506 }
1507
1508 if (refs)
1509 mapped_refs = wanted_peer_refs(&opts, refs, &remote->fetch);
1510
1511 if (mapped_refs) {
1512 /*
1513 * transport_get_remote_refs() may return refs with null sha-1
1514 * in mapped_refs (see struct transport->get_refs_list
1515 * comment). In that case we need fetch it early because
1516 * remote_head code below relies on it.
1517 *
1518 * for normal clones, transport_get_remote_refs() should
1519 * return reliable ref set, we can delay cloning until after
1520 * remote HEAD check.
1521 */
1522 for (ref = refs; ref; ref = ref->next)
1523 if (is_null_oid(&ref->old_oid)) {
1524 complete_refs_before_fetch = 0;
1525 break;
1526 }
1527
1528 if (!is_local && !complete_refs_before_fetch) {
1529 if (transport_fetch_refs(transport, mapped_refs))
1530 die(_("remote transport reported error"));
1531 }
1532 }
1533
1534 remote_head = find_ref_by_name(refs, "HEAD");
1535 remote_head_points_at = guess_remote_head(remote_head, mapped_refs,
1536 REMOTE_GUESS_HEAD_QUIET);
1537
1538 if (option_branch) {
1539 our_head_points_at = find_remote_branch(mapped_refs, option_branch);
1540 if (!our_head_points_at)
1541 die(_("Remote branch %s not found in upstream %s"),
1542 option_branch, remote_name);
1543 } else if (option_rev) {
1544 our_head_points_at = mapped_refs;
1545 if (!our_head_points_at)
1546 die(_("Remote revision %s not found in upstream %s"),
1547 option_rev, remote_name);
1548 } else if (remote_head_points_at) {
1549 our_head_points_at = remote_head_points_at;
1550 } else if (remote_head) {
1551 our_head_points_at = NULL;
1552 } else {
1553 char *to_free = NULL;
1554 const char *branch;
1555
1556 if (!mapped_refs) {
1557 warning(_("You appear to have cloned an empty repository."));
1558 option_no_checkout = 1;
1559 }
1560
1561 if (transport_ls_refs_options.unborn_head_target &&
1562 skip_prefix(transport_ls_refs_options.unborn_head_target,
1563 "refs/heads/", &branch)) {
1564 unborn_head = xstrdup(transport_ls_refs_options.unborn_head_target);
1565 } else {
1566 branch = to_free = repo_default_branch_name(the_repository, 0);
1567 unborn_head = xstrfmt("refs/heads/%s", branch);
1568 }
1569
1570 /*
1571 * We may have selected a local default branch name "foo",
1572 * and even though the remote's HEAD does not point there,
1573 * it may still have a "foo" branch. If so, set it up so
1574 * that we can follow the usual checkout code later.
1575 *
1576 * Note that for an empty repo we'll already have set
1577 * option_no_checkout above, which would work against us here.
1578 * But for an empty repo, find_remote_branch() can never find
1579 * a match.
1580 */
1581 our_head_points_at = find_remote_branch(mapped_refs, branch);
1582
1583 free(to_free);
1584 }
1585
1586 if (!option_rev)
1587 write_refspec_config(src_ref_prefix, our_head_points_at,
1588 remote_head_points_at, &branch_top);
1589
1590 if (filter_options.choice)
1591 partial_clone_register(remote_name, &filter_options);
1592
1593 if (is_local)
1594 clone_local(path, git_dir);
1595 else if (mapped_refs && complete_refs_before_fetch) {
1596 if (transport_fetch_refs(transport, mapped_refs))
1597 die(_("remote transport reported error"));
1598 }
1599
1600 update_remote_refs(refs, mapped_refs, remote_head_points_at,
1601 branch_top.buf, reflog_msg.buf, transport,
1602 !is_local);
1603
1604 update_head(&opts, our_head_points_at, remote_head, unborn_head, reflog_msg.buf);
1605
1606 /*
1607 * We want to show progress for recursive submodule clones iff
1608 * we did so for the main clone. But only the transport knows
1609 * the final decision for this flag, so we need to rescue the value
1610 * before we free the transport.
1611 */
1612 submodule_progress = transport->progress;
1613
1614 transport_unlock_pack(transport, 0);
1615 transport_disconnect(transport);
1616
1617 if (option_dissociate) {
1618 close_object_store(the_repository->objects);
1619 dissociate_from_references();
1620 }
1621
1622 if (option_sparse_checkout && git_sparse_checkout_init(dir))
1623 return 1;
1624
1625 junk_mode = JUNK_LEAVE_REPO;
1626 err = checkout(submodule_progress, filter_submodules,
1627 ref_storage_format);
1628
1629 string_list_clear(&option_not, 0);
1630 string_list_clear(&option_config, 0);
1631 string_list_clear(&server_options, 0);
1632
1633 free(remote_name);
1634 strbuf_release(&reflog_msg);
1635 strbuf_release(&branch_top);
1636 strbuf_release(&buf);
1637 strbuf_release(&key);
1638 free_refs(mapped_refs);
1639 free_refs(remote_head_points_at);
1640 free(unborn_head);
1641 free(dir);
1642 free(path);
1643 free(repo_to_free);
1644 junk_mode = JUNK_LEAVE_ALL;
1645
1646 transport_ls_refs_options_release(&transport_ls_refs_options);
1647 return err;
1648 }