Merge branch 'dl/test-must-fail-fixes-5'
[git/raj.git] / builtin / init-db.c
blobcee64823cbb500a8df0f19f486a2d3593492b1e6
1 /*
2 * GIT - The information manager from hell
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"
13 #ifndef DEFAULT_GIT_TEMPLATE_DIR
14 #define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
15 #endif
17 #ifdef NO_TRUSTABLE_FILEMODE
18 #define TEST_FILEMODE 0
19 #else
20 #define TEST_FILEMODE 1
21 #endif
23 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
25 static int init_is_bare_repository = 0;
26 static int init_shared_repository = -1;
27 static const char *init_db_template_dir;
29 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
30 DIR *dir)
32 size_t path_baselen = path->len;
33 size_t template_baselen = template_path->len;
34 struct dirent *de;
36 /* Note: if ".git/hooks" file exists in the repository being
37 * re-initialized, /etc/core-git/templates/hooks/update would
38 * cause "git init" to fail here. I think this is sane but
39 * it means that the set of templates we ship by default, along
40 * with the way the namespace under .git/ is organized, should
41 * be really carefully chosen.
43 safe_create_dir(path->buf, 1);
44 while ((de = readdir(dir)) != NULL) {
45 struct stat st_git, st_template;
46 int exists = 0;
48 strbuf_setlen(path, path_baselen);
49 strbuf_setlen(template_path, template_baselen);
51 if (de->d_name[0] == '.')
52 continue;
53 strbuf_addstr(path, de->d_name);
54 strbuf_addstr(template_path, de->d_name);
55 if (lstat(path->buf, &st_git)) {
56 if (errno != ENOENT)
57 die_errno(_("cannot stat '%s'"), path->buf);
59 else
60 exists = 1;
62 if (lstat(template_path->buf, &st_template))
63 die_errno(_("cannot stat template '%s'"), template_path->buf);
65 if (S_ISDIR(st_template.st_mode)) {
66 DIR *subdir = opendir(template_path->buf);
67 if (!subdir)
68 die_errno(_("cannot opendir '%s'"), template_path->buf);
69 strbuf_addch(path, '/');
70 strbuf_addch(template_path, '/');
71 copy_templates_1(path, template_path, subdir);
72 closedir(subdir);
74 else if (exists)
75 continue;
76 else if (S_ISLNK(st_template.st_mode)) {
77 struct strbuf lnk = STRBUF_INIT;
78 if (strbuf_readlink(&lnk, template_path->buf,
79 st_template.st_size) < 0)
80 die_errno(_("cannot readlink '%s'"), template_path->buf);
81 if (symlink(lnk.buf, path->buf))
82 die_errno(_("cannot symlink '%s' '%s'"),
83 lnk.buf, path->buf);
84 strbuf_release(&lnk);
86 else if (S_ISREG(st_template.st_mode)) {
87 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
88 die_errno(_("cannot copy '%s' to '%s'"),
89 template_path->buf, path->buf);
91 else
92 error(_("ignoring template %s"), template_path->buf);
96 static void copy_templates(const char *template_dir)
98 struct strbuf path = STRBUF_INIT;
99 struct strbuf template_path = STRBUF_INIT;
100 size_t template_len;
101 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
102 struct strbuf err = STRBUF_INIT;
103 DIR *dir;
104 char *to_free = NULL;
106 if (!template_dir)
107 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
108 if (!template_dir)
109 template_dir = init_db_template_dir;
110 if (!template_dir)
111 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
112 if (!template_dir[0]) {
113 free(to_free);
114 return;
117 strbuf_addstr(&template_path, template_dir);
118 strbuf_complete(&template_path, '/');
119 template_len = template_path.len;
121 dir = opendir(template_path.buf);
122 if (!dir) {
123 warning(_("templates not found in %s"), template_dir);
124 goto free_return;
127 /* Make sure that template is from the correct vintage */
128 strbuf_addstr(&template_path, "config");
129 read_repository_format(&template_format, template_path.buf);
130 strbuf_setlen(&template_path, template_len);
133 * No mention of version at all is OK, but anything else should be
134 * verified.
136 if (template_format.version >= 0 &&
137 verify_repository_format(&template_format, &err) < 0) {
138 warning(_("not copying templates from '%s': %s"),
139 template_dir, err.buf);
140 strbuf_release(&err);
141 goto close_free_return;
144 strbuf_addstr(&path, get_git_common_dir());
145 strbuf_complete(&path, '/');
146 copy_templates_1(&path, &template_path, dir);
147 close_free_return:
148 closedir(dir);
149 free_return:
150 free(to_free);
151 strbuf_release(&path);
152 strbuf_release(&template_path);
153 clear_repository_format(&template_format);
156 static int git_init_db_config(const char *k, const char *v, void *cb)
158 if (!strcmp(k, "init.templatedir"))
159 return git_config_pathname(&init_db_template_dir, k, v);
161 if (starts_with(k, "core."))
162 return platform_core_config(k, v, cb);
164 return 0;
168 * If the git_dir is not directly inside the working tree, then git will not
169 * find it by default, and we need to set the worktree explicitly.
171 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
173 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
174 return 0;
175 if (skip_prefix(git_dir, work_tree, &git_dir) &&
176 !strcmp(git_dir, "/.git"))
177 return 0;
178 return 1;
181 void initialize_repository_version(int hash_algo)
183 char repo_version_string[10];
184 int repo_version = GIT_REPO_VERSION;
186 #ifndef ENABLE_SHA256
187 if (hash_algo != GIT_HASH_SHA1)
188 die(_("The hash algorithm %s is not supported in this build."), hash_algos[hash_algo].name);
189 #endif
191 if (hash_algo != GIT_HASH_SHA1)
192 repo_version = GIT_REPO_VERSION_READ;
194 /* This forces creation of new config file */
195 xsnprintf(repo_version_string, sizeof(repo_version_string),
196 "%d", repo_version);
197 git_config_set("core.repositoryformatversion", repo_version_string);
199 if (hash_algo != GIT_HASH_SHA1)
200 git_config_set("extensions.objectformat",
201 hash_algos[hash_algo].name);
204 static int create_default_files(const char *template_path,
205 const char *original_git_dir,
206 const char *initial_branch,
207 const struct repository_format *fmt)
209 struct stat st1;
210 struct strbuf buf = STRBUF_INIT;
211 char *path;
212 char junk[2];
213 int reinit;
214 int filemode;
215 struct strbuf err = STRBUF_INIT;
217 /* Just look for `init.templatedir` */
218 init_db_template_dir = NULL; /* re-set in case it was set before */
219 git_config(git_init_db_config, NULL);
222 * First copy the templates -- we might have the default
223 * config file there, in which case we would want to read
224 * from it after installing.
226 * Before reading that config, we also need to clear out any cached
227 * values (since we've just potentially changed what's available on
228 * disk).
230 copy_templates(template_path);
231 git_config_clear();
232 reset_shared_repository();
233 git_config(git_default_config, NULL);
236 * We must make sure command-line options continue to override any
237 * values we might have just re-read from the config.
239 is_bare_repository_cfg = init_is_bare_repository;
240 if (init_shared_repository != -1)
241 set_shared_repository(init_shared_repository);
244 * We would have created the above under user's umask -- under
245 * shared-repository settings, we would need to fix them up.
247 if (get_shared_repository()) {
248 adjust_shared_perm(get_git_dir());
252 * We need to create a "refs" dir in any case so that older
253 * versions of git can tell that this is a repository.
255 safe_create_dir(git_path("refs"), 1);
256 adjust_shared_perm(git_path("refs"));
258 if (refs_init_db(&err))
259 die("failed to set up refs db: %s", err.buf);
262 * Point the HEAD symref to the initial branch with if HEAD does
263 * not yet exist.
265 path = git_path_buf(&buf, "HEAD");
266 reinit = (!access(path, R_OK)
267 || readlink(path, junk, sizeof(junk)-1) != -1);
268 if (!reinit) {
269 char *ref;
271 if (!initial_branch)
272 initial_branch = git_default_branch_name();
274 ref = xstrfmt("refs/heads/%s", initial_branch);
275 if (check_refname_format(ref, 0) < 0)
276 die(_("invalid initial branch name: '%s'"),
277 initial_branch);
279 if (create_symref("HEAD", ref, NULL) < 0)
280 exit(1);
281 free(ref);
284 initialize_repository_version(fmt->hash_algo);
286 /* Check filemode trustability */
287 path = git_path_buf(&buf, "config");
288 filemode = TEST_FILEMODE;
289 if (TEST_FILEMODE && !lstat(path, &st1)) {
290 struct stat st2;
291 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
292 !lstat(path, &st2) &&
293 st1.st_mode != st2.st_mode &&
294 !chmod(path, st1.st_mode));
295 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
296 filemode = 0;
298 git_config_set("core.filemode", filemode ? "true" : "false");
300 if (is_bare_repository())
301 git_config_set("core.bare", "true");
302 else {
303 const char *work_tree = get_git_work_tree();
304 git_config_set("core.bare", "false");
305 /* allow template config file to override the default */
306 if (log_all_ref_updates == LOG_REFS_UNSET)
307 git_config_set("core.logallrefupdates", "true");
308 if (needs_work_tree_config(original_git_dir, work_tree))
309 git_config_set("core.worktree", work_tree);
312 if (!reinit) {
313 /* Check if symlink is supported in the work tree */
314 path = git_path_buf(&buf, "tXXXXXX");
315 if (!close(xmkstemp(path)) &&
316 !unlink(path) &&
317 !symlink("testing", path) &&
318 !lstat(path, &st1) &&
319 S_ISLNK(st1.st_mode))
320 unlink(path); /* good */
321 else
322 git_config_set("core.symlinks", "false");
324 /* Check if the filesystem is case-insensitive */
325 path = git_path_buf(&buf, "CoNfIg");
326 if (!access(path, F_OK))
327 git_config_set("core.ignorecase", "true");
328 probe_utf8_pathname_composition();
331 strbuf_release(&buf);
332 return reinit;
335 static void create_object_directory(void)
337 struct strbuf path = STRBUF_INIT;
338 size_t baselen;
340 strbuf_addstr(&path, get_object_directory());
341 baselen = path.len;
343 safe_create_dir(path.buf, 1);
345 strbuf_setlen(&path, baselen);
346 strbuf_addstr(&path, "/pack");
347 safe_create_dir(path.buf, 1);
349 strbuf_setlen(&path, baselen);
350 strbuf_addstr(&path, "/info");
351 safe_create_dir(path.buf, 1);
353 strbuf_release(&path);
356 static void separate_git_dir(const char *git_dir, const char *git_link)
358 struct stat st;
360 if (!stat(git_link, &st)) {
361 const char *src;
363 if (S_ISREG(st.st_mode))
364 src = read_gitfile(git_link);
365 else if (S_ISDIR(st.st_mode))
366 src = git_link;
367 else
368 die(_("unable to handle file type %d"), (int)st.st_mode);
370 if (rename(src, git_dir))
371 die_errno(_("unable to move %s to %s"), src, git_dir);
374 write_file(git_link, "gitdir: %s", git_dir);
377 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
379 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
381 * If we already have an initialized repo, don't allow the user to
382 * specify a different algorithm, as that could cause corruption.
383 * Otherwise, if the user has specified one on the command line, use it.
385 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
386 die(_("attempt to reinitialize repository with different hash"));
387 else if (hash != GIT_HASH_UNKNOWN)
388 repo_fmt->hash_algo = hash;
389 else if (env) {
390 int env_algo = hash_algo_by_name(env);
391 if (env_algo == GIT_HASH_UNKNOWN)
392 die(_("unknown hash algorithm '%s'"), env);
393 repo_fmt->hash_algo = env_algo;
397 int init_db(const char *git_dir, const char *real_git_dir,
398 const char *template_dir, int hash, const char *initial_branch,
399 unsigned int flags)
401 int reinit;
402 int exist_ok = flags & INIT_DB_EXIST_OK;
403 char *original_git_dir = real_pathdup(git_dir, 1);
404 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
406 if (real_git_dir) {
407 struct stat st;
409 if (!exist_ok && !stat(git_dir, &st))
410 die(_("%s already exists"), git_dir);
412 if (!exist_ok && !stat(real_git_dir, &st))
413 die(_("%s already exists"), real_git_dir);
415 set_git_dir(real_git_dir, 1);
416 git_dir = get_git_dir();
417 separate_git_dir(git_dir, original_git_dir);
419 else {
420 set_git_dir(git_dir, 1);
421 git_dir = get_git_dir();
423 startup_info->have_repository = 1;
425 /* Just look for `core.hidedotfiles` */
426 git_config(git_init_db_config, NULL);
428 safe_create_dir(git_dir, 0);
430 init_is_bare_repository = is_bare_repository();
432 /* Check to see if the repository version is right.
433 * Note that a newly created repository does not have
434 * config file, so this will not fail. What we are catching
435 * is an attempt to reinitialize new repository with an old tool.
437 check_repository_format(&repo_fmt);
439 validate_hash_algorithm(&repo_fmt, hash);
441 reinit = create_default_files(template_dir, original_git_dir,
442 initial_branch, &repo_fmt);
443 if (reinit && initial_branch)
444 warning(_("re-init: ignored --initial-branch=%s"),
445 initial_branch);
447 create_object_directory();
449 if (get_shared_repository()) {
450 char buf[10];
451 /* We do not spell "group" and such, so that
452 * the configuration can be read by older version
453 * of git. Note, we use octal numbers for new share modes,
454 * and compatibility values for PERM_GROUP and
455 * PERM_EVERYBODY.
457 if (get_shared_repository() < 0)
458 /* force to the mode value */
459 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
460 else if (get_shared_repository() == PERM_GROUP)
461 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
462 else if (get_shared_repository() == PERM_EVERYBODY)
463 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
464 else
465 BUG("invalid value for shared_repository");
466 git_config_set("core.sharedrepository", buf);
467 git_config_set("receive.denyNonFastforwards", "true");
470 if (!(flags & INIT_DB_QUIET)) {
471 int len = strlen(git_dir);
473 if (reinit)
474 printf(get_shared_repository()
475 ? _("Reinitialized existing shared Git repository in %s%s\n")
476 : _("Reinitialized existing Git repository in %s%s\n"),
477 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
478 else
479 printf(get_shared_repository()
480 ? _("Initialized empty shared Git repository in %s%s\n")
481 : _("Initialized empty Git repository in %s%s\n"),
482 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
485 free(original_git_dir);
486 return 0;
489 static int guess_repository_type(const char *git_dir)
491 const char *slash;
492 char *cwd;
493 int cwd_is_git_dir;
496 * "GIT_DIR=. git init" is always bare.
497 * "GIT_DIR=`pwd` git init" too.
499 if (!strcmp(".", git_dir))
500 return 1;
501 cwd = xgetcwd();
502 cwd_is_git_dir = !strcmp(git_dir, cwd);
503 free(cwd);
504 if (cwd_is_git_dir)
505 return 1;
507 * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
509 if (!strcmp(git_dir, ".git"))
510 return 0;
511 slash = strrchr(git_dir, '/');
512 if (slash && !strcmp(slash, "/.git"))
513 return 0;
516 * Otherwise it is often bare. At this point
517 * we are just guessing.
519 return 1;
522 static int shared_callback(const struct option *opt, const char *arg, int unset)
524 BUG_ON_OPT_NEG(unset);
525 *((int *) opt->value) = (arg) ? git_config_perm("arg", arg) : PERM_GROUP;
526 return 0;
529 static const char *const init_db_usage[] = {
530 N_("git init [-q | --quiet] [--bare] [--template=<template-directory>] [--shared[=<permissions>]] [<directory>]"),
531 NULL
535 * If you want to, you can share the DB area with any number of branches.
536 * That has advantages: you can save space by sharing all the SHA1 objects.
537 * On the other hand, it might just make lookup slower and messier. You
538 * be the judge. The default case is to have one DB per managed directory.
540 int cmd_init_db(int argc, const char **argv, const char *prefix)
542 const char *git_dir;
543 const char *real_git_dir = NULL;
544 const char *work_tree;
545 const char *template_dir = NULL;
546 unsigned int flags = 0;
547 const char *object_format = NULL;
548 const char *initial_branch = NULL;
549 int hash_algo = GIT_HASH_UNKNOWN;
550 const struct option init_db_options[] = {
551 OPT_STRING(0, "template", &template_dir, N_("template-directory"),
552 N_("directory from which templates will be used")),
553 OPT_SET_INT(0, "bare", &is_bare_repository_cfg,
554 N_("create a bare repository"), 1),
555 { OPTION_CALLBACK, 0, "shared", &init_shared_repository,
556 N_("permissions"),
557 N_("specify that the git repository is to be shared amongst several users"),
558 PARSE_OPT_OPTARG | PARSE_OPT_NONEG, shared_callback, 0},
559 OPT_BIT('q', "quiet", &flags, N_("be quiet"), INIT_DB_QUIET),
560 OPT_STRING(0, "separate-git-dir", &real_git_dir, N_("gitdir"),
561 N_("separate git dir from working tree")),
562 OPT_STRING('b', "initial-branch", &initial_branch, N_("name"),
563 N_("override the name of the initial branch")),
564 OPT_STRING(0, "object-format", &object_format, N_("hash"),
565 N_("specify the hash algorithm to use")),
566 OPT_END()
569 argc = parse_options(argc, argv, prefix, init_db_options, init_db_usage, 0);
571 if (real_git_dir && !is_absolute_path(real_git_dir))
572 real_git_dir = real_pathdup(real_git_dir, 1);
574 if (template_dir && *template_dir && !is_absolute_path(template_dir))
575 template_dir = absolute_pathdup(template_dir);
577 if (argc == 1) {
578 int mkdir_tried = 0;
579 retry:
580 if (chdir(argv[0]) < 0) {
581 if (!mkdir_tried) {
582 int saved;
584 * At this point we haven't read any configuration,
585 * and we know shared_repository should always be 0;
586 * but just in case we play safe.
588 saved = get_shared_repository();
589 set_shared_repository(0);
590 switch (safe_create_leading_directories_const(argv[0])) {
591 case SCLD_OK:
592 case SCLD_PERMS:
593 break;
594 case SCLD_EXISTS:
595 errno = EEXIST;
596 /* fallthru */
597 default:
598 die_errno(_("cannot mkdir %s"), argv[0]);
599 break;
601 set_shared_repository(saved);
602 if (mkdir(argv[0], 0777) < 0)
603 die_errno(_("cannot mkdir %s"), argv[0]);
604 mkdir_tried = 1;
605 goto retry;
607 die_errno(_("cannot chdir to %s"), argv[0]);
609 } else if (0 < argc) {
610 usage(init_db_usage[0]);
612 if (is_bare_repository_cfg == 1) {
613 char *cwd = xgetcwd();
614 setenv(GIT_DIR_ENVIRONMENT, cwd, argc > 0);
615 free(cwd);
618 if (object_format) {
619 hash_algo = hash_algo_by_name(object_format);
620 if (hash_algo == GIT_HASH_UNKNOWN)
621 die(_("unknown hash algorithm '%s'"), object_format);
624 if (init_shared_repository != -1)
625 set_shared_repository(init_shared_repository);
628 * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
629 * without --bare. Catch the error early.
631 git_dir = xstrdup_or_null(getenv(GIT_DIR_ENVIRONMENT));
632 work_tree = xstrdup_or_null(getenv(GIT_WORK_TREE_ENVIRONMENT));
633 if ((!git_dir || is_bare_repository_cfg == 1) && work_tree)
634 die(_("%s (or --work-tree=<directory>) not allowed without "
635 "specifying %s (or --git-dir=<directory>)"),
636 GIT_WORK_TREE_ENVIRONMENT,
637 GIT_DIR_ENVIRONMENT);
640 * Set up the default .git directory contents
642 if (!git_dir)
643 git_dir = DEFAULT_GIT_DIR_ENVIRONMENT;
645 if (is_bare_repository_cfg < 0)
646 is_bare_repository_cfg = guess_repository_type(git_dir);
648 if (!is_bare_repository_cfg) {
649 const char *git_dir_parent = strrchr(git_dir, '/');
650 if (git_dir_parent) {
651 char *rel = xstrndup(git_dir, git_dir_parent - git_dir);
652 git_work_tree_cfg = real_pathdup(rel, 1);
653 free(rel);
655 if (!git_work_tree_cfg)
656 git_work_tree_cfg = xgetcwd();
657 if (work_tree)
658 set_git_work_tree(work_tree);
659 else
660 set_git_work_tree(git_work_tree_cfg);
661 if (access(get_git_work_tree(), X_OK))
662 die_errno (_("Cannot access work tree '%s'"),
663 get_git_work_tree());
665 else {
666 if (work_tree)
667 set_git_work_tree(work_tree);
670 UNLEAK(real_git_dir);
671 UNLEAK(git_dir);
672 UNLEAK(work_tree);
674 flags |= INIT_DB_EXIST_OK;
675 return init_db(git_dir, real_git_dir, template_dir, hash_algo,
676 initial_branch, flags);