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