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