2 * GIT - The information manager from hell
4 * Copyright (C) Linus Torvalds, 2005
10 #include "environment.h"
15 #include "object-file.h"
16 #include "parse-options.h"
22 #ifndef DEFAULT_GIT_TEMPLATE_DIR
23 #define DEFAULT_GIT_TEMPLATE_DIR "/usr/share/git-core/templates"
26 #ifdef NO_TRUSTABLE_FILEMODE
27 #define TEST_FILEMODE 0
29 #define TEST_FILEMODE 1
32 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
34 static void copy_templates_1(struct strbuf
*path
, struct strbuf
*template_path
,
37 size_t path_baselen
= path
->len
;
38 size_t template_baselen
= template_path
->len
;
41 /* Note: if ".git/hooks" file exists in the repository being
42 * re-initialized, /etc/core-git/templates/hooks/update would
43 * cause "git init" to fail here. I think this is sane but
44 * it means that the set of templates we ship by default, along
45 * with the way the namespace under .git/ is organized, should
46 * be really carefully chosen.
48 safe_create_dir(path
->buf
, 1);
49 while ((de
= readdir(dir
)) != NULL
) {
50 struct stat st_git
, st_template
;
53 strbuf_setlen(path
, path_baselen
);
54 strbuf_setlen(template_path
, template_baselen
);
56 if (de
->d_name
[0] == '.')
58 strbuf_addstr(path
, de
->d_name
);
59 strbuf_addstr(template_path
, de
->d_name
);
60 if (lstat(path
->buf
, &st_git
)) {
62 die_errno(_("cannot stat '%s'"), path
->buf
);
67 if (lstat(template_path
->buf
, &st_template
))
68 die_errno(_("cannot stat template '%s'"), template_path
->buf
);
70 if (S_ISDIR(st_template
.st_mode
)) {
71 DIR *subdir
= opendir(template_path
->buf
);
73 die_errno(_("cannot opendir '%s'"), template_path
->buf
);
74 strbuf_addch(path
, '/');
75 strbuf_addch(template_path
, '/');
76 copy_templates_1(path
, template_path
, subdir
);
81 else if (S_ISLNK(st_template
.st_mode
)) {
82 struct strbuf lnk
= STRBUF_INIT
;
83 if (strbuf_readlink(&lnk
, template_path
->buf
,
84 st_template
.st_size
) < 0)
85 die_errno(_("cannot readlink '%s'"), template_path
->buf
);
86 if (symlink(lnk
.buf
, path
->buf
))
87 die_errno(_("cannot symlink '%s' '%s'"),
91 else if (S_ISREG(st_template
.st_mode
)) {
92 if (copy_file(path
->buf
, template_path
->buf
, st_template
.st_mode
))
93 die_errno(_("cannot copy '%s' to '%s'"),
94 template_path
->buf
, path
->buf
);
97 error(_("ignoring template %s"), template_path
->buf
);
101 static void copy_templates(const char *template_dir
, const char *init_template_dir
)
103 struct strbuf path
= STRBUF_INIT
;
104 struct strbuf template_path
= STRBUF_INIT
;
106 struct repository_format template_format
= REPOSITORY_FORMAT_INIT
;
107 struct strbuf err
= STRBUF_INIT
;
109 char *to_free
= NULL
;
112 template_dir
= getenv(TEMPLATE_DIR_ENVIRONMENT
);
114 template_dir
= init_template_dir
;
116 template_dir
= to_free
= system_path(DEFAULT_GIT_TEMPLATE_DIR
);
117 if (!template_dir
[0]) {
122 strbuf_addstr(&template_path
, template_dir
);
123 strbuf_complete(&template_path
, '/');
124 template_len
= template_path
.len
;
126 dir
= opendir(template_path
.buf
);
128 warning(_("templates not found in %s"), template_dir
);
132 /* Make sure that template is from the correct vintage */
133 strbuf_addstr(&template_path
, "config");
134 read_repository_format(&template_format
, template_path
.buf
);
135 strbuf_setlen(&template_path
, template_len
);
138 * No mention of version at all is OK, but anything else should be
141 if (template_format
.version
>= 0 &&
142 verify_repository_format(&template_format
, &err
) < 0) {
143 warning(_("not copying templates from '%s': %s"),
144 template_dir
, err
.buf
);
145 strbuf_release(&err
);
146 goto close_free_return
;
149 strbuf_addstr(&path
, get_git_common_dir());
150 strbuf_complete(&path
, '/');
151 copy_templates_1(&path
, &template_path
, dir
);
156 strbuf_release(&path
);
157 strbuf_release(&template_path
);
158 clear_repository_format(&template_format
);
162 * If the git_dir is not directly inside the working tree, then git will not
163 * find it by default, and we need to set the worktree explicitly.
165 static int needs_work_tree_config(const char *git_dir
, const char *work_tree
)
167 if (!strcmp(work_tree
, "/") && !strcmp(git_dir
, "/.git"))
169 if (skip_prefix(git_dir
, work_tree
, &git_dir
) &&
170 !strcmp(git_dir
, "/.git"))
175 void initialize_repository_version(int hash_algo
, int reinit
)
177 char repo_version_string
[10];
178 int repo_version
= GIT_REPO_VERSION
;
180 if (hash_algo
!= GIT_HASH_SHA1
)
181 repo_version
= GIT_REPO_VERSION_READ
;
183 /* This forces creation of new config file */
184 xsnprintf(repo_version_string
, sizeof(repo_version_string
),
186 git_config_set("core.repositoryformatversion", repo_version_string
);
188 if (hash_algo
!= GIT_HASH_SHA1
)
189 git_config_set("extensions.objectformat",
190 hash_algos
[hash_algo
].name
);
192 git_config_set_gently("extensions.objectformat", NULL
);
195 static int create_default_files(const char *template_path
,
196 const char *original_git_dir
,
197 const char *initial_branch
,
198 const struct repository_format
*fmt
,
199 int prev_bare_repository
,
200 int init_shared_repository
,
204 struct strbuf buf
= STRBUF_INIT
;
209 struct strbuf err
= STRBUF_INIT
;
210 const char *init_template_dir
= NULL
;
211 const char *work_tree
= get_git_work_tree();
214 * First copy the templates -- we might have the default
215 * config file there, in which case we would want to read
216 * from it after installing.
218 * Before reading that config, we also need to clear out any cached
219 * values (since we've just potentially changed what's available on
222 git_config_get_pathname("init.templatedir", &init_template_dir
);
223 copy_templates(template_path
, init_template_dir
);
224 free((char *)init_template_dir
);
226 reset_shared_repository();
227 git_config(git_default_config
, NULL
);
230 * We must make sure command-line options continue to override any
231 * values we might have just re-read from the config.
233 if (init_shared_repository
!= -1)
234 set_shared_repository(init_shared_repository
);
236 * TODO: heed core.bare from config file in templates if no
237 * command-line override given
239 is_bare_repository_cfg
= prev_bare_repository
|| !work_tree
;
242 * Unfortunately, the line above is equivalent to
243 * is_bare_repository_cfg = !work_tree;
244 * which ignores the config entirely even if no `--[no-]bare`
245 * command line option was present.
247 * To see why, note that before this function, there was this call:
248 * prev_bare_repository = is_bare_repository()
249 * expanding the right hand side:
250 * = is_bare_repository_cfg && !get_git_work_tree()
251 * = is_bare_repository_cfg && !work_tree
252 * note that the last simplification above is valid because nothing
253 * calls repo_init() or set_git_work_tree() between any of the
254 * relevant calls in the code, and thus the !get_git_work_tree()
255 * calls will return the same result each time. So, what we are
256 * interested in computing is the right hand side of the line of
257 * code just above this comment:
258 * prev_bare_repository || !work_tree
259 * = is_bare_repository_cfg && !work_tree || !work_tree
261 * because "A && !B || !B == !B" for all boolean values of A & B.
265 * We would have created the above under user's umask -- under
266 * shared-repository settings, we would need to fix them up.
268 if (get_shared_repository()) {
269 adjust_shared_perm(get_git_dir());
273 * We need to create a "refs" dir in any case so that older
274 * versions of git can tell that this is a repository.
276 safe_create_dir(git_path("refs"), 1);
277 adjust_shared_perm(git_path("refs"));
279 if (refs_init_db(&err
))
280 die("failed to set up refs db: %s", err
.buf
);
283 * Point the HEAD symref to the initial branch with if HEAD does
286 path
= git_path_buf(&buf
, "HEAD");
287 reinit
= (!access(path
, R_OK
)
288 || readlink(path
, junk
, sizeof(junk
)-1) != -1);
293 initial_branch
= git_default_branch_name(quiet
);
295 ref
= xstrfmt("refs/heads/%s", initial_branch
);
296 if (check_refname_format(ref
, 0) < 0)
297 die(_("invalid initial branch name: '%s'"),
300 if (create_symref("HEAD", ref
, NULL
) < 0)
305 initialize_repository_version(fmt
->hash_algo
, 0);
307 /* Check filemode trustability */
308 path
= git_path_buf(&buf
, "config");
309 filemode
= TEST_FILEMODE
;
310 if (TEST_FILEMODE
&& !lstat(path
, &st1
)) {
312 filemode
= (!chmod(path
, st1
.st_mode
^ S_IXUSR
) &&
313 !lstat(path
, &st2
) &&
314 st1
.st_mode
!= st2
.st_mode
&&
315 !chmod(path
, st1
.st_mode
));
316 if (filemode
&& !reinit
&& (st1
.st_mode
& S_IXUSR
))
319 git_config_set("core.filemode", filemode
? "true" : "false");
321 if (is_bare_repository())
322 git_config_set("core.bare", "true");
324 git_config_set("core.bare", "false");
325 /* allow template config file to override the default */
326 if (log_all_ref_updates
== LOG_REFS_UNSET
)
327 git_config_set("core.logallrefupdates", "true");
328 if (needs_work_tree_config(original_git_dir
, work_tree
))
329 git_config_set("core.worktree", work_tree
);
333 /* Check if symlink is supported in the work tree */
334 path
= git_path_buf(&buf
, "tXXXXXX");
335 if (!close(xmkstemp(path
)) &&
337 !symlink("testing", path
) &&
338 !lstat(path
, &st1
) &&
339 S_ISLNK(st1
.st_mode
))
340 unlink(path
); /* good */
342 git_config_set("core.symlinks", "false");
344 /* Check if the filesystem is case-insensitive */
345 path
= git_path_buf(&buf
, "CoNfIg");
346 if (!access(path
, F_OK
))
347 git_config_set("core.ignorecase", "true");
348 probe_utf8_pathname_composition();
351 strbuf_release(&buf
);
355 static void create_object_directory(void)
357 struct strbuf path
= STRBUF_INIT
;
360 strbuf_addstr(&path
, get_object_directory());
363 safe_create_dir(path
.buf
, 1);
365 strbuf_setlen(&path
, baselen
);
366 strbuf_addstr(&path
, "/pack");
367 safe_create_dir(path
.buf
, 1);
369 strbuf_setlen(&path
, baselen
);
370 strbuf_addstr(&path
, "/info");
371 safe_create_dir(path
.buf
, 1);
373 strbuf_release(&path
);
376 static void separate_git_dir(const char *git_dir
, const char *git_link
)
380 if (!stat(git_link
, &st
)) {
383 if (S_ISREG(st
.st_mode
))
384 src
= read_gitfile(git_link
);
385 else if (S_ISDIR(st
.st_mode
))
388 die(_("unable to handle file type %d"), (int)st
.st_mode
);
390 if (rename(src
, git_dir
))
391 die_errno(_("unable to move %s to %s"), src
, git_dir
);
392 repair_worktrees(NULL
, NULL
);
395 write_file(git_link
, "gitdir: %s", git_dir
);
398 static void validate_hash_algorithm(struct repository_format
*repo_fmt
, int hash
)
400 const char *env
= getenv(GIT_DEFAULT_HASH_ENVIRONMENT
);
402 * If we already have an initialized repo, don't allow the user to
403 * specify a different algorithm, as that could cause corruption.
404 * Otherwise, if the user has specified one on the command line, use it.
406 if (repo_fmt
->version
>= 0 && hash
!= GIT_HASH_UNKNOWN
&& hash
!= repo_fmt
->hash_algo
)
407 die(_("attempt to reinitialize repository with different hash"));
408 else if (hash
!= GIT_HASH_UNKNOWN
)
409 repo_fmt
->hash_algo
= hash
;
411 int env_algo
= hash_algo_by_name(env
);
412 if (env_algo
== GIT_HASH_UNKNOWN
)
413 die(_("unknown hash algorithm '%s'"), env
);
414 repo_fmt
->hash_algo
= env_algo
;
418 int init_db(const char *git_dir
, const char *real_git_dir
,
419 const char *template_dir
, int hash
, const char *initial_branch
,
420 int init_shared_repository
, unsigned int flags
)
423 int exist_ok
= flags
& INIT_DB_EXIST_OK
;
424 char *original_git_dir
= real_pathdup(git_dir
, 1);
425 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
426 int prev_bare_repository
;
431 if (!exist_ok
&& !stat(git_dir
, &st
))
432 die(_("%s already exists"), git_dir
);
434 if (!exist_ok
&& !stat(real_git_dir
, &st
))
435 die(_("%s already exists"), real_git_dir
);
437 set_git_dir(real_git_dir
, 1);
438 git_dir
= get_git_dir();
439 separate_git_dir(git_dir
, original_git_dir
);
442 set_git_dir(git_dir
, 1);
443 git_dir
= get_git_dir();
445 startup_info
->have_repository
= 1;
447 /* Ensure `core.hidedotfiles` is processed */
448 git_config(platform_core_config
, NULL
);
450 safe_create_dir(git_dir
, 0);
452 prev_bare_repository
= is_bare_repository();
454 /* Check to see if the repository version is right.
455 * Note that a newly created repository does not have
456 * config file, so this will not fail. What we are catching
457 * is an attempt to reinitialize new repository with an old tool.
459 check_repository_format(&repo_fmt
);
461 validate_hash_algorithm(&repo_fmt
, hash
);
463 reinit
= create_default_files(template_dir
, original_git_dir
,
464 initial_branch
, &repo_fmt
,
465 prev_bare_repository
,
466 init_shared_repository
,
467 flags
& INIT_DB_QUIET
);
468 if (reinit
&& initial_branch
)
469 warning(_("re-init: ignored --initial-branch=%s"),
472 create_object_directory();
474 if (get_shared_repository()) {
476 /* We do not spell "group" and such, so that
477 * the configuration can be read by older version
478 * of git. Note, we use octal numbers for new share modes,
479 * and compatibility values for PERM_GROUP and
482 if (get_shared_repository() < 0)
483 /* force to the mode value */
484 xsnprintf(buf
, sizeof(buf
), "0%o", -get_shared_repository());
485 else if (get_shared_repository() == PERM_GROUP
)
486 xsnprintf(buf
, sizeof(buf
), "%d", OLD_PERM_GROUP
);
487 else if (get_shared_repository() == PERM_EVERYBODY
)
488 xsnprintf(buf
, sizeof(buf
), "%d", OLD_PERM_EVERYBODY
);
490 BUG("invalid value for shared_repository");
491 git_config_set("core.sharedrepository", buf
);
492 git_config_set("receive.denyNonFastforwards", "true");
495 if (!(flags
& INIT_DB_QUIET
)) {
496 int len
= strlen(git_dir
);
499 printf(get_shared_repository()
500 ? _("Reinitialized existing shared Git repository in %s%s\n")
501 : _("Reinitialized existing Git repository in %s%s\n"),
502 git_dir
, len
&& git_dir
[len
-1] != '/' ? "/" : "");
504 printf(get_shared_repository()
505 ? _("Initialized empty shared Git repository in %s%s\n")
506 : _("Initialized empty Git repository in %s%s\n"),
507 git_dir
, len
&& git_dir
[len
-1] != '/' ? "/" : "");
510 free(original_git_dir
);
514 static int guess_repository_type(const char *git_dir
)
521 * "GIT_DIR=. git init" is always bare.
522 * "GIT_DIR=`pwd` git init" too.
524 if (!strcmp(".", git_dir
))
527 cwd_is_git_dir
= !strcmp(git_dir
, cwd
);
532 * "GIT_DIR=.git or GIT_DIR=something/.git is usually not.
534 if (!strcmp(git_dir
, ".git"))
536 slash
= strrchr(git_dir
, '/');
537 if (slash
&& !strcmp(slash
, "/.git"))
541 * Otherwise it is often bare. At this point
542 * we are just guessing.
547 static int shared_callback(const struct option
*opt
, const char *arg
, int unset
)
549 BUG_ON_OPT_NEG(unset
);
550 *((int *) opt
->value
) = (arg
) ? git_config_perm("arg", arg
) : PERM_GROUP
;
554 static const char *const init_db_usage
[] = {
555 N_("git init [-q | --quiet] [--bare] [--template=<template-directory>]\n"
556 " [--separate-git-dir <git-dir>] [--object-format=<format>]\n"
557 " [-b <branch-name> | --initial-branch=<branch-name>]\n"
558 " [--shared[=<permissions>]] [<directory>]"),
563 * If you want to, you can share the DB area with any number of branches.
564 * That has advantages: you can save space by sharing all the SHA1 objects.
565 * On the other hand, it might just make lookup slower and messier. You
566 * be the judge. The default case is to have one DB per managed directory.
568 int cmd_init_db(int argc
, const char **argv
, const char *prefix
)
571 const char *real_git_dir
= NULL
;
572 const char *work_tree
;
573 const char *template_dir
= NULL
;
574 unsigned int flags
= 0;
575 const char *object_format
= NULL
;
576 const char *initial_branch
= NULL
;
577 int hash_algo
= GIT_HASH_UNKNOWN
;
578 int init_shared_repository
= -1;
579 const struct option init_db_options
[] = {
580 OPT_STRING(0, "template", &template_dir
, N_("template-directory"),
581 N_("directory from which templates will be used")),
582 OPT_SET_INT(0, "bare", &is_bare_repository_cfg
,
583 N_("create a bare repository"), 1),
584 { OPTION_CALLBACK
, 0, "shared", &init_shared_repository
,
586 N_("specify that the git repository is to be shared amongst several users"),
587 PARSE_OPT_OPTARG
| PARSE_OPT_NONEG
, shared_callback
, 0},
588 OPT_BIT('q', "quiet", &flags
, N_("be quiet"), INIT_DB_QUIET
),
589 OPT_STRING(0, "separate-git-dir", &real_git_dir
, N_("gitdir"),
590 N_("separate git dir from working tree")),
591 OPT_STRING('b', "initial-branch", &initial_branch
, N_("name"),
592 N_("override the name of the initial branch")),
593 OPT_STRING(0, "object-format", &object_format
, N_("hash"),
594 N_("specify the hash algorithm to use")),
598 argc
= parse_options(argc
, argv
, prefix
, init_db_options
, init_db_usage
, 0);
600 if (real_git_dir
&& is_bare_repository_cfg
== 1)
601 die(_("options '%s' and '%s' cannot be used together"), "--separate-git-dir", "--bare");
603 if (real_git_dir
&& !is_absolute_path(real_git_dir
))
604 real_git_dir
= real_pathdup(real_git_dir
, 1);
606 if (template_dir
&& *template_dir
&& !is_absolute_path(template_dir
)) {
607 template_dir
= absolute_pathdup(template_dir
);
608 UNLEAK(template_dir
);
614 if (chdir(argv
[0]) < 0) {
618 * At this point we haven't read any configuration,
619 * and we know shared_repository should always be 0;
620 * but just in case we play safe.
622 saved
= get_shared_repository();
623 set_shared_repository(0);
624 switch (safe_create_leading_directories_const(argv
[0])) {
632 die_errno(_("cannot mkdir %s"), argv
[0]);
635 set_shared_repository(saved
);
636 if (mkdir(argv
[0], 0777) < 0)
637 die_errno(_("cannot mkdir %s"), argv
[0]);
641 die_errno(_("cannot chdir to %s"), argv
[0]);
643 } else if (0 < argc
) {
644 usage(init_db_usage
[0]);
646 if (is_bare_repository_cfg
== 1) {
647 char *cwd
= xgetcwd();
648 setenv(GIT_DIR_ENVIRONMENT
, cwd
, argc
> 0);
653 hash_algo
= hash_algo_by_name(object_format
);
654 if (hash_algo
== GIT_HASH_UNKNOWN
)
655 die(_("unknown hash algorithm '%s'"), object_format
);
658 if (init_shared_repository
!= -1)
659 set_shared_repository(init_shared_repository
);
662 * GIT_WORK_TREE makes sense only in conjunction with GIT_DIR
663 * without --bare. Catch the error early.
665 git_dir
= xstrdup_or_null(getenv(GIT_DIR_ENVIRONMENT
));
666 work_tree
= xstrdup_or_null(getenv(GIT_WORK_TREE_ENVIRONMENT
));
667 if ((!git_dir
|| is_bare_repository_cfg
== 1) && work_tree
)
668 die(_("%s (or --work-tree=<directory>) not allowed without "
669 "specifying %s (or --git-dir=<directory>)"),
670 GIT_WORK_TREE_ENVIRONMENT
,
671 GIT_DIR_ENVIRONMENT
);
674 * Set up the default .git directory contents
677 git_dir
= DEFAULT_GIT_DIR_ENVIRONMENT
;
680 * When --separate-git-dir is used inside a linked worktree, take
681 * care to ensure that the common .git/ directory is relocated, not
682 * the worktree-specific .git/worktrees/<id>/ directory.
687 struct strbuf sb
= STRBUF_INIT
;
689 p
= read_gitfile_gently(git_dir
, &err
);
690 if (p
&& get_common_dir(&sb
, p
)) {
691 struct strbuf mainwt
= STRBUF_INIT
;
693 strbuf_addbuf(&mainwt
, &sb
);
694 strbuf_strip_suffix(&mainwt
, "/.git");
695 if (chdir(mainwt
.buf
) < 0)
696 die_errno(_("cannot chdir to %s"), mainwt
.buf
);
697 strbuf_release(&mainwt
);
698 git_dir
= strbuf_detach(&sb
, NULL
);
703 if (is_bare_repository_cfg
< 0)
704 is_bare_repository_cfg
= guess_repository_type(git_dir
);
706 if (!is_bare_repository_cfg
) {
707 const char *git_dir_parent
= strrchr(git_dir
, '/');
708 if (git_dir_parent
) {
709 char *rel
= xstrndup(git_dir
, git_dir_parent
- git_dir
);
710 git_work_tree_cfg
= real_pathdup(rel
, 1);
713 if (!git_work_tree_cfg
)
714 git_work_tree_cfg
= xgetcwd();
716 set_git_work_tree(work_tree
);
718 set_git_work_tree(git_work_tree_cfg
);
719 if (access(get_git_work_tree(), X_OK
))
720 die_errno (_("Cannot access work tree '%s'"),
721 get_git_work_tree());
725 die(_("--separate-git-dir incompatible with bare repository"));
727 set_git_work_tree(work_tree
);
730 UNLEAK(real_git_dir
);
734 flags
|= INIT_DB_EXIST_OK
;
735 return init_db(git_dir
, real_git_dir
, template_dir
, hash_algo
,
736 initial_branch
, init_shared_repository
, flags
);