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