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