builtin-clone.con commit Merge branch 'js/apply-recount' (27158e4)
   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 "cache.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 "pack-refs.h"
  22
  23/*
  24 * Overall FIXMEs:
  25 *  - respect DB_ENVIRONMENT for .git/objects.
  26 *
  27 * Implementation notes:
  28 *  - dropping use-separate-remote and no-separate-remote compatibility
  29 *
  30 */
  31static const char * const builtin_clone_usage[] = {
  32        "git-clone [options] [--] <repo> [<dir>]",
  33        NULL
  34};
  35
  36static int option_quiet, option_no_checkout, option_bare;
  37static int option_local, option_no_hardlinks, option_shared;
  38static char *option_template, *option_reference, *option_depth;
  39static char *option_origin = NULL;
  40static char *option_upload_pack = "git-upload-pack";
  41
  42static struct option builtin_clone_options[] = {
  43        OPT__QUIET(&option_quiet),
  44        OPT_BOOLEAN('n', "no-checkout", &option_no_checkout,
  45                    "don't create a checkout"),
  46        OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"),
  47        OPT_BOOLEAN(0, "naked", &option_bare, "create a bare repository"),
  48        OPT_BOOLEAN('l', "local", &option_local,
  49                    "to clone from a local repository"),
  50        OPT_BOOLEAN(0, "no-hardlinks", &option_no_hardlinks,
  51                    "don't use local hardlinks, always copy"),
  52        OPT_BOOLEAN('s', "shared", &option_shared,
  53                    "setup as shared repository"),
  54        OPT_STRING(0, "template", &option_template, "path",
  55                   "path the template repository"),
  56        OPT_STRING(0, "reference", &option_reference, "repo",
  57                   "reference repository"),
  58        OPT_STRING('o', "origin", &option_origin, "branch",
  59                   "use <branch> instead or 'origin' to track upstream"),
  60        OPT_STRING('u', "upload-pack", &option_upload_pack, "path",
  61                   "path to git-upload-pack on the remote"),
  62        OPT_STRING(0, "depth", &option_depth, "depth",
  63                    "create a shallow clone of that depth"),
  64
  65        OPT_END()
  66};
  67
  68static char *get_repo_path(const char *repo, int *is_bundle)
  69{
  70        static char *suffix[] = { "/.git", ".git", "" };
  71        static char *bundle_suffix[] = { ".bundle", "" };
  72        struct stat st;
  73        int i;
  74
  75        for (i = 0; i < ARRAY_SIZE(suffix); i++) {
  76                const char *path;
  77                path = mkpath("%s%s", repo, suffix[i]);
  78                if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
  79                        *is_bundle = 0;
  80                        return xstrdup(make_nonrelative_path(path));
  81                }
  82        }
  83
  84        for (i = 0; i < ARRAY_SIZE(bundle_suffix); i++) {
  85                const char *path;
  86                path = mkpath("%s%s", repo, bundle_suffix[i]);
  87                if (!stat(path, &st) && S_ISREG(st.st_mode)) {
  88                        *is_bundle = 1;
  89                        return xstrdup(make_nonrelative_path(path));
  90                }
  91        }
  92
  93        return NULL;
  94}
  95
  96static char *guess_dir_name(const char *repo, int is_bundle)
  97{
  98        const char *p, *start, *end, *limit;
  99        int after_slash_or_colon;
 100
 101        /* Guess dir name from repository: strip trailing '/',
 102         * strip trailing '[:/]*.{git,bundle}', strip leading '.*[/:]'. */
 103
 104        after_slash_or_colon = 1;
 105        limit = repo + strlen(repo);
 106        start = repo;
 107        end = limit;
 108        for (p = repo; p < limit; p++) {
 109                const char *prefix = is_bundle ? ".bundle" : ".git";
 110                if (!prefixcmp(p, prefix)) {
 111                        if (!after_slash_or_colon)
 112                                end = p;
 113                        p += strlen(prefix) - 1;
 114                } else if (!prefixcmp(p, ".bundle")) {
 115                        if (!after_slash_or_colon)
 116                                end = p;
 117                        p += 7;
 118                } else if (*p == '/' || *p == ':') {
 119                        if (end == limit)
 120                                end = p;
 121                        after_slash_or_colon = 1;
 122                } else if (after_slash_or_colon) {
 123                        start = p;
 124                        end = limit;
 125                        after_slash_or_colon = 0;
 126                }
 127        }
 128
 129        return xstrndup(start, end - start);
 130}
 131
 132static int is_directory(const char *path)
 133{
 134        struct stat buf;
 135
 136        return !stat(path, &buf) && S_ISDIR(buf.st_mode);
 137}
 138
 139static void setup_reference(const char *repo)
 140{
 141        const char *ref_git;
 142        char *ref_git_copy;
 143
 144        struct remote *remote;
 145        struct transport *transport;
 146        const struct ref *extra;
 147
 148        ref_git = make_absolute_path(option_reference);
 149
 150        if (is_directory(mkpath("%s/.git/objects", ref_git)))
 151                ref_git = mkpath("%s/.git", ref_git);
 152        else if (!is_directory(mkpath("%s/objects", ref_git)))
 153                die("reference repository '%s' is not a local directory.",
 154                    option_reference);
 155
 156        ref_git_copy = xstrdup(ref_git);
 157
 158        add_to_alternates_file(ref_git_copy);
 159
 160        remote = remote_get(ref_git_copy);
 161        transport = transport_get(remote, ref_git_copy);
 162        for (extra = transport_get_remote_refs(transport); extra;
 163             extra = extra->next)
 164                add_extra_ref(extra->name, extra->old_sha1, 0);
 165
 166        transport_disconnect(transport);
 167
 168        free(ref_git_copy);
 169}
 170
 171static void copy_or_link_directory(char *src, char *dest)
 172{
 173        struct dirent *de;
 174        struct stat buf;
 175        int src_len, dest_len;
 176        DIR *dir;
 177
 178        dir = opendir(src);
 179        if (!dir)
 180                die("failed to open %s\n", src);
 181
 182        if (mkdir(dest, 0777)) {
 183                if (errno != EEXIST)
 184                        die("failed to create directory %s\n", dest);
 185                else if (stat(dest, &buf))
 186                        die("failed to stat %s\n", dest);
 187                else if (!S_ISDIR(buf.st_mode))
 188                        die("%s exists and is not a directory\n", dest);
 189        }
 190
 191        src_len = strlen(src);
 192        src[src_len] = '/';
 193        dest_len = strlen(dest);
 194        dest[dest_len] = '/';
 195
 196        while ((de = readdir(dir)) != NULL) {
 197                strcpy(src + src_len + 1, de->d_name);
 198                strcpy(dest + dest_len + 1, de->d_name);
 199                if (stat(src, &buf)) {
 200                        warning ("failed to stat %s\n", src);
 201                        continue;
 202                }
 203                if (S_ISDIR(buf.st_mode)) {
 204                        if (de->d_name[0] != '.')
 205                                copy_or_link_directory(src, dest);
 206                        continue;
 207                }
 208
 209                if (unlink(dest) && errno != ENOENT)
 210                        die("failed to unlink %s\n", dest);
 211                if (!option_no_hardlinks) {
 212                        if (!link(src, dest))
 213                                continue;
 214                        if (option_local)
 215                                die("failed to create link %s\n", dest);
 216                        option_no_hardlinks = 1;
 217                }
 218                if (copy_file(dest, src, 0666))
 219                        die("failed to copy file to %s\n", dest);
 220        }
 221        closedir(dir);
 222}
 223
 224static const struct ref *clone_local(const char *src_repo,
 225                                     const char *dest_repo)
 226{
 227        const struct ref *ret;
 228        char src[PATH_MAX];
 229        char dest[PATH_MAX];
 230        struct remote *remote;
 231        struct transport *transport;
 232
 233        if (option_shared)
 234                add_to_alternates_file(src_repo);
 235        else {
 236                snprintf(src, PATH_MAX, "%s/objects", src_repo);
 237                snprintf(dest, PATH_MAX, "%s/objects", dest_repo);
 238                copy_or_link_directory(src, dest);
 239        }
 240
 241        remote = remote_get(src_repo);
 242        transport = transport_get(remote, src_repo);
 243        ret = transport_get_remote_refs(transport);
 244        transport_disconnect(transport);
 245        return ret;
 246}
 247
 248static const char *junk_work_tree;
 249static const char *junk_git_dir;
 250pid_t junk_pid;
 251
 252static void remove_junk(void)
 253{
 254        struct strbuf sb;
 255        if (getpid() != junk_pid)
 256                return;
 257        strbuf_init(&sb, 0);
 258        if (junk_git_dir) {
 259                strbuf_addstr(&sb, junk_git_dir);
 260                remove_dir_recursively(&sb, 0);
 261                strbuf_reset(&sb);
 262        }
 263        if (junk_work_tree) {
 264                strbuf_addstr(&sb, junk_work_tree);
 265                remove_dir_recursively(&sb, 0);
 266                strbuf_reset(&sb);
 267        }
 268}
 269
 270static void remove_junk_on_signal(int signo)
 271{
 272        remove_junk();
 273        signal(SIGINT, SIG_DFL);
 274        raise(signo);
 275}
 276
 277static const struct ref *locate_head(const struct ref *refs,
 278                                     const struct ref *mapped_refs,
 279                                     const struct ref **remote_head_p)
 280{
 281        const struct ref *remote_head = NULL;
 282        const struct ref *remote_master = NULL;
 283        const struct ref *r;
 284        for (r = refs; r; r = r->next)
 285                if (!strcmp(r->name, "HEAD"))
 286                        remote_head = r;
 287
 288        for (r = mapped_refs; r; r = r->next)
 289                if (!strcmp(r->name, "refs/heads/master"))
 290                        remote_master = r;
 291
 292        if (remote_head_p)
 293                *remote_head_p = remote_head;
 294
 295        /* If there's no HEAD value at all, never mind. */
 296        if (!remote_head)
 297                return NULL;
 298
 299        /* If refs/heads/master could be right, it is. */
 300        if (remote_master && !hashcmp(remote_master->old_sha1,
 301                                      remote_head->old_sha1))
 302                return remote_master;
 303
 304        /* Look for another ref that points there */
 305        for (r = mapped_refs; r; r = r->next)
 306                if (r != remote_head &&
 307                    !hashcmp(r->old_sha1, remote_head->old_sha1))
 308                        return r;
 309
 310        /* Nothing is the same */
 311        return NULL;
 312}
 313
 314static struct ref *write_remote_refs(const struct ref *refs,
 315                struct refspec *refspec, const char *reflog)
 316{
 317        struct ref *local_refs = NULL;
 318        struct ref **tail = &local_refs;
 319        struct ref *r;
 320
 321        get_fetch_map(refs, refspec, &tail, 0);
 322        get_fetch_map(refs, tag_refspec, &tail, 0);
 323
 324        for (r = local_refs; r; r = r->next)
 325                add_extra_ref(r->peer_ref->name, r->old_sha1, 0);
 326
 327        pack_refs(PACK_REFS_ALL);
 328        clear_extra_refs();
 329
 330        return local_refs;
 331}
 332
 333int cmd_clone(int argc, const char **argv, const char *prefix)
 334{
 335        int use_local_hardlinks = 1;
 336        int use_separate_remote = 1;
 337        int is_bundle = 0;
 338        struct stat buf;
 339        const char *repo_name, *repo, *work_tree, *git_dir;
 340        char *path, *dir;
 341        const struct ref *refs, *head_points_at, *remote_head, *mapped_refs;
 342        char branch_top[256], key[256], value[256];
 343        struct strbuf reflog_msg;
 344
 345        struct refspec refspec;
 346
 347        junk_pid = getpid();
 348
 349        argc = parse_options(argc, argv, builtin_clone_options,
 350                             builtin_clone_usage, 0);
 351
 352        if (argc == 0)
 353                die("You must specify a repository to clone.");
 354
 355        if (option_no_hardlinks)
 356                use_local_hardlinks = 0;
 357
 358        if (option_bare) {
 359                if (option_origin)
 360                        die("--bare and --origin %s options are incompatible.",
 361                            option_origin);
 362                option_no_checkout = 1;
 363                use_separate_remote = 0;
 364        }
 365
 366        if (!option_origin)
 367                option_origin = "origin";
 368
 369        repo_name = argv[0];
 370
 371        path = get_repo_path(repo_name, &is_bundle);
 372        if (path)
 373                repo = path;
 374        else if (!strchr(repo_name, ':'))
 375                repo = xstrdup(make_absolute_path(repo_name));
 376        else
 377                repo = repo_name;
 378
 379        if (argc == 2)
 380                dir = xstrdup(argv[1]);
 381        else
 382                dir = guess_dir_name(repo_name, is_bundle);
 383
 384        if (!stat(dir, &buf))
 385                die("destination directory '%s' already exists.", dir);
 386
 387        strbuf_init(&reflog_msg, 0);
 388        strbuf_addf(&reflog_msg, "clone: from %s", repo);
 389
 390        if (option_bare)
 391                work_tree = NULL;
 392        else {
 393                work_tree = getenv("GIT_WORK_TREE");
 394                if (work_tree && !stat(work_tree, &buf))
 395                        die("working tree '%s' already exists.", work_tree);
 396        }
 397
 398        if (option_bare || work_tree)
 399                git_dir = xstrdup(dir);
 400        else {
 401                work_tree = dir;
 402                git_dir = xstrdup(mkpath("%s/.git", dir));
 403        }
 404
 405        if (!option_bare) {
 406                junk_work_tree = work_tree;
 407                if (safe_create_leading_directories_const(work_tree) < 0)
 408                        die("could not create leading directories of '%s'",
 409                                        work_tree);
 410                if (mkdir(work_tree, 0755))
 411                        die("could not create work tree dir '%s'.", work_tree);
 412                set_git_work_tree(work_tree);
 413        }
 414        junk_git_dir = git_dir;
 415        atexit(remove_junk);
 416        signal(SIGINT, remove_junk_on_signal);
 417
 418        setenv(CONFIG_ENVIRONMENT, xstrdup(mkpath("%s/config", git_dir)), 1);
 419
 420        if (safe_create_leading_directories_const(git_dir) < 0)
 421                die("could not create leading directories of '%s'", git_dir);
 422        set_git_dir(make_absolute_path(git_dir));
 423
 424        fprintf(stderr, "Initialize %s\n", git_dir);
 425        init_db(option_template, option_quiet ? INIT_DB_QUIET : 0);
 426
 427        /*
 428         * At this point, the config exists, so we do not need the
 429         * environment variable.  We actually need to unset it, too, to
 430         * re-enable parsing of the global configs.
 431         */
 432        unsetenv(CONFIG_ENVIRONMENT);
 433
 434        if (option_reference)
 435                setup_reference(git_dir);
 436
 437        git_config(git_default_config, NULL);
 438
 439        if (option_bare) {
 440                strcpy(branch_top, "refs/heads/");
 441
 442                git_config_set("core.bare", "true");
 443        } else {
 444                snprintf(branch_top, sizeof(branch_top),
 445                         "refs/remotes/%s/", option_origin);
 446
 447                /* Configure the remote */
 448                snprintf(key, sizeof(key), "remote.%s.url", option_origin);
 449                git_config_set(key, repo);
 450
 451                snprintf(key, sizeof(key), "remote.%s.fetch", option_origin);
 452                snprintf(value, sizeof(value),
 453                                "+refs/heads/*:%s*", branch_top);
 454                git_config_set_multivar(key, value, "^$", 0);
 455        }
 456
 457        refspec.force = 0;
 458        refspec.pattern = 1;
 459        refspec.src = "refs/heads/";
 460        refspec.dst = branch_top;
 461
 462        if (path && !is_bundle)
 463                refs = clone_local(path, git_dir);
 464        else {
 465                struct remote *remote = remote_get(argv[0]);
 466                struct transport *transport =
 467                        transport_get(remote, remote->url[0]);
 468
 469                if (!transport->get_refs_list || !transport->fetch)
 470                        die("Don't know how to clone %s", transport->url);
 471
 472                transport_set_option(transport, TRANS_OPT_KEEP, "yes");
 473
 474                if (option_depth)
 475                        transport_set_option(transport, TRANS_OPT_DEPTH,
 476                                             option_depth);
 477
 478                if (option_quiet)
 479                        transport->verbose = -1;
 480
 481                refs = transport_get_remote_refs(transport);
 482                transport_fetch_refs(transport, refs);
 483        }
 484
 485        clear_extra_refs();
 486
 487        mapped_refs = write_remote_refs(refs, &refspec, reflog_msg.buf);
 488
 489        head_points_at = locate_head(refs, mapped_refs, &remote_head);
 490
 491        if (head_points_at) {
 492                /* Local default branch link */
 493                create_symref("HEAD", head_points_at->name, NULL);
 494
 495                if (!option_bare) {
 496                        struct strbuf head_ref;
 497                        const char *head = head_points_at->name;
 498
 499                        if (!prefixcmp(head, "refs/heads/"))
 500                                head += 11;
 501
 502                        /* Set up the initial local branch */
 503
 504                        /* Local branch initial value */
 505                        update_ref(reflog_msg.buf, "HEAD",
 506                                   head_points_at->old_sha1,
 507                                   NULL, 0, DIE_ON_ERR);
 508
 509                        strbuf_init(&head_ref, 0);
 510                        strbuf_addstr(&head_ref, branch_top);
 511                        strbuf_addstr(&head_ref, "HEAD");
 512
 513                        /* Remote branch link */
 514                        create_symref(head_ref.buf,
 515                                      head_points_at->peer_ref->name,
 516                                      reflog_msg.buf);
 517
 518                        snprintf(key, sizeof(key), "branch.%s.remote", head);
 519                        git_config_set(key, option_origin);
 520                        snprintf(key, sizeof(key), "branch.%s.merge", head);
 521                        git_config_set(key, head_points_at->name);
 522                }
 523        } else if (remote_head) {
 524                /* Source had detached HEAD pointing somewhere. */
 525                if (!option_bare)
 526                        update_ref(reflog_msg.buf, "HEAD",
 527                                   remote_head->old_sha1,
 528                                   NULL, REF_NODEREF, DIE_ON_ERR);
 529        } else {
 530                /* Nothing to checkout out */
 531                if (!option_no_checkout)
 532                        warning("remote HEAD refers to nonexistent ref, "
 533                                "unable to checkout.\n");
 534                option_no_checkout = 1;
 535        }
 536
 537        if (!option_no_checkout) {
 538                struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
 539                struct unpack_trees_options opts;
 540                struct tree *tree;
 541                struct tree_desc t;
 542                int fd;
 543
 544                /* We need to be in the new work tree for the checkout */
 545                setup_work_tree();
 546
 547                fd = hold_locked_index(lock_file, 1);
 548
 549                memset(&opts, 0, sizeof opts);
 550                opts.update = 1;
 551                opts.merge = 1;
 552                opts.fn = oneway_merge;
 553                opts.verbose_update = !option_quiet;
 554                opts.src_index = &the_index;
 555                opts.dst_index = &the_index;
 556
 557                tree = parse_tree_indirect(remote_head->old_sha1);
 558                parse_tree(tree);
 559                init_tree_desc(&t, tree->buffer, tree->size);
 560                unpack_trees(1, &t, &opts);
 561
 562                if (write_cache(fd, active_cache, active_nr) ||
 563                    commit_locked_index(lock_file))
 564                        die("unable to write new index file");
 565        }
 566
 567        strbuf_release(&reflog_msg);
 568        junk_pid = 0;
 569        return 0;
 570}