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