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