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