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