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