builtin / clone.con commit Merge branch 'sb/submodule-helper-clone-regression-fix' into sb/submodule-init (7307dd8)
   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 "lockfile.h"
  13#include "parse-options.h"
  14#include "fetch-pack.h"
  15#include "refs.h"
  16#include "tree.h"
  17#include "tree-walk.h"
  18#include "unpack-trees.h"
  19#include "transport.h"
  20#include "strbuf.h"
  21#include "dir.h"
  22#include "sigchain.h"
  23#include "branch.h"
  24#include "remote.h"
  25#include "run-command.h"
  26#include "connected.h"
  27
  28/*
  29 * Overall FIXMEs:
  30 *  - respect DB_ENVIRONMENT for .git/objects.
  31 *
  32 * Implementation notes:
  33 *  - dropping use-separate-remote and no-separate-remote compatibility
  34 *
  35 */
  36static const char * const builtin_clone_usage[] = {
  37        N_("git clone [<options>] [--] <repo> [<dir>]"),
  38        NULL
  39};
  40
  41static int option_no_checkout, option_bare, option_mirror, option_single_branch = -1;
  42static int option_local = -1, option_no_hardlinks, option_shared, option_recursive;
  43static char *option_template, *option_depth;
  44static char *option_origin = NULL;
  45static char *option_branch = NULL;
  46static const char *real_git_dir;
  47static char *option_upload_pack = "git-upload-pack";
  48static int option_verbosity;
  49static int option_progress = -1;
  50static struct string_list option_config;
  51static struct string_list option_reference;
  52static int option_dissociate;
  53static int max_jobs = -1;
  54
  55static struct option builtin_clone_options[] = {
  56        OPT__VERBOSITY(&option_verbosity),
  57        OPT_BOOL(0, "progress", &option_progress,
  58                 N_("force progress reporting")),
  59        OPT_BOOL('n', "no-checkout", &option_no_checkout,
  60                 N_("don't create a checkout")),
  61        OPT_BOOL(0, "bare", &option_bare, N_("create a bare repository")),
  62        OPT_HIDDEN_BOOL(0, "naked", &option_bare,
  63                        N_("create a bare repository")),
  64        OPT_BOOL(0, "mirror", &option_mirror,
  65                 N_("create a mirror repository (implies bare)")),
  66        OPT_BOOL('l', "local", &option_local,
  67                N_("to clone from a local repository")),
  68        OPT_BOOL(0, "no-hardlinks", &option_no_hardlinks,
  69                    N_("don't use local hardlinks, always copy")),
  70        OPT_BOOL('s', "shared", &option_shared,
  71                    N_("setup as shared repository")),
  72        OPT_BOOL(0, "recursive", &option_recursive,
  73                    N_("initialize submodules in the clone")),
  74        OPT_BOOL(0, "recurse-submodules", &option_recursive,
  75                    N_("initialize submodules in the clone")),
  76        OPT_INTEGER('j', "jobs", &max_jobs,
  77                    N_("number of submodules cloned in parallel")),
  78        OPT_STRING(0, "template", &option_template, N_("template-directory"),
  79                   N_("directory from which templates will be used")),
  80        OPT_STRING_LIST(0, "reference", &option_reference, N_("repo"),
  81                        N_("reference repository")),
  82        OPT_BOOL(0, "dissociate", &option_dissociate,
  83                 N_("use --reference only while cloning")),
  84        OPT_STRING('o', "origin", &option_origin, N_("name"),
  85                   N_("use <name> instead of 'origin' to track upstream")),
  86        OPT_STRING('b', "branch", &option_branch, N_("branch"),
  87                   N_("checkout <branch> instead of the remote's HEAD")),
  88        OPT_STRING('u', "upload-pack", &option_upload_pack, N_("path"),
  89                   N_("path to git-upload-pack on the remote")),
  90        OPT_STRING(0, "depth", &option_depth, N_("depth"),
  91                    N_("create a shallow clone of that depth")),
  92        OPT_BOOL(0, "single-branch", &option_single_branch,
  93                    N_("clone only one branch, HEAD or --branch")),
  94        OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
  95                   N_("separate git dir from working tree")),
  96        OPT_STRING_LIST('c', "config", &option_config, N_("key=value"),
  97                        N_("set config inside the new repository")),
  98        OPT_END()
  99};
 100
 101static const char *get_repo_path_1(struct strbuf *path, int *is_bundle)
 102{
 103        static char *suffix[] = { "/.git", "", ".git/.git", ".git" };
 104        static char *bundle_suffix[] = { ".bundle", "" };
 105        size_t baselen = path->len;
 106        struct stat st;
 107        int i;
 108
 109        for (i = 0; i < ARRAY_SIZE(suffix); i++) {
 110                strbuf_setlen(path, baselen);
 111                strbuf_addstr(path, suffix[i]);
 112                if (stat(path->buf, &st))
 113                        continue;
 114                if (S_ISDIR(st.st_mode) && is_git_directory(path->buf)) {
 115                        *is_bundle = 0;
 116                        return path->buf;
 117                } else if (S_ISREG(st.st_mode) && st.st_size > 8) {
 118                        /* Is it a "gitfile"? */
 119                        char signature[8];
 120                        const char *dst;
 121                        int len, fd = open(path->buf, O_RDONLY);
 122                        if (fd < 0)
 123                                continue;
 124                        len = read_in_full(fd, signature, 8);
 125                        close(fd);
 126                        if (len != 8 || strncmp(signature, "gitdir: ", 8))
 127                                continue;
 128                        dst = read_gitfile(path->buf);
 129                        if (dst) {
 130                                *is_bundle = 0;
 131                                return dst;
 132                        }
 133                }
 134        }
 135
 136        for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
 137                strbuf_setlen(path, baselen);
 138                strbuf_addstr(path, bundle_suffix[i]);
 139                if (!stat(path->buf, &st) && S_ISREG(st.st_mode)) {
 140                        *is_bundle = 1;
 141                        return path->buf;
 142                }
 143        }
 144
 145        return NULL;
 146}
 147
 148static char *get_repo_path(const char *repo, int *is_bundle)
 149{
 150        struct strbuf path = STRBUF_INIT;
 151        const char *raw;
 152        char *canon;
 153
 154        strbuf_addstr(&path, repo);
 155        raw = get_repo_path_1(&path, is_bundle);
 156        canon = raw ? xstrdup(absolute_path(raw)) : NULL;
 157        strbuf_release(&path);
 158        return canon;
 159}
 160
 161static char *guess_dir_name(const char *repo, int is_bundle, int is_bare)
 162{
 163        const char *end = repo + strlen(repo), *start, *ptr;
 164        size_t len;
 165        char *dir;
 166
 167        /*
 168         * Skip scheme.
 169         */
 170        start = strstr(repo, "://");
 171        if (start == NULL)
 172                start = repo;
 173        else
 174                start += 3;
 175
 176        /*
 177         * Skip authentication data. The stripping does happen
 178         * greedily, such that we strip up to the last '@' inside
 179         * the host part.
 180         */
 181        for (ptr = start; ptr < end && !is_dir_sep(*ptr); ptr++) {
 182                if (*ptr == '@')
 183                        start = ptr + 1;
 184        }
 185
 186        /*
 187         * Strip trailing spaces, slashes and /.git
 188         */
 189        while (start < end && (is_dir_sep(end[-1]) || isspace(end[-1])))
 190                end--;
 191        if (end - start > 5 && is_dir_sep(end[-5]) &&
 192            !strncmp(end - 4, ".git", 4)) {
 193                end -= 5;
 194                while (start < end && is_dir_sep(end[-1]))
 195                        end--;
 196        }
 197
 198        /*
 199         * Strip trailing port number if we've got only a
 200         * hostname (that is, there is no dir separator but a
 201         * colon). This check is required such that we do not
 202         * strip URI's like '/foo/bar:2222.git', which should
 203         * result in a dir '2222' being guessed due to backwards
 204         * compatibility.
 205         */
 206        if (memchr(start, '/', end - start) == NULL
 207            && memchr(start, ':', end - start) != NULL) {
 208                ptr = end;
 209                while (start < ptr && isdigit(ptr[-1]) && ptr[-1] != ':')
 210                        ptr--;
 211                if (start < ptr && ptr[-1] == ':')
 212                        end = ptr - 1;
 213        }
 214
 215        /*
 216         * Find last component. To remain backwards compatible we
 217         * also regard colons as path separators, such that
 218         * cloning a repository 'foo:bar.git' would result in a
 219         * directory 'bar' being guessed.
 220         */
 221        ptr = end;
 222        while (start < ptr && !is_dir_sep(ptr[-1]) && ptr[-1] != ':')
 223                ptr--;
 224        start = ptr;
 225
 226        /*
 227         * Strip .{bundle,git}.
 228         */
 229        len = end - start;
 230        strip_suffix_mem(start, &len, is_bundle ? ".bundle" : ".git");
 231
 232        if (!len || (len == 1 && *start == '/'))
 233            die("No directory name could be guessed.\n"
 234                "Please specify a directory on the command line");
 235
 236        if (is_bare)
 237                dir = xstrfmt("%.*s.git", (int)len, start);
 238        else
 239                dir = xstrndup(start, len);
 240        /*
 241         * Replace sequences of 'control' characters and whitespace
 242         * with one ascii space, remove leading and trailing spaces.
 243         */
 244        if (*dir) {
 245                char *out = dir;
 246                int prev_space = 1 /* strip leading whitespace */;
 247                for (end = dir; *end; ++end) {
 248                        char ch = *end;
 249                        if ((unsigned char)ch < '\x20')
 250                                ch = '\x20';
 251                        if (isspace(ch)) {
 252                                if (prev_space)
 253                                        continue;
 254                                prev_space = 1;
 255                        } else
 256                                prev_space = 0;
 257                        *out++ = ch;
 258                }
 259                *out = '\0';
 260                if (out > dir && prev_space)
 261                        out[-1] = '\0';
 262        }
 263        return dir;
 264}
 265
 266static void strip_trailing_slashes(char *dir)
 267{
 268        char *end = dir + strlen(dir);
 269
 270        while (dir < end - 1 && is_dir_sep(end[-1]))
 271                end--;
 272        *end = '\0';
 273}
 274
 275static int add_one_reference(struct string_list_item *item, void *cb_data)
 276{
 277        char *ref_git;
 278        const char *repo;
 279        struct strbuf alternate = STRBUF_INIT;
 280
 281        /* Beware: read_gitfile(), real_path() and mkpath() return static buffer */
 282        ref_git = xstrdup(real_path(item->string));
 283
 284        repo = read_gitfile(ref_git);
 285        if (!repo)
 286                repo = read_gitfile(mkpath("%s/.git", ref_git));
 287        if (repo) {
 288                free(ref_git);
 289                ref_git = xstrdup(repo);
 290        }
 291
 292        if (!repo && is_directory(mkpath("%s/.git/objects", ref_git))) {
 293                char *ref_git_git = mkpathdup("%s/.git", ref_git);
 294                free(ref_git);
 295                ref_git = ref_git_git;
 296        } else if (!is_directory(mkpath("%s/objects", ref_git))) {
 297                struct strbuf sb = STRBUF_INIT;
 298                if (get_common_dir(&sb, ref_git))
 299                        die(_("reference repository '%s' as a linked checkout is not supported yet."),
 300                            item->string);
 301                die(_("reference repository '%s' is not a local repository."),
 302                    item->string);
 303        }
 304
 305        if (!access(mkpath("%s/shallow", ref_git), F_OK))
 306                die(_("reference repository '%s' is shallow"), item->string);
 307
 308        if (!access(mkpath("%s/info/grafts", ref_git), F_OK))
 309                die(_("reference repository '%s' is grafted"), item->string);
 310
 311        strbuf_addf(&alternate, "%s/objects", ref_git);
 312        add_to_alternates_file(alternate.buf);
 313        strbuf_release(&alternate);
 314        free(ref_git);
 315        return 0;
 316}
 317
 318static void setup_reference(void)
 319{
 320        for_each_string_list(&option_reference, add_one_reference, NULL);
 321}
 322
 323static void copy_alternates(struct strbuf *src, struct strbuf *dst,
 324                            const char *src_repo)
 325{
 326        /*
 327         * Read from the source objects/info/alternates file
 328         * and copy the entries to corresponding file in the
 329         * destination repository with add_to_alternates_file().
 330         * Both src and dst have "$path/objects/info/alternates".
 331         *
 332         * Instead of copying bit-for-bit from the original,
 333         * we need to append to existing one so that the already
 334         * created entry via "clone -s" is not lost, and also
 335         * to turn entries with paths relative to the original
 336         * absolute, so that they can be used in the new repository.
 337         */
 338        FILE *in = fopen(src->buf, "r");
 339        struct strbuf line = STRBUF_INIT;
 340
 341        while (strbuf_getline(&line, in, '\n') != EOF) {
 342                char *abs_path;
 343                if (!line.len || line.buf[0] == '#')
 344                        continue;
 345                if (is_absolute_path(line.buf)) {
 346                        add_to_alternates_file(line.buf);
 347                        continue;
 348                }
 349                abs_path = mkpathdup("%s/objects/%s", src_repo, line.buf);
 350                normalize_path_copy(abs_path, abs_path);
 351                add_to_alternates_file(abs_path);
 352                free(abs_path);
 353        }
 354        strbuf_release(&line);
 355        fclose(in);
 356}
 357
 358static void copy_or_link_directory(struct strbuf *src, struct strbuf *dest,
 359                                   const char *src_repo, int src_baselen)
 360{
 361        struct dirent *de;
 362        struct stat buf;
 363        int src_len, dest_len;
 364        DIR *dir;
 365
 366        dir = opendir(src->buf);
 367        if (!dir)
 368                die_errno(_("failed to open '%s'"), src->buf);
 369
 370        if (mkdir(dest->buf, 0777)) {
 371                if (errno != EEXIST)
 372                        die_errno(_("failed to create directory '%s'"), dest->buf);
 373                else if (stat(dest->buf, &buf))
 374                        die_errno(_("failed to stat '%s'"), dest->buf);
 375                else if (!S_ISDIR(buf.st_mode))
 376                        die(_("%s exists and is not a directory"), dest->buf);
 377        }
 378
 379        strbuf_addch(src, '/');
 380        src_len = src->len;
 381        strbuf_addch(dest, '/');
 382        dest_len = dest->len;
 383
 384        while ((de = readdir(dir)) != NULL) {
 385                strbuf_setlen(src, src_len);
 386                strbuf_addstr(src, de->d_name);
 387                strbuf_setlen(dest, dest_len);
 388                strbuf_addstr(dest, de->d_name);
 389                if (stat(src->buf, &buf)) {
 390                        warning (_("failed to stat %s\n"), src->buf);
 391                        continue;
 392                }
 393                if (S_ISDIR(buf.st_mode)) {
 394                        if (de->d_name[0] != '.')
 395                                copy_or_link_directory(src, dest,
 396                                                       src_repo, src_baselen);
 397                        continue;
 398                }
 399
 400                /* Files that cannot be copied bit-for-bit... */
 401                if (!strcmp(src->buf + src_baselen, "/info/alternates")) {
 402                        copy_alternates(src, dest, src_repo);
 403                        continue;
 404                }
 405
 406                if (unlink(dest->buf) && errno != ENOENT)
 407                        die_errno(_("failed to unlink '%s'"), dest->buf);
 408                if (!option_no_hardlinks) {
 409                        if (!link(src->buf, dest->buf))
 410                                continue;
 411                        if (option_local > 0)
 412                                die_errno(_("failed to create link '%s'"), dest->buf);
 413                        option_no_hardlinks = 1;
 414                }
 415                if (copy_file_with_time(dest->buf, src->buf, 0666))
 416                        die_errno(_("failed to copy file to '%s'"), dest->buf);
 417        }
 418        closedir(dir);
 419}
 420
 421static void clone_local(const char *src_repo, const char *dest_repo)
 422{
 423        if (option_shared) {
 424                struct strbuf alt = STRBUF_INIT;
 425                strbuf_addf(&alt, "%s/objects", src_repo);
 426                add_to_alternates_file(alt.buf);
 427                strbuf_release(&alt);
 428        } else {
 429                struct strbuf src = STRBUF_INIT;
 430                struct strbuf dest = STRBUF_INIT;
 431                get_common_dir(&src, src_repo);
 432                get_common_dir(&dest, dest_repo);
 433                strbuf_addstr(&src, "/objects");
 434                strbuf_addstr(&dest, "/objects");
 435                copy_or_link_directory(&src, &dest, src_repo, src.len);
 436                strbuf_release(&src);
 437                strbuf_release(&dest);
 438        }
 439
 440        if (0 <= option_verbosity)
 441                fprintf(stderr, _("done.\n"));
 442}
 443
 444static const char *junk_work_tree;
 445static const char *junk_git_dir;
 446static enum {
 447        JUNK_LEAVE_NONE,
 448        JUNK_LEAVE_REPO,
 449        JUNK_LEAVE_ALL
 450} junk_mode = JUNK_LEAVE_NONE;
 451
 452static const char junk_leave_repo_msg[] =
 453N_("Clone succeeded, but checkout failed.\n"
 454   "You can inspect what was checked out with 'git status'\n"
 455   "and retry the checkout with 'git checkout -f HEAD'\n");
 456
 457static void remove_junk(void)
 458{
 459        struct strbuf sb = STRBUF_INIT;
 460
 461        switch (junk_mode) {
 462        case JUNK_LEAVE_REPO:
 463                warning("%s", _(junk_leave_repo_msg));
 464                /* fall-through */
 465        case JUNK_LEAVE_ALL:
 466                return;
 467        default:
 468                /* proceed to removal */
 469                break;
 470        }
 471
 472        if (junk_git_dir) {
 473                strbuf_addstr(&sb, junk_git_dir);
 474                remove_dir_recursively(&sb, 0);
 475                strbuf_reset(&sb);
 476        }
 477        if (junk_work_tree) {
 478                strbuf_addstr(&sb, junk_work_tree);
 479                remove_dir_recursively(&sb, 0);
 480                strbuf_reset(&sb);
 481        }
 482}
 483
 484static void remove_junk_on_signal(int signo)
 485{
 486        remove_junk();
 487        sigchain_pop(signo);
 488        raise(signo);
 489}
 490
 491static struct ref *find_remote_branch(const struct ref *refs, const char *branch)
 492{
 493        struct ref *ref;
 494        struct strbuf head = STRBUF_INIT;
 495        strbuf_addstr(&head, "refs/heads/");
 496        strbuf_addstr(&head, branch);
 497        ref = find_ref_by_name(refs, head.buf);
 498        strbuf_release(&head);
 499
 500        if (ref)
 501                return ref;
 502
 503        strbuf_addstr(&head, "refs/tags/");
 504        strbuf_addstr(&head, branch);
 505        ref = find_ref_by_name(refs, head.buf);
 506        strbuf_release(&head);
 507
 508        return ref;
 509}
 510
 511static struct ref *wanted_peer_refs(const struct ref *refs,
 512                struct refspec *refspec)
 513{
 514        struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
 515        struct ref *local_refs = head;
 516        struct ref **tail = head ? &head->next : &local_refs;
 517
 518        if (option_single_branch) {
 519                struct ref *remote_head = NULL;
 520
 521                if (!option_branch)
 522                        remote_head = guess_remote_head(head, refs, 0);
 523                else {
 524                        local_refs = NULL;
 525                        tail = &local_refs;
 526                        remote_head = copy_ref(find_remote_branch(refs, option_branch));
 527                }
 528
 529                if (!remote_head && option_branch)
 530                        warning(_("Could not find remote branch %s to clone."),
 531                                option_branch);
 532                else {
 533                        get_fetch_map(remote_head, refspec, &tail, 0);
 534
 535                        /* if --branch=tag, pull the requested tag explicitly */
 536                        get_fetch_map(remote_head, tag_refspec, &tail, 0);
 537                }
 538        } else
 539                get_fetch_map(refs, refspec, &tail, 0);
 540
 541        if (!option_mirror && !option_single_branch)
 542                get_fetch_map(refs, tag_refspec, &tail, 0);
 543
 544        return local_refs;
 545}
 546
 547static void write_remote_refs(const struct ref *local_refs)
 548{
 549        const struct ref *r;
 550
 551        struct ref_transaction *t;
 552        struct strbuf err = STRBUF_INIT;
 553
 554        t = ref_transaction_begin(&err);
 555        if (!t)
 556                die("%s", err.buf);
 557
 558        for (r = local_refs; r; r = r->next) {
 559                if (!r->peer_ref)
 560                        continue;
 561                if (ref_transaction_create(t, r->peer_ref->name, r->old_oid.hash,
 562                                           0, NULL, &err))
 563                        die("%s", err.buf);
 564        }
 565
 566        if (initial_ref_transaction_commit(t, &err))
 567                die("%s", err.buf);
 568
 569        strbuf_release(&err);
 570        ref_transaction_free(t);
 571}
 572
 573static void write_followtags(const struct ref *refs, const char *msg)
 574{
 575        const struct ref *ref;
 576        for (ref = refs; ref; ref = ref->next) {
 577                if (!starts_with(ref->name, "refs/tags/"))
 578                        continue;
 579                if (ends_with(ref->name, "^{}"))
 580                        continue;
 581                if (!has_object_file(&ref->old_oid))
 582                        continue;
 583                update_ref(msg, ref->name, ref->old_oid.hash,
 584                           NULL, 0, UPDATE_REFS_DIE_ON_ERR);
 585        }
 586}
 587
 588static int iterate_ref_map(void *cb_data, unsigned char sha1[20])
 589{
 590        struct ref **rm = cb_data;
 591        struct ref *ref = *rm;
 592
 593        /*
 594         * Skip anything missing a peer_ref, which we are not
 595         * actually going to write a ref for.
 596         */
 597        while (ref && !ref->peer_ref)
 598                ref = ref->next;
 599        /* Returning -1 notes "end of list" to the caller. */
 600        if (!ref)
 601                return -1;
 602
 603        hashcpy(sha1, ref->old_oid.hash);
 604        *rm = ref->next;
 605        return 0;
 606}
 607
 608static void update_remote_refs(const struct ref *refs,
 609                               const struct ref *mapped_refs,
 610                               const struct ref *remote_head_points_at,
 611                               const char *branch_top,
 612                               const char *msg,
 613                               struct transport *transport,
 614                               int check_connectivity)
 615{
 616        const struct ref *rm = mapped_refs;
 617
 618        if (check_connectivity) {
 619                if (transport->progress)
 620                        fprintf(stderr, _("Checking connectivity... "));
 621                if (check_everything_connected_with_transport(iterate_ref_map,
 622                                                              0, &rm, transport))
 623                        die(_("remote did not send all necessary objects"));
 624                if (transport->progress)
 625                        fprintf(stderr, _("done.\n"));
 626        }
 627
 628        if (refs) {
 629                write_remote_refs(mapped_refs);
 630                if (option_single_branch)
 631                        write_followtags(refs, msg);
 632        }
 633
 634        if (remote_head_points_at && !option_bare) {
 635                struct strbuf head_ref = STRBUF_INIT;
 636                strbuf_addstr(&head_ref, branch_top);
 637                strbuf_addstr(&head_ref, "HEAD");
 638                create_symref(head_ref.buf,
 639                              remote_head_points_at->peer_ref->name,
 640                              msg);
 641        }
 642}
 643
 644static void update_head(const struct ref *our, const struct ref *remote,
 645                        const char *msg)
 646{
 647        const char *head;
 648        if (our && skip_prefix(our->name, "refs/heads/", &head)) {
 649                /* Local default branch link */
 650                create_symref("HEAD", our->name, NULL);
 651                if (!option_bare) {
 652                        update_ref(msg, "HEAD", our->old_oid.hash, NULL, 0,
 653                                   UPDATE_REFS_DIE_ON_ERR);
 654                        install_branch_config(0, head, option_origin, our->name);
 655                }
 656        } else if (our) {
 657                struct commit *c = lookup_commit_reference(our->old_oid.hash);
 658                /* --branch specifies a non-branch (i.e. tags), detach HEAD */
 659                update_ref(msg, "HEAD", c->object.oid.hash,
 660                           NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
 661        } else if (remote) {
 662                /*
 663                 * We know remote HEAD points to a non-branch, or
 664                 * HEAD points to a branch but we don't know which one.
 665                 * Detach HEAD in all these cases.
 666                 */
 667                update_ref(msg, "HEAD", remote->old_oid.hash,
 668                           NULL, REF_NODEREF, UPDATE_REFS_DIE_ON_ERR);
 669        }
 670}
 671
 672static int checkout(void)
 673{
 674        unsigned char sha1[20];
 675        char *head;
 676        struct lock_file *lock_file;
 677        struct unpack_trees_options opts;
 678        struct tree *tree;
 679        struct tree_desc t;
 680        int err = 0;
 681
 682        if (option_no_checkout)
 683                return 0;
 684
 685        head = resolve_refdup("HEAD", RESOLVE_REF_READING, sha1, NULL);
 686        if (!head) {
 687                warning(_("remote HEAD refers to nonexistent ref, "
 688                          "unable to checkout.\n"));
 689                return 0;
 690        }
 691        if (!strcmp(head, "HEAD")) {
 692                if (advice_detached_head)
 693                        detach_advice(sha1_to_hex(sha1));
 694        } else {
 695                if (!starts_with(head, "refs/heads/"))
 696                        die(_("HEAD not found below refs/heads!"));
 697        }
 698        free(head);
 699
 700        /* We need to be in the new work tree for the checkout */
 701        setup_work_tree();
 702
 703        lock_file = xcalloc(1, sizeof(struct lock_file));
 704        hold_locked_index(lock_file, 1);
 705
 706        memset(&opts, 0, sizeof opts);
 707        opts.update = 1;
 708        opts.merge = 1;
 709        opts.fn = oneway_merge;
 710        opts.verbose_update = (option_verbosity >= 0);
 711        opts.src_index = &the_index;
 712        opts.dst_index = &the_index;
 713
 714        tree = parse_tree_indirect(sha1);
 715        parse_tree(tree);
 716        init_tree_desc(&t, tree->buffer, tree->size);
 717        if (unpack_trees(1, &t, &opts) < 0)
 718                die(_("unable to checkout working tree"));
 719
 720        if (write_locked_index(&the_index, lock_file, COMMIT_LOCK))
 721                die(_("unable to write new index file"));
 722
 723        err |= run_hook_le(NULL, "post-checkout", sha1_to_hex(null_sha1),
 724                           sha1_to_hex(sha1), "1", NULL);
 725
 726        if (!err && option_recursive) {
 727                struct argv_array args = ARGV_ARRAY_INIT;
 728                argv_array_pushl(&args, "submodule", "update", "--init", "--recursive", NULL);
 729
 730                if (max_jobs != -1)
 731                        argv_array_pushf(&args, "--jobs=%d", max_jobs);
 732
 733                err = run_command_v_opt(args.argv, RUN_GIT_CMD);
 734                argv_array_clear(&args);
 735        }
 736
 737        return err;
 738}
 739
 740static int write_one_config(const char *key, const char *value, void *data)
 741{
 742        return git_config_set_multivar(key, value ? value : "true", "^$", 0);
 743}
 744
 745static void write_config(struct string_list *config)
 746{
 747        int i;
 748
 749        for (i = 0; i < config->nr; i++) {
 750                if (git_config_parse_parameter(config->items[i].string,
 751                                               write_one_config, NULL) < 0)
 752                        die("unable to write parameters to config file");
 753        }
 754}
 755
 756static void write_refspec_config(const char *src_ref_prefix,
 757                const struct ref *our_head_points_at,
 758                const struct ref *remote_head_points_at,
 759                struct strbuf *branch_top)
 760{
 761        struct strbuf key = STRBUF_INIT;
 762        struct strbuf value = STRBUF_INIT;
 763
 764        if (option_mirror || !option_bare) {
 765                if (option_single_branch && !option_mirror) {
 766                        if (option_branch) {
 767                                if (starts_with(our_head_points_at->name, "refs/tags/"))
 768                                        strbuf_addf(&value, "+%s:%s", our_head_points_at->name,
 769                                                our_head_points_at->name);
 770                                else
 771                                        strbuf_addf(&value, "+%s:%s%s", our_head_points_at->name,
 772                                                branch_top->buf, option_branch);
 773                        } else if (remote_head_points_at) {
 774                                const char *head = remote_head_points_at->name;
 775                                if (!skip_prefix(head, "refs/heads/", &head))
 776                                        die("BUG: remote HEAD points at non-head?");
 777
 778                                strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
 779                                                branch_top->buf, head);
 780                        }
 781                        /*
 782                         * otherwise, the next "git fetch" will
 783                         * simply fetch from HEAD without updating
 784                         * any remote-tracking branch, which is what
 785                         * we want.
 786                         */
 787                } else {
 788                        strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top->buf);
 789                }
 790                /* Configure the remote */
 791                if (value.len) {
 792                        strbuf_addf(&key, "remote.%s.fetch", option_origin);
 793                        git_config_set_multivar(key.buf, value.buf, "^$", 0);
 794                        strbuf_reset(&key);
 795
 796                        if (option_mirror) {
 797                                strbuf_addf(&key, "remote.%s.mirror", option_origin);
 798                                git_config_set(key.buf, "true");
 799                                strbuf_reset(&key);
 800                        }
 801                }
 802        }
 803
 804        strbuf_release(&key);
 805        strbuf_release(&value);
 806}
 807
 808static void dissociate_from_references(void)
 809{
 810        static const char* argv[] = { "repack", "-a", "-d", NULL };
 811        char *alternates = git_pathdup("objects/info/alternates");
 812
 813        if (!access(alternates, F_OK)) {
 814                if (run_command_v_opt(argv, RUN_GIT_CMD|RUN_COMMAND_NO_STDIN))
 815                        die(_("cannot repack to clean up"));
 816                if (unlink(alternates) && errno != ENOENT)
 817                        die_errno(_("cannot unlink temporary alternates file"));
 818        }
 819        free(alternates);
 820}
 821
 822int cmd_clone(int argc, const char **argv, const char *prefix)
 823{
 824        int is_bundle = 0, is_local;
 825        struct stat buf;
 826        const char *repo_name, *repo, *work_tree, *git_dir;
 827        char *path, *dir;
 828        int dest_exists;
 829        const struct ref *refs, *remote_head;
 830        const struct ref *remote_head_points_at;
 831        const struct ref *our_head_points_at;
 832        struct ref *mapped_refs;
 833        const struct ref *ref;
 834        struct strbuf key = STRBUF_INIT, value = STRBUF_INIT;
 835        struct strbuf branch_top = STRBUF_INIT, reflog_msg = STRBUF_INIT;
 836        struct transport *transport = NULL;
 837        const char *src_ref_prefix = "refs/heads/";
 838        struct remote *remote;
 839        int err = 0, complete_refs_before_fetch = 1;
 840
 841        struct refspec *refspec;
 842        const char *fetch_pattern;
 843
 844        packet_trace_identity("clone");
 845        argc = parse_options(argc, argv, prefix, builtin_clone_options,
 846                             builtin_clone_usage, 0);
 847
 848        if (argc > 2)
 849                usage_msg_opt(_("Too many arguments."),
 850                        builtin_clone_usage, builtin_clone_options);
 851
 852        if (argc == 0)
 853                usage_msg_opt(_("You must specify a repository to clone."),
 854                        builtin_clone_usage, builtin_clone_options);
 855
 856        if (option_single_branch == -1)
 857                option_single_branch = option_depth ? 1 : 0;
 858
 859        if (option_mirror)
 860                option_bare = 1;
 861
 862        if (option_bare) {
 863                if (option_origin)
 864                        die(_("--bare and --origin %s options are incompatible."),
 865                            option_origin);
 866                if (real_git_dir)
 867                        die(_("--bare and --separate-git-dir are incompatible."));
 868                option_no_checkout = 1;
 869        }
 870
 871        if (!option_origin)
 872                option_origin = "origin";
 873
 874        repo_name = argv[0];
 875
 876        path = get_repo_path(repo_name, &is_bundle);
 877        if (path)
 878                repo = xstrdup(absolute_path(repo_name));
 879        else if (!strchr(repo_name, ':'))
 880                die(_("repository '%s' does not exist"), repo_name);
 881        else
 882                repo = repo_name;
 883
 884        /* no need to be strict, transport_set_option() will validate it again */
 885        if (option_depth && atoi(option_depth) < 1)
 886                die(_("depth %s is not a positive number"), option_depth);
 887
 888        if (argc == 2)
 889                dir = xstrdup(argv[1]);
 890        else
 891                dir = guess_dir_name(repo_name, is_bundle, option_bare);
 892        strip_trailing_slashes(dir);
 893
 894        dest_exists = !stat(dir, &buf);
 895        if (dest_exists && !is_empty_dir(dir))
 896                die(_("destination path '%s' already exists and is not "
 897                        "an empty directory."), dir);
 898
 899        strbuf_addf(&reflog_msg, "clone: from %s", repo);
 900
 901        if (option_bare)
 902                work_tree = NULL;
 903        else {
 904                work_tree = getenv("GIT_WORK_TREE");
 905                if (work_tree && !stat(work_tree, &buf))
 906                        die(_("working tree '%s' already exists."), work_tree);
 907        }
 908
 909        if (option_bare || work_tree)
 910                git_dir = xstrdup(dir);
 911        else {
 912                work_tree = dir;
 913                git_dir = mkpathdup("%s/.git", dir);
 914        }
 915
 916        atexit(remove_junk);
 917        sigchain_push_common(remove_junk_on_signal);
 918
 919        if (!option_bare) {
 920                if (safe_create_leading_directories_const(work_tree) < 0)
 921                        die_errno(_("could not create leading directories of '%s'"),
 922                                  work_tree);
 923                if (!dest_exists && mkdir(work_tree, 0777))
 924                        die_errno(_("could not create work tree dir '%s'"),
 925                                  work_tree);
 926                junk_work_tree = work_tree;
 927                set_git_work_tree(work_tree);
 928        }
 929
 930        junk_git_dir = git_dir;
 931        if (safe_create_leading_directories_const(git_dir) < 0)
 932                die(_("could not create leading directories of '%s'"), git_dir);
 933
 934        set_git_dir_init(git_dir, real_git_dir, 0);
 935        if (real_git_dir) {
 936                git_dir = real_git_dir;
 937                junk_git_dir = real_git_dir;
 938        }
 939
 940        if (0 <= option_verbosity) {
 941                if (option_bare)
 942                        fprintf(stderr, _("Cloning into bare repository '%s'...\n"), dir);
 943                else
 944                        fprintf(stderr, _("Cloning into '%s'...\n"), dir);
 945        }
 946        init_db(option_template, INIT_DB_QUIET);
 947        write_config(&option_config);
 948
 949        git_config(git_default_config, NULL);
 950
 951        if (option_bare) {
 952                if (option_mirror)
 953                        src_ref_prefix = "refs/";
 954                strbuf_addstr(&branch_top, src_ref_prefix);
 955
 956                git_config_set("core.bare", "true");
 957        } else {
 958                strbuf_addf(&branch_top, "refs/remotes/%s/", option_origin);
 959        }
 960
 961        strbuf_addf(&value, "+%s*:%s*", src_ref_prefix, branch_top.buf);
 962        strbuf_addf(&key, "remote.%s.url", option_origin);
 963        git_config_set(key.buf, repo);
 964        strbuf_reset(&key);
 965
 966        if (option_reference.nr)
 967                setup_reference();
 968
 969        fetch_pattern = value.buf;
 970        refspec = parse_fetch_refspec(1, &fetch_pattern);
 971
 972        strbuf_reset(&value);
 973
 974        remote = remote_get(option_origin);
 975        transport = transport_get(remote, remote->url[0]);
 976        transport_set_verbosity(transport, option_verbosity, option_progress);
 977
 978        path = get_repo_path(remote->url[0], &is_bundle);
 979        is_local = option_local != 0 && path && !is_bundle;
 980        if (is_local) {
 981                if (option_depth)
 982                        warning(_("--depth is ignored in local clones; use file:// instead."));
 983                if (!access(mkpath("%s/shallow", path), F_OK)) {
 984                        if (option_local > 0)
 985                                warning(_("source repository is shallow, ignoring --local"));
 986                        is_local = 0;
 987                }
 988        }
 989        if (option_local > 0 && !is_local)
 990                warning(_("--local is ignored"));
 991        transport->cloning = 1;
 992
 993        if (!transport->get_refs_list || (!is_local && !transport->fetch))
 994                die(_("Don't know how to clone %s"), transport->url);
 995
 996        transport_set_option(transport, TRANS_OPT_KEEP, "yes");
 997
 998        if (option_depth)
 999                transport_set_option(transport, TRANS_OPT_DEPTH,
1000                                     option_depth);
1001        if (option_single_branch)
1002                transport_set_option(transport, TRANS_OPT_FOLLOWTAGS, "1");
1003
1004        if (option_upload_pack)
1005                transport_set_option(transport, TRANS_OPT_UPLOADPACK,
1006                                     option_upload_pack);
1007
1008        if (transport->smart_options && !option_depth)
1009                transport->smart_options->check_self_contained_and_connected = 1;
1010
1011        refs = transport_get_remote_refs(transport);
1012
1013        if (refs) {
1014                mapped_refs = wanted_peer_refs(refs, refspec);
1015                /*
1016                 * transport_get_remote_refs() may return refs with null sha-1
1017                 * in mapped_refs (see struct transport->get_refs_list
1018                 * comment). In that case we need fetch it early because
1019                 * remote_head code below relies on it.
1020                 *
1021                 * for normal clones, transport_get_remote_refs() should
1022                 * return reliable ref set, we can delay cloning until after
1023                 * remote HEAD check.
1024                 */
1025                for (ref = refs; ref; ref = ref->next)
1026                        if (is_null_oid(&ref->old_oid)) {
1027                                complete_refs_before_fetch = 0;
1028                                break;
1029                        }
1030
1031                if (!is_local && !complete_refs_before_fetch)
1032                        transport_fetch_refs(transport, mapped_refs);
1033
1034                remote_head = find_ref_by_name(refs, "HEAD");
1035                remote_head_points_at =
1036                        guess_remote_head(remote_head, mapped_refs, 0);
1037
1038                if (option_branch) {
1039                        our_head_points_at =
1040                                find_remote_branch(mapped_refs, option_branch);
1041
1042                        if (!our_head_points_at)
1043                                die(_("Remote branch %s not found in upstream %s"),
1044                                    option_branch, option_origin);
1045                }
1046                else
1047                        our_head_points_at = remote_head_points_at;
1048        }
1049        else {
1050                if (option_branch)
1051                        die(_("Remote branch %s not found in upstream %s"),
1052                                        option_branch, option_origin);
1053
1054                warning(_("You appear to have cloned an empty repository."));
1055                mapped_refs = NULL;
1056                our_head_points_at = NULL;
1057                remote_head_points_at = NULL;
1058                remote_head = NULL;
1059                option_no_checkout = 1;
1060                if (!option_bare)
1061                        install_branch_config(0, "master", option_origin,
1062                                              "refs/heads/master");
1063        }
1064
1065        write_refspec_config(src_ref_prefix, our_head_points_at,
1066                        remote_head_points_at, &branch_top);
1067
1068        if (is_local)
1069                clone_local(path, git_dir);
1070        else if (refs && complete_refs_before_fetch)
1071                transport_fetch_refs(transport, mapped_refs);
1072
1073        update_remote_refs(refs, mapped_refs, remote_head_points_at,
1074                           branch_top.buf, reflog_msg.buf, transport, !is_local);
1075
1076        update_head(our_head_points_at, remote_head, reflog_msg.buf);
1077
1078        transport_unlock_pack(transport);
1079        transport_disconnect(transport);
1080
1081        if (option_dissociate) {
1082                close_all_packs();
1083                dissociate_from_references();
1084        }
1085
1086        junk_mode = JUNK_LEAVE_REPO;
1087        err = checkout();
1088
1089        strbuf_release(&reflog_msg);
1090        strbuf_release(&branch_top);
1091        strbuf_release(&key);
1092        strbuf_release(&value);
1093        junk_mode = JUNK_LEAVE_ALL;
1094
1095        free(refspec);
1096        return err;
1097}