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