builtin / init-db.con commit transport-helper: enforce atomic in push_refs_with_push (3bca1e7)
   1/*
   2 * GIT - The information manager from hell
   3 *
   4 * Copyright (C) Linus Torvalds, 2005
   5 */
   6#include "cache.h"
   7#include "config.h"
   8#include "refs.h"
   9#include "builtin.h"
  10#include "exec-cmd.h"
  11#include "parse-options.h"
  12
  13#ifndef DEFAULT_GIT_TEMPLATE_DIR
  14#define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
  15#endif
  16
  17#ifdef NO_TRUSTABLE_FILEMODE
  18#define TEST_FILEMODE 0
  19#else
  20#define TEST_FILEMODE 1
  21#endif
  22
  23static int init_is_bare_repository = 0;
  24static int init_shared_repository = -1;
  25static const char *init_db_template_dir;
  26
  27static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
  28                             DIR *dir)
  29{
  30        size_t path_baselen = path->len;
  31        size_t template_baselen = template_path->len;
  32        struct dirent *de;
  33
  34        /* Note: if ".git/hooks" file exists in the repository being
  35         * re-initialized, /etc/core-git/templates/hooks/update would
  36         * cause "git init" to fail here.  I think this is sane but
  37         * it means that the set of templates we ship by default, along
  38         * with the way the namespace under .git/ is organized, should
  39         * be really carefully chosen.
  40         */
  41        safe_create_dir(path->buf, 1);
  42        while ((de = readdir(dir)) != NULL) {
  43                struct stat st_git, st_template;
  44                int exists = 0;
  45
  46                strbuf_setlen(path, path_baselen);
  47                strbuf_setlen(template_path, template_baselen);
  48
  49                if (de->d_name[0] == '.')
  50                        continue;
  51                strbuf_addstr(path, de->d_name);
  52                strbuf_addstr(template_path, de->d_name);
  53                if (lstat(path->buf, &st_git)) {
  54                        if (errno != ENOENT)
  55                                die_errno(_("cannot stat '%s'"), path->buf);
  56                }
  57                else
  58                        exists = 1;
  59
  60                if (lstat(template_path->buf, &st_template))
  61                        die_errno(_("cannot stat template '%s'"), template_path->buf);
  62
  63                if (S_ISDIR(st_template.st_mode)) {
  64                        DIR *subdir = opendir(template_path->buf);
  65                        if (!subdir)
  66                                die_errno(_("cannot opendir '%s'"), template_path->buf);
  67                        strbuf_addch(path, '/');
  68                        strbuf_addch(template_path, '/');
  69                        copy_templates_1(path, template_path, subdir);
  70                        closedir(subdir);
  71                }
  72                else if (exists)
  73                        continue;
  74                else if (S_ISLNK(st_template.st_mode)) {
  75                        struct strbuf lnk = STRBUF_INIT;
  76                        if (strbuf_readlink(&lnk, template_path->buf,
  77                                            st_template.st_size) < 0)
  78                                die_errno(_("cannot readlink '%s'"), template_path->buf);
  79                        if (symlink(lnk.buf, path->buf))
  80                                die_errno(_("cannot symlink '%s' '%s'"),
  81                                          lnk.buf, path->buf);
  82                        strbuf_release(&lnk);
  83                }
  84                else if (S_ISREG(st_template.st_mode)) {
  85                        if (copy_file(path->buf, template_path->buf, st_template.st_mode))
  86                                die_errno(_("cannot copy '%s' to '%s'"),
  87                                          template_path->buf, path->buf);
  88                }
  89                else
  90                        error(_("ignoring template %s"), template_path->buf);
  91        }
  92}
  93
  94static void copy_templates(const char *template_dir)
  95{
  96        struct strbuf path = STRBUF_INIT;
  97        struct strbuf template_path = STRBUF_INIT;
  98        size_t template_len;
  99        struct repository_format template_format = REPOSITORY_FORMAT_INIT;
 100        struct strbuf err = STRBUF_INIT;
 101        DIR *dir;
 102        char *to_free = NULL;
 103
 104        if (!template_dir)
 105                template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
 106        if (!template_dir)
 107                template_dir = init_db_template_dir;
 108        if (!template_dir)
 109                template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
 110        if (!template_dir[0]) {
 111                free(to_free);
 112                return;
 113        }
 114
 115        strbuf_addstr(&template_path, template_dir);
 116        strbuf_complete(&template_path, '/');
 117        template_len = template_path.len;
 118
 119        dir = opendir(template_path.buf);
 120        if (!dir) {
 121                warning(_("templates not found in %s"), template_dir);
 122                goto free_return;
 123        }
 124
 125        /* Make sure that template is from the correct vintage */
 126        strbuf_addstr(&template_path, "config");
 127        read_repository_format(&template_format, template_path.buf);
 128        strbuf_setlen(&template_path, template_len);
 129
 130        /*
 131         * No mention of version at all is OK, but anything else should be
 132         * verified.
 133         */
 134        if (template_format.version >= 0 &&
 135            verify_repository_format(&template_format, &err) < 0) {
 136                warning(_("not copying templates from '%s': %s"),
 137                          template_dir, err.buf);
 138                strbuf_release(&err);
 139                goto close_free_return;
 140        }
 141
 142        strbuf_addstr(&path, get_git_common_dir());
 143        strbuf_complete(&path, '/');
 144        copy_templates_1(&path, &template_path, dir);
 145close_free_return:
 146        closedir(dir);
 147free_return:
 148        free(to_free);
 149        strbuf_release(&path);
 150        strbuf_release(&template_path);
 151        clear_repository_format(&template_format);
 152}
 153
 154static int git_init_db_config(const char *k, const char *v, void *cb)
 155{
 156        if (!strcmp(k, "init.templatedir"))
 157                return git_config_pathname(&init_db_template_dir, k, v);
 158
 159        if (starts_with(k, "core."))
 160                return platform_core_config(k, v, cb);
 161
 162        return 0;
 163}
 164
 165/*
 166 * If the git_dir is not directly inside the working tree, then git will not
 167 * find it by default, and we need to set the worktree explicitly.
 168 */
 169static int needs_work_tree_config(const char *git_dir, const char *work_tree)
 170{
 171        if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
 172                return 0;
 173        if (skip_prefix(git_dir, work_tree, &git_dir) &&
 174            !strcmp(git_dir, "/.git"))
 175                return 0;
 176        return 1;
 177}
 178
 179static int create_default_files(const char *template_path,
 180                                const char *original_git_dir)
 181{
 182        struct stat st1;
 183        struct strbuf buf = STRBUF_INIT;
 184        char *path;
 185        char repo_version_string[10];
 186        char junk[2];
 187        int reinit;
 188        int filemode;
 189        struct strbuf err = STRBUF_INIT;
 190
 191        /* Just look for `init.templatedir` */
 192        init_db_template_dir = NULL; /* re-set in case it was set before */
 193        git_config(git_init_db_config, NULL);
 194
 195        /*
 196         * First copy the templates -- we might have the default
 197         * config file there, in which case we would want to read
 198         * from it after installing.
 199         *
 200         * Before reading that config, we also need to clear out any cached
 201         * values (since we've just potentially changed what's available on
 202         * disk).
 203         */
 204        copy_templates(template_path);
 205        git_config_clear();
 206        reset_shared_repository();
 207        git_config(git_default_config, NULL);
 208
 209        /*
 210         * We must make sure command-line options continue to override any
 211         * values we might have just re-read from the config.
 212         */
 213        is_bare_repository_cfg = init_is_bare_repository;
 214        if (init_shared_repository != -1)
 215                set_shared_repository(init_shared_repository);
 216
 217        /*
 218         * We would have created the above under user's umask -- under
 219         * shared-repository settings, we would need to fix them up.
 220         */
 221        if (get_shared_repository()) {
 222                adjust_shared_perm(get_git_dir());
 223        }
 224
 225        /*
 226         * We need to create a "refs" dir in any case so that older
 227         * versions of git can tell that this is a repository.
 228         */
 229        safe_create_dir(git_path("refs"), 1);
 230        adjust_shared_perm(git_path("refs"));
 231
 232        if (refs_init_db(&err))
 233                die("failed to set up refs db: %s", err.buf);
 234
 235        /*
 236         * Create the default symlink from ".git/HEAD" to the "master"
 237         * branch, if it does not exist yet.
 238         */
 239        path = git_path_buf(&buf, "HEAD");
 240        reinit = (!access(path, R_OK)
 241                  || readlink(path, junk, sizeof(junk)-1) != -1);
 242        if (!reinit) {
 243                if (create_symref("HEAD", "refs/heads/master", NULL) < 0)
 244                        exit(1);
 245        }
 246
 247        /* This forces creation of new config file */
 248        xsnprintf(repo_version_string, sizeof(repo_version_string),
 249                  "%d", GIT_REPO_VERSION);
 250        git_config_set("core.repositoryformatversion", repo_version_string);
 251
 252        /* Check filemode trustability */
 253        path = git_path_buf(&buf, "config");
 254        filemode = TEST_FILEMODE;
 255        if (TEST_FILEMODE && !lstat(path, &st1)) {
 256                struct stat st2;
 257                filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
 258                                !lstat(path, &st2) &&
 259                                st1.st_mode != st2.st_mode &&
 260                                !chmod(path, st1.st_mode));
 261                if (filemode && !reinit && (st1.st_mode & S_IXUSR))
 262                        filemode = 0;
 263        }
 264        git_config_set("core.filemode", filemode ? "true" : "false");
 265
 266        if (is_bare_repository())
 267                git_config_set("core.bare", "true");
 268        else {
 269                const char *work_tree = get_git_work_tree();
 270                git_config_set("core.bare", "false");
 271                /* allow template config file to override the default */
 272                if (log_all_ref_updates == LOG_REFS_UNSET)
 273                        git_config_set("core.logallrefupdates", "true");
 274                if (needs_work_tree_config(original_git_dir, work_tree))
 275                        git_config_set("core.worktree", work_tree);
 276        }
 277
 278        if (!reinit) {
 279                /* Check if symlink is supported in the work tree */
 280                path = git_path_buf(&buf, "tXXXXXX");
 281                if (!close(xmkstemp(path)) &&
 282                    !unlink(path) &&
 283                    !symlink("testing", path) &&
 284                    !lstat(path, &st1) &&
 285                    S_ISLNK(st1.st_mode))
 286                        unlink(path); /* good */
 287                else
 288                        git_config_set("core.symlinks", "false");
 289
 290                /* Check if the filesystem is case-insensitive */
 291                path = git_path_buf(&buf, "CoNfIg");
 292                if (!access(path, F_OK))
 293                        git_config_set("core.ignorecase", "true");
 294                probe_utf8_pathname_composition();
 295        }
 296
 297        strbuf_release(&buf);
 298        return reinit;
 299}
 300
 301static void create_object_directory(void)
 302{
 303        struct strbuf path = STRBUF_INIT;
 304        size_t baselen;
 305
 306        strbuf_addstr(&path, get_object_directory());
 307        baselen = path.len;
 308
 309        safe_create_dir(path.buf, 1);
 310
 311        strbuf_setlen(&path, baselen);
 312        strbuf_addstr(&path, "/pack");
 313        safe_create_dir(path.buf, 1);
 314
 315        strbuf_setlen(&path, baselen);
 316        strbuf_addstr(&path, "/info");
 317        safe_create_dir(path.buf, 1);
 318
 319        strbuf_release(&path);
 320}
 321
 322static void separate_git_dir(const char *git_dir, const char *git_link)
 323{
 324        struct stat st;
 325
 326        if (!stat(git_link, &st)) {
 327                const char *src;
 328
 329                if (S_ISREG(st.st_mode))
 330                        src = read_gitfile(git_link);
 331                else if (S_ISDIR(st.st_mode))
 332                        src = git_link;
 333                else
 334                        die(_("unable to handle file type %d"), (int)st.st_mode);
 335
 336                if (rename(src, git_dir))
 337                        die_errno(_("unable to move %s to %s"), src, git_dir);
 338        }
 339
 340        write_file(git_link, "gitdir: %s", git_dir);
 341}
 342
 343int init_db(const char *git_dir, const char *real_git_dir,
 344            const char *template_dir, unsigned int flags)
 345{
 346        int reinit;
 347        int exist_ok = flags & INIT_DB_EXIST_OK;
 348        char *original_git_dir = real_pathdup(git_dir, 1);
 349
 350        if (real_git_dir) {
 351                struct stat st;
 352
 353                if (!exist_ok && !stat(git_dir, &st))
 354                        die(_("%s already exists"), git_dir);
 355
 356                if (!exist_ok && !stat(real_git_dir, &st))
 357                        die(_("%s already exists"), real_git_dir);
 358
 359                set_git_dir(real_path(real_git_dir));
 360                git_dir = get_git_dir();
 361                separate_git_dir(git_dir, original_git_dir);
 362        }
 363        else {
 364                set_git_dir(real_path(git_dir));
 365                git_dir = get_git_dir();
 366        }
 367        startup_info->have_repository = 1;
 368
 369        /* Just look for `core.hidedotfiles` */
 370        git_config(git_init_db_config, NULL);
 371
 372        safe_create_dir(git_dir, 0);
 373
 374        init_is_bare_repository = is_bare_repository();
 375
 376        /* Check to see if the repository version is right.
 377         * Note that a newly created repository does not have
 378         * config file, so this will not fail.  What we are catching
 379         * is an attempt to reinitialize new repository with an old tool.
 380         */
 381        check_repository_format();
 382
 383        reinit = create_default_files(template_dir, original_git_dir);
 384
 385        create_object_directory();
 386
 387        if (get_shared_repository()) {
 388                char buf[10];
 389                /* We do not spell "group" and such, so that
 390                 * the configuration can be read by older version
 391                 * of git. Note, we use octal numbers for new share modes,
 392                 * and compatibility values for PERM_GROUP and
 393                 * PERM_EVERYBODY.
 394                 */
 395                if (get_shared_repository() < 0)
 396                        /* force to the mode value */
 397                        xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
 398                else if (get_shared_repository() == PERM_GROUP)
 399                        xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
 400                else if (get_shared_repository() == PERM_EVERYBODY)
 401                        xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
 402                else
 403                        BUG("invalid value for shared_repository");
 404                git_config_set("core.sharedrepository", buf);
 405                git_config_set("receive.denyNonFastforwards", "true");
 406        }
 407
 408        if (!(flags & INIT_DB_QUIET)) {
 409                int len = strlen(git_dir);
 410
 411                if (reinit)
 412                        printf(get_shared_repository()
 413                               ? _("Reinitialized existing shared Git repository in %s%s\n")
 414                               : _("Reinitialized existing Git repository in %s%s\n"),
 415                               git_dir, len && git_dir[len-1] != '/' ? "/" : "");
 416                else
 417                        printf(get_shared_repository()
 418                               ? _("Initialized empty shared Git repository in %s%s\n")
 419                               : _("Initialized empty Git repository in %s%s\n"),
 420                               git_dir, len && git_dir[len-1] != '/' ? "/" : "");
 421        }
 422
 423        free(original_git_dir);
 424        return 0;
 425}
 426
 427static int guess_repository_type(const char *git_dir)
 428{
 429        const char *slash;
 430        char *cwd;
 431        int cwd_is_git_dir;
 432
 433        /*
 434         * "GIT_DIR=. git init" is always bare.
 435         * "GIT_DIR=`pwd` git init" too.
 436         */
 437        if (!strcmp(".", git_dir))
 438                return 1;
 439        cwd = xgetcwd();
 440        cwd_is_git_dir = !strcmp(git_dir, cwd);
 441        free(cwd);
 442        if (cwd_is_git_dir)
 443                return 1;
 444        /*
 445         * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
 446         */
 447        if (!strcmp(git_dir, ".git"))
 448                return 0;
 449        slash = strrchr(git_dir, '/');
 450        if (slash && !strcmp(slash, "/.git"))
 451                return 0;
 452
 453        /*
 454         * Otherwise it is often bare.  At this point
 455         * we are just guessing.
 456         */
 457        return 1;
 458}
 459
 460static int shared_callback(const struct option *opt, const char *arg, int unset)
 461{
 462        BUG_ON_OPT_NEG(unset);
 463        *((int *) opt->value) = (arg) ? git_config_perm("arg", arg) : PERM_GROUP;
 464        return 0;
 465}
 466
 467static const char *const init_db_usage[] = {
 468        N_("git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"),
 469        NULL
 470};
 471
 472/*
 473 * If you want to, you can share the DB area with any number of branches.
 474 * That has advantages: you can save space by sharing all the SHA1 objects.
 475 * On the other hand, it might just make lookup slower and messier. You
 476 * be the judge.  The default case is to have one DB per managed directory.
 477 */
 478int cmd_init_db(int argc, const char **argv, const char *prefix)
 479{
 480        const char *git_dir;
 481        const char *real_git_dir = NULL;
 482        const char *work_tree;
 483        const char *template_dir = NULL;
 484        unsigned int flags = 0;
 485        const struct option init_db_options[] = {
 486                OPT_STRING(0, "template", &template_dir, N_("template-directory"),
 487                                N_("directory from which templates will be used")),
 488                OPT_SET_INT(0, "bare", &is_bare_repository_cfg,
 489                                N_("create a bare repository"), 1),
 490                { OPTION_CALLBACK, 0, "shared", &init_shared_repository,
 491                        N_("permissions"),
 492                        N_("specify that the git repository is to be shared amongst several users"),
 493                        PARSE_OPT_OPTARG | PARSE_OPT_NONEG, shared_callback, 0},
 494                OPT_BIT('q', "quiet", &flags, N_("be quiet"), INIT_DB_QUIET),
 495                OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
 496                           N_("separate git dir from working tree")),
 497                OPT_END()
 498        };
 499
 500        argc = parse_options(argc, argv, prefix, init_db_options, init_db_usage, 0);
 501
 502        if (real_git_dir && !is_absolute_path(real_git_dir))
 503                real_git_dir = real_pathdup(real_git_dir, 1);
 504
 505        if (argc == 1) {
 506                int mkdir_tried = 0;
 507        retry:
 508                if (chdir(argv[0]) < 0) {
 509                        if (!mkdir_tried) {
 510                                int saved;
 511                                /*
 512                                 * At this point we haven't read any configuration,
 513                                 * and we know shared_repository should always be 0;
 514                                 * but just in case we play safe.
 515                                 */
 516                                saved = get_shared_repository();
 517                                set_shared_repository(0);
 518                                switch (safe_create_leading_directories_const(argv[0])) {
 519                                case SCLD_OK:
 520                                case SCLD_PERMS:
 521                                        break;
 522                                case SCLD_EXISTS:
 523                                        errno = EEXIST;
 524                                        /* fallthru */
 525                                default:
 526                                        die_errno(_("cannot mkdir %s"), argv[0]);
 527                                        break;
 528                                }
 529                                set_shared_repository(saved);
 530                                if (mkdir(argv[0], 0777) < 0)
 531                                        die_errno(_("cannot mkdir %s"), argv[0]);
 532                                mkdir_tried = 1;
 533                                goto retry;
 534                        }
 535                        die_errno(_("cannot chdir to %s"), argv[0]);
 536                }
 537        } else if (0 < argc) {
 538                usage(init_db_usage[0]);
 539        }
 540        if (is_bare_repository_cfg == 1) {
 541                char *cwd = xgetcwd();
 542                setenv(GIT_DIR_ENVIRONMENT, cwd, argc > 0);
 543                free(cwd);
 544        }
 545
 546        if (init_shared_repository != -1)
 547                set_shared_repository(init_shared_repository);
 548
 549        /*
 550         * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
 551         * without --bare.  Catch the error early.
 552         */
 553        git_dir = xstrdup_or_null(getenv(GIT_DIR_ENVIRONMENT));
 554        work_tree = xstrdup_or_null(getenv(GIT_WORK_TREE_ENVIRONMENT));
 555        if ((!git_dir || is_bare_repository_cfg == 1) && work_tree)
 556                die(_("%s (or --work-tree=<directory>) not allowed without "
 557                          "specifying %s (or --git-dir=<directory>)"),
 558                    GIT_WORK_TREE_ENVIRONMENT,
 559                    GIT_DIR_ENVIRONMENT);
 560
 561        /*
 562         * Set up the default .git directory contents
 563         */
 564        if (!git_dir)
 565                git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
 566
 567        if (is_bare_repository_cfg < 0)
 568                is_bare_repository_cfg = guess_repository_type(git_dir);
 569
 570        if (!is_bare_repository_cfg) {
 571                const char *git_dir_parent = strrchr(git_dir, '/');
 572                if (git_dir_parent) {
 573                        char *rel = xstrndup(git_dir, git_dir_parent - git_dir);
 574                        git_work_tree_cfg = real_pathdup(rel, 1);
 575                        free(rel);
 576                }
 577                if (!git_work_tree_cfg)
 578                        git_work_tree_cfg = xgetcwd();
 579                if (work_tree)
 580                        set_git_work_tree(work_tree);
 581                else
 582                        set_git_work_tree(git_work_tree_cfg);
 583                if (access(get_git_work_tree(), X_OK))
 584                        die_errno (_("Cannot access work tree '%s'"),
 585                                   get_git_work_tree());
 586        }
 587        else {
 588                if (work_tree)
 589                        set_git_work_tree(work_tree);
 590        }
 591
 592        UNLEAK(real_git_dir);
 593        UNLEAK(git_dir);
 594        UNLEAK(work_tree);
 595
 596        flags |= INIT_DB_EXIST_OK;
 597        return init_db(git_dir, real_git_dir, template_dir, flags);
 598}