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