1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
6 #include "environment.h"
10 #include "object-file.h"
11 #include "object-name.h"
13 #include "replace-object.h"
14 #include "repository.h"
19 #include "string-list.h"
21 #include "chdir-notify.h"
24 #include "tmp-objdir.h"
30 static int inside_git_dir
= -1;
31 static int inside_work_tree
= -1;
32 static int work_tree_config_is_bogus
;
33 enum allowed_bare_repo
{
34 ALLOWED_BARE_REPO_EXPLICIT
= 0,
35 ALLOWED_BARE_REPO_ALL
,
38 static struct startup_info the_startup_info
;
39 struct startup_info
*startup_info
= &the_startup_info
;
40 const char *tmp_original_cwd
;
43 * The input parameter must contain an absolute path, and it must already be
46 * Find the part of an absolute path that lies inside the work tree by
47 * dereferencing symlinks outside the work tree, for example:
48 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
49 * /dir/file (work tree is /) -> dir/file
50 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
51 * /dir/repolink/file (repolink points to /dir/repo) -> file
52 * /dir/repo (exactly equal to work tree) -> (empty string)
54 static int abspath_part_inside_repo(char *path
)
60 const char *work_tree
= precompose_string_if_needed(repo_get_work_tree(the_repository
));
61 struct strbuf realpath
= STRBUF_INIT
;
65 wtlen
= strlen(work_tree
);
67 off
= offset_1st_component(path
);
69 /* check if work tree is already the prefix */
70 if (wtlen
<= len
&& !fspathncmp(path
, work_tree
, wtlen
)) {
71 if (path
[wtlen
] == '/') {
72 memmove(path
, path
+ wtlen
+ 1, len
- wtlen
);
74 } else if (path
[wtlen
- 1] == '/' || path
[wtlen
] == '\0') {
75 /* work tree is the root, or the whole path */
76 memmove(path
, path
+ wtlen
, len
- wtlen
+ 1);
79 /* work tree might match beginning of a symlink to work tree */
85 /* check each '/'-terminated level */
90 strbuf_realpath(&realpath
, path0
, 1);
91 if (fspathcmp(realpath
.buf
, work_tree
) == 0) {
92 memmove(path0
, path
+ 1, len
- (path
- path0
));
93 strbuf_release(&realpath
);
100 /* check whole path */
101 strbuf_realpath(&realpath
, path0
, 1);
102 if (fspathcmp(realpath
.buf
, work_tree
) == 0) {
104 strbuf_release(&realpath
);
108 strbuf_release(&realpath
);
113 * Normalize "path", prepending the "prefix" for relative paths. If
114 * remaining_prefix is not NULL, return the actual prefix still
115 * remains in the path. For example, prefix = sub1/sub2/ and path is
117 * foo -> sub1/sub2/foo (full prefix)
118 * ../foo -> sub1/foo (remaining prefix is sub1/)
119 * ../../bar -> bar (no remaining prefix)
120 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
121 * `pwd`/../bar -> sub1/bar (no remaining prefix)
123 char *prefix_path_gently(const char *prefix
, int len
,
124 int *remaining_prefix
, const char *path
)
126 const char *orig
= path
;
128 if (is_absolute_path(orig
)) {
129 sanitized
= xmallocz(strlen(path
));
130 if (remaining_prefix
)
131 *remaining_prefix
= 0;
132 if (normalize_path_copy_len(sanitized
, path
, remaining_prefix
)) {
136 if (abspath_part_inside_repo(sanitized
)) {
141 sanitized
= xstrfmt("%.*s%s", len
, len
? prefix
: "", path
);
142 if (remaining_prefix
)
143 *remaining_prefix
= len
;
144 if (normalize_path_copy_len(sanitized
, sanitized
, remaining_prefix
)) {
152 char *prefix_path(const char *prefix
, int len
, const char *path
)
154 char *r
= prefix_path_gently(prefix
, len
, NULL
, path
);
156 const char *hint_path
= repo_get_work_tree(the_repository
);
158 hint_path
= repo_get_git_dir(the_repository
);
159 die(_("'%s' is outside repository at '%s'"), path
,
160 absolute_path(hint_path
));
165 int path_inside_repo(const char *prefix
, const char *path
)
167 int len
= prefix
? strlen(prefix
) : 0;
168 char *r
= prefix_path_gently(prefix
, len
, NULL
, path
);
176 int check_filename(const char *prefix
, const char *arg
)
178 char *to_free
= NULL
;
181 if (skip_prefix(arg
, ":/", &arg
)) {
182 if (!*arg
) /* ":/" is root dir, always exists */
185 } else if (skip_prefix(arg
, ":!", &arg
) ||
186 skip_prefix(arg
, ":^", &arg
)) {
187 if (!*arg
) /* excluding everything is silly, but allowed */
192 arg
= to_free
= prefix_filename(prefix
, arg
);
194 if (!lstat(arg
, &st
)) {
196 return 1; /* file exists */
198 if (is_missing_file_error(errno
)) {
200 return 0; /* file does not exist */
202 die_errno(_("failed to stat '%s'"), arg
);
205 static void NORETURN
die_verify_filename(struct repository
*r
,
208 int diagnose_misspelt_rev
)
210 if (!diagnose_misspelt_rev
)
211 die(_("%s: no such path in the working tree.\n"
212 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
215 * Saying "'(icase)foo' does not exist in the index" when the
216 * user gave us ":(icase)foo" is just stupid. A magic pathspec
217 * begins with a colon and is followed by a non-alnum; do not
218 * let maybe_die_on_misspelt_object_name() even trigger.
220 if (!(arg
[0] == ':' && !isalnum(arg
[1])))
221 maybe_die_on_misspelt_object_name(r
, arg
, prefix
);
223 /* ... or fall back the most general message. */
224 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
225 "Use '--' to separate paths from revisions, like this:\n"
226 "'git <command> [<revision>...] -- [<file>...]'"), arg
);
231 * Check for arguments that don't resolve as actual files,
232 * but which look sufficiently like pathspecs that we'll consider
233 * them such for the purposes of rev/pathspec DWIM parsing.
235 static int looks_like_pathspec(const char *arg
)
241 * Wildcard characters imply the user is looking to match pathspecs
242 * that aren't in the filesystem. Note that this doesn't include
243 * backslash even though it's a glob special; by itself it doesn't
244 * cause any increase in the match. Likewise ignore backslash-escaped
245 * wildcard characters.
247 for (p
= arg
; *p
; p
++) {
250 } else if (is_glob_special(*p
)) {
258 /* long-form pathspec magic */
259 if (starts_with(arg
, ":("))
266 * Verify a filename that we got as an argument for a pathspec
267 * entry. Note that a filename that begins with "-" never verifies
268 * as true, because even if such a filename were to exist, we want
269 * it to be preceded by the "--" marker (or we want the user to
270 * use a format like "./-filename")
272 * The "diagnose_misspelt_rev" is used to provide a user-friendly
273 * diagnosis when dying upon finding that "name" is not a pathname.
274 * If set to 1, the diagnosis will try to diagnose "name" as an
275 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
276 * will only complain about an inexisting file.
278 * This function is typically called to check that a "file or rev"
279 * argument is unambiguous. In this case, the caller will want
280 * diagnose_misspelt_rev == 1 when verifying the first non-rev
281 * argument (which could have been a revision), and
282 * diagnose_misspelt_rev == 0 for the next ones (because we already
283 * saw a filename, there's not ambiguity anymore).
285 void verify_filename(const char *prefix
,
287 int diagnose_misspelt_rev
)
290 die(_("option '%s' must come before non-option arguments"), arg
);
291 if (looks_like_pathspec(arg
) || check_filename(prefix
, arg
))
293 die_verify_filename(the_repository
, prefix
, arg
, diagnose_misspelt_rev
);
297 * Opposite of the above: the command line did not have -- marker
298 * and we parsed the arg as a refname. It should not be interpretable
301 void verify_non_filename(const char *prefix
, const char *arg
)
303 if (!is_inside_work_tree() || is_inside_git_dir())
307 if (!check_filename(prefix
, arg
))
309 die(_("ambiguous argument '%s': both revision and filename\n"
310 "Use '--' to separate paths from revisions, like this:\n"
311 "'git <command> [<revision>...] -- [<file>...]'"), arg
);
314 int get_common_dir(struct strbuf
*sb
, const char *gitdir
)
316 const char *git_env_common_dir
= getenv(GIT_COMMON_DIR_ENVIRONMENT
);
317 if (git_env_common_dir
) {
318 strbuf_addstr(sb
, git_env_common_dir
);
321 return get_common_dir_noenv(sb
, gitdir
);
325 int get_common_dir_noenv(struct strbuf
*sb
, const char *gitdir
)
327 struct strbuf data
= STRBUF_INIT
;
328 struct strbuf path
= STRBUF_INIT
;
331 strbuf_addf(&path
, "%s/commondir", gitdir
);
332 if (file_exists(path
.buf
)) {
333 if (strbuf_read_file(&data
, path
.buf
, 0) <= 0)
334 die_errno(_("failed to read %s"), path
.buf
);
335 while (data
.len
&& (data
.buf
[data
.len
- 1] == '\n' ||
336 data
.buf
[data
.len
- 1] == '\r'))
338 data
.buf
[data
.len
] = '\0';
340 if (!is_absolute_path(data
.buf
))
341 strbuf_addf(&path
, "%s/", gitdir
);
342 strbuf_addbuf(&path
, &data
);
343 strbuf_add_real_path(sb
, path
.buf
);
346 strbuf_addstr(sb
, gitdir
);
349 strbuf_release(&data
);
350 strbuf_release(&path
);
354 static int validate_headref(const char *path
)
359 struct object_id oid
;
363 if (lstat(path
, &st
) < 0)
366 /* Make sure it is a "refs/.." symlink */
367 if (S_ISLNK(st
.st_mode
)) {
368 len
= readlink(path
, buffer
, sizeof(buffer
)-1);
369 if (len
>= 5 && !memcmp("refs/", buffer
, 5))
375 * Anything else, just open it and try to see if it is a symbolic ref.
377 fd
= open(path
, O_RDONLY
);
380 len
= read_in_full(fd
, buffer
, sizeof(buffer
)-1);
388 * Is it a symbolic ref?
390 if (skip_prefix(buffer
, "ref:", &refname
)) {
391 while (isspace(*refname
))
393 if (starts_with(refname
, "refs/"))
398 * Is this a detached HEAD?
400 if (get_oid_hex_any(buffer
, &oid
) != GIT_HASH_UNKNOWN
)
407 * Test if it looks like we're at a git directory.
410 * - either an objects/ directory _or_ the proper
411 * GIT_OBJECT_DIRECTORY environment variable
412 * - a refs/ directory
413 * - either a HEAD symlink or a HEAD file that is formatted as
414 * a proper "ref:", or a regular file HEAD that has a properly
415 * formatted sha1 object name.
417 int is_git_directory(const char *suspect
)
419 struct strbuf path
= STRBUF_INIT
;
423 /* Check worktree-related signatures */
424 strbuf_addstr(&path
, suspect
);
425 strbuf_complete(&path
, '/');
426 strbuf_addstr(&path
, "HEAD");
427 if (validate_headref(path
.buf
))
431 get_common_dir(&path
, suspect
);
434 /* Check non-worktree-related signatures */
435 if (getenv(DB_ENVIRONMENT
)) {
436 if (access(getenv(DB_ENVIRONMENT
), X_OK
))
440 strbuf_setlen(&path
, len
);
441 strbuf_addstr(&path
, "/objects");
442 if (access(path
.buf
, X_OK
))
446 strbuf_setlen(&path
, len
);
447 strbuf_addstr(&path
, "/refs");
448 if (access(path
.buf
, X_OK
))
453 strbuf_release(&path
);
457 int is_nonbare_repository_dir(struct strbuf
*path
)
461 size_t orig_path_len
= path
->len
;
462 assert(orig_path_len
!= 0);
463 strbuf_complete(path
, '/');
464 strbuf_addstr(path
, ".git");
465 if (read_gitfile_gently(path
->buf
, &gitfile_error
) || is_git_directory(path
->buf
))
467 if (gitfile_error
== READ_GITFILE_ERR_OPEN_FAILED
||
468 gitfile_error
== READ_GITFILE_ERR_READ_FAILED
)
470 strbuf_setlen(path
, orig_path_len
);
474 int is_inside_git_dir(void)
476 if (inside_git_dir
< 0)
477 inside_git_dir
= is_inside_dir(repo_get_git_dir(the_repository
));
478 return inside_git_dir
;
481 int is_inside_work_tree(void)
483 if (inside_work_tree
< 0)
484 inside_work_tree
= is_inside_dir(repo_get_work_tree(the_repository
));
485 return inside_work_tree
;
488 void setup_work_tree(void)
490 const char *work_tree
;
491 static int initialized
= 0;
496 if (work_tree_config_is_bogus
)
497 die(_("unable to set up work tree using invalid config"));
499 work_tree
= repo_get_work_tree(the_repository
);
500 if (!work_tree
|| chdir_notify(work_tree
))
501 die(_("this operation must be run in a work tree"));
504 * Make sure subsequent git processes find correct worktree
505 * if $GIT_WORK_TREE is set relative
507 if (getenv(GIT_WORK_TREE_ENVIRONMENT
))
508 setenv(GIT_WORK_TREE_ENVIRONMENT
, ".", 1);
513 static void setup_original_cwd(void)
515 struct strbuf tmp
= STRBUF_INIT
;
516 const char *worktree
= NULL
;
519 if (!tmp_original_cwd
)
523 * startup_info->original_cwd points to the current working
524 * directory we inherited from our parent process, which is a
525 * directory we want to avoid removing.
527 * For convenience, we would like to have the path relative to the
528 * worktree instead of an absolute path.
530 * Yes, startup_info->original_cwd is usually the same as 'prefix',
531 * but differs in two ways:
532 * - prefix has a trailing '/'
533 * - if the user passes '-C' to git, that modifies the prefix but
534 * not startup_info->original_cwd.
537 /* Normalize the directory */
538 if (!strbuf_realpath(&tmp
, tmp_original_cwd
, 0)) {
539 trace2_data_string("setup", the_repository
,
540 "realpath-path", tmp_original_cwd
);
541 trace2_data_string("setup", the_repository
,
542 "realpath-failure", strerror(errno
));
543 free((char*)tmp_original_cwd
);
544 tmp_original_cwd
= NULL
;
548 free((char*)tmp_original_cwd
);
549 tmp_original_cwd
= NULL
;
550 startup_info
->original_cwd
= strbuf_detach(&tmp
, NULL
);
553 * Get our worktree; we only protect the current working directory
554 * if it's in the worktree.
556 worktree
= repo_get_work_tree(the_repository
);
558 goto no_prevention_needed
;
560 offset
= dir_inside_of(startup_info
->original_cwd
, worktree
);
563 * If startup_info->original_cwd == worktree, that is already
564 * protected and we don't need original_cwd as a secondary
565 * protection measure.
567 if (!*(startup_info
->original_cwd
+ offset
))
568 goto no_prevention_needed
;
571 * original_cwd was inside worktree; precompose it just as
572 * we do prefix so that built up paths will match
574 startup_info
->original_cwd
= \
575 precompose_string_if_needed(startup_info
->original_cwd
580 no_prevention_needed
:
581 free((char*)startup_info
->original_cwd
);
582 startup_info
->original_cwd
= NULL
;
585 static int read_worktree_config(const char *var
, const char *value
,
586 const struct config_context
*ctx UNUSED
,
589 struct repository_format
*data
= vdata
;
591 if (strcmp(var
, "core.bare") == 0) {
592 data
->is_bare
= git_config_bool(var
, value
);
593 } else if (strcmp(var
, "core.worktree") == 0) {
595 return config_error_nonbool(var
);
596 free(data
->work_tree
);
597 data
->work_tree
= xstrdup(value
);
602 enum extension_result
{
603 EXTENSION_ERROR
= -1, /* compatible with error(), etc */
604 EXTENSION_UNKNOWN
= 0,
609 * Do not add new extensions to this function. It handles extensions which are
610 * respected even in v0-format repositories for historical compatibility.
612 static enum extension_result
handle_extension_v0(const char *var
,
615 struct repository_format
*data
)
617 if (!strcmp(ext
, "noop")) {
619 } else if (!strcmp(ext
, "preciousobjects")) {
620 data
->precious_objects
= git_config_bool(var
, value
);
622 } else if (!strcmp(ext
, "partialclone")) {
624 return config_error_nonbool(var
);
625 data
->partial_clone
= xstrdup(value
);
627 } else if (!strcmp(ext
, "worktreeconfig")) {
628 data
->worktree_config
= git_config_bool(var
, value
);
632 return EXTENSION_UNKNOWN
;
636 * Record any new extensions in this function.
638 static enum extension_result
handle_extension(const char *var
,
641 struct repository_format
*data
)
643 if (!strcmp(ext
, "noop-v1")) {
645 } else if (!strcmp(ext
, "objectformat")) {
649 return config_error_nonbool(var
);
650 format
= hash_algo_by_name(value
);
651 if (format
== GIT_HASH_UNKNOWN
)
652 return error(_("invalid value for '%s': '%s'"),
653 "extensions.objectformat", value
);
654 data
->hash_algo
= format
;
656 } else if (!strcmp(ext
, "compatobjectformat")) {
657 struct string_list_item
*item
;
661 return config_error_nonbool(var
);
662 format
= hash_algo_by_name(value
);
663 if (format
== GIT_HASH_UNKNOWN
)
664 return error(_("invalid value for '%s': '%s'"),
665 "extensions.compatobjectformat", value
);
666 /* For now only support compatObjectFormat being specified once. */
667 for_each_string_list_item(item
, &data
->v1_only_extensions
) {
668 if (!strcmp(item
->string
, "compatobjectformat"))
669 return error(_("'%s' already specified as '%s'"),
670 "extensions.compatobjectformat",
671 hash_algos
[data
->compat_hash_algo
].name
);
673 data
->compat_hash_algo
= format
;
675 } else if (!strcmp(ext
, "refstorage")) {
679 return config_error_nonbool(var
);
680 format
= ref_storage_format_by_name(value
);
681 if (format
== REF_STORAGE_FORMAT_UNKNOWN
)
682 return error(_("invalid value for '%s': '%s'"),
683 "extensions.refstorage", value
);
684 data
->ref_storage_format
= format
;
687 return EXTENSION_UNKNOWN
;
690 static int check_repo_format(const char *var
, const char *value
,
691 const struct config_context
*ctx
, void *vdata
)
693 struct repository_format
*data
= vdata
;
696 if (strcmp(var
, "core.repositoryformatversion") == 0)
697 data
->version
= git_config_int(var
, value
, ctx
->kvi
);
698 else if (skip_prefix(var
, "extensions.", &ext
)) {
699 switch (handle_extension_v0(var
, value
, ext
, data
)) {
700 case EXTENSION_ERROR
:
704 case EXTENSION_UNKNOWN
:
708 switch (handle_extension(var
, value
, ext
, data
)) {
709 case EXTENSION_ERROR
:
712 string_list_append(&data
->v1_only_extensions
, ext
);
714 case EXTENSION_UNKNOWN
:
715 string_list_append(&data
->unknown_extensions
, ext
);
720 return read_worktree_config(var
, value
, ctx
, vdata
);
723 static int check_repository_format_gently(const char *gitdir
, struct repository_format
*candidate
, int *nongit_ok
)
725 struct strbuf sb
= STRBUF_INIT
;
726 struct strbuf err
= STRBUF_INIT
;
729 has_common
= get_common_dir(&sb
, gitdir
);
730 strbuf_addstr(&sb
, "/config");
731 read_repository_format(candidate
, sb
.buf
);
735 * For historical use of check_repository_format() in git-init,
736 * we treat a missing config as a silent "ok", even when nongit_ok
739 if (candidate
->version
< 0)
742 if (verify_repository_format(candidate
, &err
) < 0) {
744 warning("%s", err
.buf
);
745 strbuf_release(&err
);
752 repository_format_precious_objects
= candidate
->precious_objects
;
753 string_list_clear(&candidate
->unknown_extensions
, 0);
754 string_list_clear(&candidate
->v1_only_extensions
, 0);
756 if (candidate
->worktree_config
) {
758 * pick up core.bare and core.worktree from per-worktree
761 strbuf_addf(&sb
, "%s/config.worktree", gitdir
);
762 git_config_from_file(read_worktree_config
, sb
.buf
, candidate
);
768 if (candidate
->is_bare
!= -1) {
769 is_bare_repository_cfg
= candidate
->is_bare
;
770 if (is_bare_repository_cfg
== 1)
771 inside_work_tree
= -1;
773 if (candidate
->work_tree
) {
774 free(git_work_tree_cfg
);
775 git_work_tree_cfg
= xstrdup(candidate
->work_tree
);
776 inside_work_tree
= -1;
783 int upgrade_repository_format(int target_version
)
785 struct strbuf sb
= STRBUF_INIT
;
786 struct strbuf err
= STRBUF_INIT
;
787 struct strbuf repo_version
= STRBUF_INIT
;
788 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
791 strbuf_git_common_path(&sb
, the_repository
, "config");
792 read_repository_format(&repo_fmt
, sb
.buf
);
795 if (repo_fmt
.version
>= target_version
) {
800 if (verify_repository_format(&repo_fmt
, &err
) < 0) {
801 ret
= error("cannot upgrade repository format from %d to %d: %s",
802 repo_fmt
.version
, target_version
, err
.buf
);
805 if (!repo_fmt
.version
&& repo_fmt
.unknown_extensions
.nr
) {
806 ret
= error("cannot upgrade repository format: "
807 "unknown extension %s",
808 repo_fmt
.unknown_extensions
.items
[0].string
);
812 strbuf_addf(&repo_version
, "%d", target_version
);
813 git_config_set("core.repositoryformatversion", repo_version
.buf
);
818 clear_repository_format(&repo_fmt
);
819 strbuf_release(&repo_version
);
820 strbuf_release(&err
);
824 static void init_repository_format(struct repository_format
*format
)
826 const struct repository_format fresh
= REPOSITORY_FORMAT_INIT
;
828 memcpy(format
, &fresh
, sizeof(fresh
));
831 int read_repository_format(struct repository_format
*format
, const char *path
)
833 clear_repository_format(format
);
834 git_config_from_file(check_repo_format
, path
, format
);
835 if (format
->version
== -1)
836 clear_repository_format(format
);
837 return format
->version
;
840 void clear_repository_format(struct repository_format
*format
)
842 string_list_clear(&format
->unknown_extensions
, 0);
843 string_list_clear(&format
->v1_only_extensions
, 0);
844 free(format
->work_tree
);
845 free(format
->partial_clone
);
846 init_repository_format(format
);
849 int verify_repository_format(const struct repository_format
*format
,
852 if (GIT_REPO_VERSION_READ
< format
->version
) {
853 strbuf_addf(err
, _("Expected git repo version <= %d, found %d"),
854 GIT_REPO_VERSION_READ
, format
->version
);
858 if (format
->version
>= 1 && format
->unknown_extensions
.nr
) {
861 strbuf_addstr(err
, Q_("unknown repository extension found:",
862 "unknown repository extensions found:",
863 format
->unknown_extensions
.nr
));
865 for (i
= 0; i
< format
->unknown_extensions
.nr
; i
++)
866 strbuf_addf(err
, "\n\t%s",
867 format
->unknown_extensions
.items
[i
].string
);
871 if (format
->version
== 0 && format
->v1_only_extensions
.nr
) {
875 Q_("repo version is 0, but v1-only extension found:",
876 "repo version is 0, but v1-only extensions found:",
877 format
->v1_only_extensions
.nr
));
879 for (i
= 0; i
< format
->v1_only_extensions
.nr
; i
++)
880 strbuf_addf(err
, "\n\t%s",
881 format
->v1_only_extensions
.items
[i
].string
);
888 void read_gitfile_error_die(int error_code
, const char *path
, const char *dir
)
890 switch (error_code
) {
891 case READ_GITFILE_ERR_STAT_FAILED
:
892 case READ_GITFILE_ERR_NOT_A_FILE
:
893 /* non-fatal; follow return path */
895 case READ_GITFILE_ERR_OPEN_FAILED
:
896 die_errno(_("error opening '%s'"), path
);
897 case READ_GITFILE_ERR_TOO_LARGE
:
898 die(_("too large to be a .git file: '%s'"), path
);
899 case READ_GITFILE_ERR_READ_FAILED
:
900 die(_("error reading %s"), path
);
901 case READ_GITFILE_ERR_INVALID_FORMAT
:
902 die(_("invalid gitfile format: %s"), path
);
903 case READ_GITFILE_ERR_NO_PATH
:
904 die(_("no path in gitfile: %s"), path
);
905 case READ_GITFILE_ERR_NOT_A_REPO
:
906 die(_("not a git repository: %s"), dir
);
908 BUG("unknown error code");
913 * Try to read the location of the git directory from the .git file,
914 * return path to git directory if found. The return value comes from
917 * On failure, if return_error_code is not NULL, return_error_code
918 * will be set to an error code and NULL will be returned. If
919 * return_error_code is NULL the function will die instead (for most
922 const char *read_gitfile_gently(const char *path
, int *return_error_code
)
924 const int max_file_size
= 1 << 20; /* 1MB */
932 static struct strbuf realpath
= STRBUF_INIT
;
934 if (stat(path
, &st
)) {
935 /* NEEDSWORK: discern between ENOENT vs other errors */
936 error_code
= READ_GITFILE_ERR_STAT_FAILED
;
939 if (!S_ISREG(st
.st_mode
)) {
940 error_code
= READ_GITFILE_ERR_NOT_A_FILE
;
943 if (st
.st_size
> max_file_size
) {
944 error_code
= READ_GITFILE_ERR_TOO_LARGE
;
947 fd
= open(path
, O_RDONLY
);
949 error_code
= READ_GITFILE_ERR_OPEN_FAILED
;
952 buf
= xmallocz(st
.st_size
);
953 len
= read_in_full(fd
, buf
, st
.st_size
);
955 if (len
!= st
.st_size
) {
956 error_code
= READ_GITFILE_ERR_READ_FAILED
;
959 if (!starts_with(buf
, "gitdir: ")) {
960 error_code
= READ_GITFILE_ERR_INVALID_FORMAT
;
963 while (buf
[len
- 1] == '\n' || buf
[len
- 1] == '\r')
966 error_code
= READ_GITFILE_ERR_NO_PATH
;
972 if (!is_absolute_path(dir
) && (slash
= strrchr(path
, '/'))) {
973 size_t pathlen
= slash
+1 - path
;
974 dir
= xstrfmt("%.*s%.*s", (int)pathlen
, path
,
975 (int)(len
- 8), buf
+ 8);
979 if (!is_git_directory(dir
)) {
980 error_code
= READ_GITFILE_ERR_NOT_A_REPO
;
984 strbuf_realpath(&realpath
, dir
, 1);
988 if (return_error_code
)
989 *return_error_code
= error_code
;
991 read_gitfile_error_die(error_code
, path
, dir
);
994 return error_code
? NULL
: path
;
997 static const char *setup_explicit_git_dir(const char *gitdirenv
,
999 struct repository_format
*repo_fmt
,
1002 const char *work_tree_env
= getenv(GIT_WORK_TREE_ENVIRONMENT
);
1003 const char *worktree
;
1007 if (PATH_MAX
- 40 < strlen(gitdirenv
))
1008 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT
);
1010 gitfile
= (char*)read_gitfile(gitdirenv
);
1012 gitfile
= xstrdup(gitfile
);
1013 gitdirenv
= gitfile
;
1016 if (!is_git_directory(gitdirenv
)) {
1022 die(_("not a git repository: '%s'"), gitdirenv
);
1025 if (check_repository_format_gently(gitdirenv
, repo_fmt
, nongit_ok
)) {
1030 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
1032 set_git_work_tree(work_tree_env
);
1033 else if (is_bare_repository_cfg
> 0) {
1034 if (git_work_tree_cfg
) {
1036 warning("core.bare and core.worktree do not make sense");
1037 work_tree_config_is_bogus
= 1;
1041 set_git_dir(gitdirenv
, 0);
1045 else if (git_work_tree_cfg
) { /* #6, #14 */
1046 if (is_absolute_path(git_work_tree_cfg
))
1047 set_git_work_tree(git_work_tree_cfg
);
1049 char *core_worktree
;
1050 if (chdir(gitdirenv
))
1051 die_errno(_("cannot chdir to '%s'"), gitdirenv
);
1052 if (chdir(git_work_tree_cfg
))
1053 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg
);
1054 core_worktree
= xgetcwd();
1055 if (chdir(cwd
->buf
))
1056 die_errno(_("cannot come back to cwd"));
1057 set_git_work_tree(core_worktree
);
1058 free(core_worktree
);
1061 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT
, 1)) {
1063 set_git_dir(gitdirenv
, 0);
1068 set_git_work_tree(".");
1070 /* set_git_work_tree() must have been called by now */
1071 worktree
= repo_get_work_tree(the_repository
);
1073 /* both repo_get_work_tree() and cwd are already normalized */
1074 if (!strcmp(cwd
->buf
, worktree
)) { /* cwd == worktree */
1075 set_git_dir(gitdirenv
, 0);
1080 offset
= dir_inside_of(cwd
->buf
, worktree
);
1081 if (offset
>= 0) { /* cwd inside worktree? */
1082 set_git_dir(gitdirenv
, 1);
1083 if (chdir(worktree
))
1084 die_errno(_("cannot chdir to '%s'"), worktree
);
1085 strbuf_addch(cwd
, '/');
1087 return cwd
->buf
+ offset
;
1090 /* cwd outside worktree */
1091 set_git_dir(gitdirenv
, 0);
1096 static const char *setup_discovered_git_dir(const char *gitdir
,
1097 struct strbuf
*cwd
, int offset
,
1098 struct repository_format
*repo_fmt
,
1101 if (check_repository_format_gently(gitdir
, repo_fmt
, nongit_ok
))
1104 /* --work-tree is set without --git-dir; use discovered one */
1105 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
1106 char *to_free
= NULL
;
1109 if (offset
!= cwd
->len
&& !is_absolute_path(gitdir
))
1110 gitdir
= to_free
= real_pathdup(gitdir
, 1);
1111 if (chdir(cwd
->buf
))
1112 die_errno(_("cannot come back to cwd"));
1113 ret
= setup_explicit_git_dir(gitdir
, cwd
, repo_fmt
, nongit_ok
);
1118 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1119 if (is_bare_repository_cfg
> 0) {
1120 set_git_dir(gitdir
, (offset
!= cwd
->len
));
1121 if (chdir(cwd
->buf
))
1122 die_errno(_("cannot come back to cwd"));
1126 /* #0, #1, #5, #8, #9, #12, #13 */
1127 set_git_work_tree(".");
1128 if (strcmp(gitdir
, DEFAULT_GIT_DIR_ENVIRONMENT
))
1129 set_git_dir(gitdir
, 0);
1131 inside_work_tree
= 1;
1132 if (offset
>= cwd
->len
)
1135 /* Make "offset" point past the '/' (already the case for root dirs) */
1136 if (offset
!= offset_1st_component(cwd
->buf
))
1138 /* Add a '/' at the end */
1139 strbuf_addch(cwd
, '/');
1140 return cwd
->buf
+ offset
;
1143 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1144 static const char *setup_bare_git_dir(struct strbuf
*cwd
, int offset
,
1145 struct repository_format
*repo_fmt
,
1150 if (check_repository_format_gently(".", repo_fmt
, nongit_ok
))
1153 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT
, "0", 1);
1155 /* --work-tree is set without --git-dir; use discovered one */
1156 if (getenv(GIT_WORK_TREE_ENVIRONMENT
) || git_work_tree_cfg
) {
1157 static const char *gitdir
;
1159 gitdir
= offset
== cwd
->len
? "." : xmemdupz(cwd
->buf
, offset
);
1160 if (chdir(cwd
->buf
))
1161 die_errno(_("cannot come back to cwd"));
1162 return setup_explicit_git_dir(gitdir
, cwd
, repo_fmt
, nongit_ok
);
1166 inside_work_tree
= 0;
1167 if (offset
!= cwd
->len
) {
1168 if (chdir(cwd
->buf
))
1169 die_errno(_("cannot come back to cwd"));
1170 root_len
= offset_1st_component(cwd
->buf
);
1171 strbuf_setlen(cwd
, offset
> root_len
? offset
: root_len
);
1172 set_git_dir(cwd
->buf
, 0);
1175 set_git_dir(".", 0);
1179 static dev_t
get_device_or_die(const char *path
, const char *prefix
, int prefix_len
)
1182 if (stat(path
, &buf
)) {
1183 die_errno(_("failed to stat '%*s%s%s'"),
1185 prefix
? prefix
: "",
1186 prefix
? "/" : "", path
);
1192 * A "string_list_each_func_t" function that canonicalizes an entry
1193 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1194 * discards it if unusable. The presence of an empty entry in
1195 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1196 * subsequent entries.
1198 static int canonicalize_ceiling_entry(struct string_list_item
*item
,
1201 int *empty_entry_found
= cb_data
;
1202 char *ceil
= item
->string
;
1205 *empty_entry_found
= 1;
1207 } else if (!is_absolute_path(ceil
)) {
1209 } else if (*empty_entry_found
) {
1210 /* Keep entry but do not canonicalize it */
1213 char *real_path
= real_pathdup(ceil
, 0);
1218 item
->string
= real_path
;
1223 struct safe_directory_data
{
1228 static int safe_directory_cb(const char *key
, const char *value
,
1229 const struct config_context
*ctx UNUSED
, void *d
)
1231 struct safe_directory_data
*data
= d
;
1233 if (strcmp(key
, "safe.directory"))
1236 if (!value
|| !*value
) {
1238 } else if (!strcmp(value
, "*")) {
1241 char *allowed
= NULL
;
1243 if (!git_config_pathname(&allowed
, key
, value
)) {
1244 char *normalized
= NULL
;
1247 * Setting safe.directory to a non-absolute path
1248 * makes little sense---it won't be relative to
1249 * the configuration file the item is defined in.
1250 * Except for ".", which means "if we are at the top
1251 * level of a repository, then it is OK", which is
1252 * slightly tighter than "*" that allows discovery.
1254 if (!is_absolute_path(allowed
) && strcmp(allowed
, ".")) {
1255 warning(_("safe.directory '%s' not absolute"),
1261 * A .gitconfig in $HOME may be shared across
1262 * different machines and safe.directory entries
1263 * may or may not exist as paths on all of these
1264 * machines. In other words, it is not a warning
1265 * worthy event when there is no such path on this
1266 * machine---the entry may be useful elsewhere.
1268 normalized
= real_pathdup(allowed
, 0);
1272 if (ends_with(normalized
, "/*")) {
1273 size_t len
= strlen(normalized
);
1274 if (!fspathncmp(normalized
, data
->path
, len
- 1))
1276 } else if (!fspathcmp(data
->path
, normalized
)) {
1289 * Check if a repository is safe, by verifying the ownership of the
1290 * worktree (if any), the git directory, and the gitfile (if any).
1292 * Exemptions for known-safe repositories can be added via `safe.directory`
1293 * config settings; for non-bare repositories, their worktree needs to be
1294 * added, for bare ones their git directory.
1296 static int ensure_valid_ownership(const char *gitfile
,
1297 const char *worktree
, const char *gitdir
,
1298 struct strbuf
*report
)
1300 struct safe_directory_data data
= { 0 };
1302 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1303 (!gitfile
|| is_path_owned_by_current_user(gitfile
, report
)) &&
1304 (!worktree
|| is_path_owned_by_current_user(worktree
, report
)) &&
1305 (!gitdir
|| is_path_owned_by_current_user(gitdir
, report
)))
1309 * normalize the data.path for comparison with normalized paths
1310 * that come from the configuration file. The path is unsafe
1311 * if it cannot be normalized.
1313 data
.path
= real_pathdup(worktree
? worktree
: gitdir
, 0);
1318 * data.path is the "path" that identifies the repository and it is
1319 * constant regardless of what failed above. data.is_safe should be
1320 * initialized to false, and might be changed by the callback.
1322 git_protected_config(safe_directory_cb
, &data
);
1325 return data
.is_safe
;
1328 void die_upon_dubious_ownership(const char *gitfile
, const char *worktree
,
1331 struct strbuf report
= STRBUF_INIT
, quoted
= STRBUF_INIT
;
1334 if (ensure_valid_ownership(gitfile
, worktree
, gitdir
, &report
))
1337 strbuf_complete(&report
, '\n');
1338 path
= gitfile
? gitfile
: gitdir
;
1339 sq_quote_buf_pretty("ed
, path
);
1341 die(_("detected dubious ownership in repository at '%s'\n"
1343 "To add an exception for this directory, call:\n"
1345 "\tgit config --global --add safe.directory %s"),
1346 path
, report
.buf
, quoted
.buf
);
1349 static int allowed_bare_repo_cb(const char *key
, const char *value
,
1350 const struct config_context
*ctx UNUSED
,
1353 enum allowed_bare_repo
*allowed_bare_repo
= d
;
1355 if (strcasecmp(key
, "safe.bareRepository"))
1358 if (!strcmp(value
, "explicit")) {
1359 *allowed_bare_repo
= ALLOWED_BARE_REPO_EXPLICIT
;
1362 if (!strcmp(value
, "all")) {
1363 *allowed_bare_repo
= ALLOWED_BARE_REPO_ALL
;
1369 static enum allowed_bare_repo
get_allowed_bare_repo(void)
1371 enum allowed_bare_repo result
= ALLOWED_BARE_REPO_ALL
;
1372 git_protected_config(allowed_bare_repo_cb
, &result
);
1376 static const char *allowed_bare_repo_to_string(
1377 enum allowed_bare_repo allowed_bare_repo
)
1379 switch (allowed_bare_repo
) {
1380 case ALLOWED_BARE_REPO_EXPLICIT
:
1382 case ALLOWED_BARE_REPO_ALL
:
1385 BUG("invalid allowed_bare_repo %d",
1391 static int is_implicit_bare_repo(const char *path
)
1394 * what we found is a ".git" directory at the root of
1397 if (ends_with_path_components(path
, ".git"))
1401 * we are inside $GIT_DIR of a secondary worktree of a
1402 * non-bare repository.
1404 if (strstr(path
, "/.git/worktrees/"))
1408 * we are inside $GIT_DIR of a worktree of a non-embedded
1409 * submodule, whose superproject is not a bare repository.
1411 if (strstr(path
, "/.git/modules/"))
1418 * We cannot decide in this function whether we are in the work tree or
1419 * not, since the config can only be read _after_ this function was called.
1421 * Also, we avoid changing any global state (such as the current working
1422 * directory) to allow early callers.
1424 * The directory where the search should start needs to be passed in via the
1425 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1426 * the directory where the search ended, and `gitdir` will contain the path of
1427 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1428 * is relative to `dir` (i.e. *not* necessarily the cwd).
1430 static enum discovery_result
setup_git_directory_gently_1(struct strbuf
*dir
,
1431 struct strbuf
*gitdir
,
1432 struct strbuf
*report
,
1435 const char *env_ceiling_dirs
= getenv(CEILING_DIRECTORIES_ENVIRONMENT
);
1436 struct string_list ceiling_dirs
= STRING_LIST_INIT_DUP
;
1437 const char *gitdirenv
;
1438 int ceil_offset
= -1, min_offset
= offset_1st_component(dir
->buf
);
1439 dev_t current_device
= 0;
1440 int one_filesystem
= 1;
1443 * If GIT_DIR is set explicitly, we're not going
1444 * to do any discovery, but we still do repository
1447 gitdirenv
= getenv(GIT_DIR_ENVIRONMENT
);
1449 strbuf_addstr(gitdir
, gitdirenv
);
1450 return GIT_DIR_EXPLICIT
;
1453 if (env_ceiling_dirs
) {
1454 int empty_entry_found
= 0;
1456 string_list_split(&ceiling_dirs
, env_ceiling_dirs
, PATH_SEP
, -1);
1457 filter_string_list(&ceiling_dirs
, 0,
1458 canonicalize_ceiling_entry
, &empty_entry_found
);
1459 ceil_offset
= longest_ancestor_length(dir
->buf
, &ceiling_dirs
);
1460 string_list_clear(&ceiling_dirs
, 0);
1463 if (ceil_offset
< 0)
1464 ceil_offset
= min_offset
- 2;
1466 if (min_offset
&& min_offset
== dir
->len
&&
1467 !is_dir_sep(dir
->buf
[min_offset
- 1])) {
1468 strbuf_addch(dir
, '/');
1473 * Test in the following order (relative to the dir):
1474 * - .git (file containing "gitdir: <path>")
1483 one_filesystem
= !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1485 current_device
= get_device_or_die(dir
->buf
, NULL
, 0);
1487 int offset
= dir
->len
, error_code
= 0;
1488 char *gitdir_path
= NULL
;
1489 char *gitfile
= NULL
;
1491 if (offset
> min_offset
)
1492 strbuf_addch(dir
, '/');
1493 strbuf_addstr(dir
, DEFAULT_GIT_DIR_ENVIRONMENT
);
1494 gitdirenv
= read_gitfile_gently(dir
->buf
, die_on_error
?
1495 NULL
: &error_code
);
1498 error_code
== READ_GITFILE_ERR_NOT_A_FILE
) {
1499 /* NEEDSWORK: fail if .git is not file nor dir */
1500 if (is_git_directory(dir
->buf
)) {
1501 gitdirenv
= DEFAULT_GIT_DIR_ENVIRONMENT
;
1502 gitdir_path
= xstrdup(dir
->buf
);
1504 } else if (error_code
!= READ_GITFILE_ERR_STAT_FAILED
)
1505 return GIT_DIR_INVALID_GITFILE
;
1507 gitfile
= xstrdup(dir
->buf
);
1509 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1510 * to check that directory for a repository.
1511 * Now trim that tentative addition away, because we want to
1512 * focus on the real directory we are in.
1514 strbuf_setlen(dir
, offset
);
1516 enum discovery_result ret
;
1517 const char *gitdir_candidate
=
1518 gitdir_path
? gitdir_path
: gitdirenv
;
1520 if (ensure_valid_ownership(gitfile
, dir
->buf
,
1521 gitdir_candidate
, report
)) {
1522 strbuf_addstr(gitdir
, gitdirenv
);
1523 ret
= GIT_DIR_DISCOVERED
;
1525 ret
= GIT_DIR_INVALID_OWNERSHIP
;
1528 * Earlier, during discovery, we might have allocated
1529 * string copies for gitdir_path or gitfile so make
1530 * sure we don't leak by freeing them now, before
1531 * leaving the loop and function.
1533 * Note: gitdirenv will be non-NULL whenever these are
1534 * allocated, therefore we need not take care of releasing
1535 * them outside of this conditional block.
1543 if (is_git_directory(dir
->buf
)) {
1544 trace2_data_string("setup", NULL
, "implicit-bare-repository", dir
->buf
);
1545 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT
&&
1546 !is_implicit_bare_repo(dir
->buf
))
1547 return GIT_DIR_DISALLOWED_BARE
;
1548 if (!ensure_valid_ownership(NULL
, NULL
, dir
->buf
, report
))
1549 return GIT_DIR_INVALID_OWNERSHIP
;
1550 strbuf_addstr(gitdir
, ".");
1551 return GIT_DIR_BARE
;
1554 if (offset
<= min_offset
)
1555 return GIT_DIR_HIT_CEILING
;
1557 while (--offset
> ceil_offset
&& !is_dir_sep(dir
->buf
[offset
]))
1559 if (offset
<= ceil_offset
)
1560 return GIT_DIR_HIT_CEILING
;
1562 strbuf_setlen(dir
, offset
> min_offset
? offset
: min_offset
);
1563 if (one_filesystem
&&
1564 current_device
!= get_device_or_die(dir
->buf
, NULL
, offset
))
1565 return GIT_DIR_HIT_MOUNT_POINT
;
1569 enum discovery_result
discover_git_directory_reason(struct strbuf
*commondir
,
1570 struct strbuf
*gitdir
)
1572 struct strbuf dir
= STRBUF_INIT
, err
= STRBUF_INIT
;
1573 size_t gitdir_offset
= gitdir
->len
, cwd_len
;
1574 size_t commondir_offset
= commondir
->len
;
1575 struct repository_format candidate
= REPOSITORY_FORMAT_INIT
;
1576 enum discovery_result result
;
1578 if (strbuf_getcwd(&dir
))
1579 return GIT_DIR_CWD_FAILURE
;
1582 result
= setup_git_directory_gently_1(&dir
, gitdir
, NULL
, 0);
1584 strbuf_release(&dir
);
1589 * The returned gitdir is relative to dir, and if dir does not reflect
1590 * the current working directory, we simply make the gitdir absolute.
1592 if (dir
.len
< cwd_len
&& !is_absolute_path(gitdir
->buf
+ gitdir_offset
)) {
1593 /* Avoid a trailing "/." */
1594 if (!strcmp(".", gitdir
->buf
+ gitdir_offset
))
1595 strbuf_setlen(gitdir
, gitdir_offset
);
1597 strbuf_addch(&dir
, '/');
1598 strbuf_insert(gitdir
, gitdir_offset
, dir
.buf
, dir
.len
);
1601 get_common_dir(commondir
, gitdir
->buf
+ gitdir_offset
);
1604 strbuf_addf(&dir
, "%s/config", commondir
->buf
+ commondir_offset
);
1605 read_repository_format(&candidate
, dir
.buf
);
1606 strbuf_release(&dir
);
1608 if (verify_repository_format(&candidate
, &err
) < 0) {
1609 warning("ignoring git dir '%s': %s",
1610 gitdir
->buf
+ gitdir_offset
, err
.buf
);
1611 strbuf_release(&err
);
1612 strbuf_setlen(commondir
, commondir_offset
);
1613 strbuf_setlen(gitdir
, gitdir_offset
);
1614 clear_repository_format(&candidate
);
1615 return GIT_DIR_INVALID_FORMAT
;
1618 clear_repository_format(&candidate
);
1622 void setup_git_env(const char *git_dir
)
1624 char *git_replace_ref_base
;
1625 const char *shallow_file
;
1626 const char *replace_ref_base
;
1627 struct set_gitdir_args args
= { NULL
};
1628 struct strvec to_free
= STRVEC_INIT
;
1630 args
.commondir
= getenv_safe(&to_free
, GIT_COMMON_DIR_ENVIRONMENT
);
1631 args
.object_dir
= getenv_safe(&to_free
, DB_ENVIRONMENT
);
1632 args
.graft_file
= getenv_safe(&to_free
, GRAFT_ENVIRONMENT
);
1633 args
.index_file
= getenv_safe(&to_free
, INDEX_ENVIRONMENT
);
1634 args
.alternate_db
= getenv_safe(&to_free
, ALTERNATE_DB_ENVIRONMENT
);
1635 if (getenv(GIT_QUARANTINE_ENVIRONMENT
)) {
1636 args
.disable_ref_updates
= 1;
1639 repo_set_gitdir(the_repository
, git_dir
, &args
);
1640 strvec_clear(&to_free
);
1642 if (getenv(NO_REPLACE_OBJECTS_ENVIRONMENT
))
1643 disable_replace_refs();
1644 replace_ref_base
= getenv(GIT_REPLACE_REF_BASE_ENVIRONMENT
);
1645 git_replace_ref_base
= xstrdup(replace_ref_base
? replace_ref_base
1647 update_ref_namespace(NAMESPACE_REPLACE
, git_replace_ref_base
);
1649 shallow_file
= getenv(GIT_SHALLOW_FILE_ENVIRONMENT
);
1651 set_alternate_shallow_file(the_repository
, shallow_file
, 0);
1653 if (git_env_bool(NO_LAZY_FETCH_ENVIRONMENT
, 0))
1654 fetch_if_missing
= 0;
1657 static void set_git_dir_1(const char *path
)
1659 xsetenv(GIT_DIR_ENVIRONMENT
, path
, 1);
1660 setup_git_env(path
);
1663 static void update_relative_gitdir(const char *name UNUSED
,
1664 const char *old_cwd
,
1665 const char *new_cwd
,
1668 char *path
= reparent_relative_path(old_cwd
, new_cwd
,
1669 repo_get_git_dir(the_repository
));
1670 struct tmp_objdir
*tmp_objdir
= tmp_objdir_unapply_primary_odb();
1672 trace_printf_key(&trace_setup_key
,
1673 "setup: move $GIT_DIR to '%s'",
1675 set_git_dir_1(path
);
1677 tmp_objdir_reapply_primary_odb(tmp_objdir
, old_cwd
, new_cwd
);
1681 void set_git_dir(const char *path
, int make_realpath
)
1683 struct strbuf realpath
= STRBUF_INIT
;
1685 if (make_realpath
) {
1686 strbuf_realpath(&realpath
, path
, 1);
1687 path
= realpath
.buf
;
1690 set_git_dir_1(path
);
1691 if (!is_absolute_path(path
))
1692 chdir_notify_register(NULL
, update_relative_gitdir
, NULL
);
1694 strbuf_release(&realpath
);
1697 static int git_work_tree_initialized
;
1700 * Note. This works only before you used a work tree. This was added
1701 * primarily to support git-clone to work in a new repository it just
1702 * created, and is not meant to flip between different work trees.
1704 void set_git_work_tree(const char *new_work_tree
)
1706 if (git_work_tree_initialized
) {
1707 struct strbuf realpath
= STRBUF_INIT
;
1709 strbuf_realpath(&realpath
, new_work_tree
, 1);
1710 new_work_tree
= realpath
.buf
;
1711 if (strcmp(new_work_tree
, the_repository
->worktree
))
1712 die("internal error: work tree has already been set\n"
1713 "Current worktree: %s\nNew worktree: %s",
1714 the_repository
->worktree
, new_work_tree
);
1715 strbuf_release(&realpath
);
1718 git_work_tree_initialized
= 1;
1719 repo_set_worktree(the_repository
, new_work_tree
);
1722 const char *setup_git_directory_gently(int *nongit_ok
)
1724 static struct strbuf cwd
= STRBUF_INIT
;
1725 struct strbuf dir
= STRBUF_INIT
, gitdir
= STRBUF_INIT
, report
= STRBUF_INIT
;
1726 const char *prefix
= NULL
;
1727 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
1730 * We may have read an incomplete configuration before
1731 * setting-up the git directory. If so, clear the cache so
1732 * that the next queries to the configuration reload complete
1733 * configuration (including the per-repo config file that we
1734 * ignored previously).
1739 * Let's assume that we are in a git repository.
1740 * If it turns out later that we are somewhere else, the value will be
1741 * updated accordingly.
1746 if (strbuf_getcwd(&cwd
))
1747 die_errno(_("Unable to read current working directory"));
1748 strbuf_addbuf(&dir
, &cwd
);
1750 switch (setup_git_directory_gently_1(&dir
, &gitdir
, &report
, 1)) {
1751 case GIT_DIR_EXPLICIT
:
1752 prefix
= setup_explicit_git_dir(gitdir
.buf
, &cwd
, &repo_fmt
, nongit_ok
);
1754 case GIT_DIR_DISCOVERED
:
1755 if (dir
.len
< cwd
.len
&& chdir(dir
.buf
))
1756 die(_("cannot change to '%s'"), dir
.buf
);
1757 prefix
= setup_discovered_git_dir(gitdir
.buf
, &cwd
, dir
.len
,
1758 &repo_fmt
, nongit_ok
);
1761 if (dir
.len
< cwd
.len
&& chdir(dir
.buf
))
1762 die(_("cannot change to '%s'"), dir
.buf
);
1763 prefix
= setup_bare_git_dir(&cwd
, dir
.len
, &repo_fmt
, nongit_ok
);
1765 case GIT_DIR_HIT_CEILING
:
1767 die(_("not a git repository (or any of the parent directories): %s"),
1768 DEFAULT_GIT_DIR_ENVIRONMENT
);
1771 case GIT_DIR_HIT_MOUNT_POINT
:
1773 die(_("not a git repository (or any parent up to mount point %s)\n"
1774 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1778 case GIT_DIR_INVALID_OWNERSHIP
:
1780 struct strbuf quoted
= STRBUF_INIT
;
1782 strbuf_complete(&report
, '\n');
1783 sq_quote_buf_pretty("ed
, dir
.buf
);
1784 die(_("detected dubious ownership in repository at '%s'\n"
1786 "To add an exception for this directory, call:\n"
1788 "\tgit config --global --add safe.directory %s"),
1789 dir
.buf
, report
.buf
, quoted
.buf
);
1793 case GIT_DIR_DISALLOWED_BARE
:
1795 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1797 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1801 case GIT_DIR_CWD_FAILURE
:
1802 case GIT_DIR_INVALID_FORMAT
:
1804 * As a safeguard against setup_git_directory_gently_1 returning
1805 * these values, fallthrough to BUG. Otherwise it is possible to
1806 * set startup_info->have_repository to 1 when we did nothing to
1807 * find a repository.
1810 BUG("unhandled setup_git_directory_gently_1() result");
1814 * At this point, nongit_ok is stable. If it is non-NULL and points
1815 * to a non-zero value, then this means that we haven't found a
1816 * repository and that the caller expects startup_info to reflect
1819 * Regardless of the state of nongit_ok, startup_info->prefix and
1820 * the GIT_PREFIX environment variable must always match. For details
1821 * see Documentation/config/alias.txt.
1823 if (nongit_ok
&& *nongit_ok
)
1824 startup_info
->have_repository
= 0;
1826 startup_info
->have_repository
= 1;
1829 * Not all paths through the setup code will call 'set_git_dir()' (which
1830 * directly sets up the environment) so in order to guarantee that the
1831 * environment is in a consistent state after setup, explicitly setup
1832 * the environment if we have a repository.
1834 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1835 * code paths so we also need to explicitly setup the environment if
1836 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1837 * GIT_DIR values at some point in the future.
1839 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1840 startup_info
->have_repository
||
1841 /* GIT_DIR_EXPLICIT */
1842 getenv(GIT_DIR_ENVIRONMENT
)) {
1843 if (!the_repository
->gitdir
) {
1844 const char *gitdir
= getenv(GIT_DIR_ENVIRONMENT
);
1846 gitdir
= DEFAULT_GIT_DIR_ENVIRONMENT
;
1847 setup_git_env(gitdir
);
1849 if (startup_info
->have_repository
) {
1850 repo_set_hash_algo(the_repository
, repo_fmt
.hash_algo
);
1851 repo_set_compat_hash_algo(the_repository
,
1852 repo_fmt
.compat_hash_algo
);
1853 repo_set_ref_storage_format(the_repository
,
1854 repo_fmt
.ref_storage_format
);
1855 the_repository
->repository_format_worktree_config
=
1856 repo_fmt
.worktree_config
;
1857 /* take ownership of repo_fmt.partial_clone */
1858 the_repository
->repository_format_partial_clone
=
1859 repo_fmt
.partial_clone
;
1860 repo_fmt
.partial_clone
= NULL
;
1864 * Since precompose_string_if_needed() needs to look at
1865 * the core.precomposeunicode configuration, this
1866 * has to happen after the above block that finds
1867 * out where the repository is, i.e. a preparation
1868 * for calling git_config_get_bool().
1871 prefix
= precompose_string_if_needed(prefix
);
1872 startup_info
->prefix
= prefix
;
1873 setenv(GIT_PREFIX_ENVIRONMENT
, prefix
, 1);
1875 startup_info
->prefix
= NULL
;
1876 setenv(GIT_PREFIX_ENVIRONMENT
, "", 1);
1879 setup_original_cwd();
1881 strbuf_release(&dir
);
1882 strbuf_release(&gitdir
);
1883 strbuf_release(&report
);
1884 clear_repository_format(&repo_fmt
);
1889 int git_config_perm(const char *var
, const char *value
)
1897 if (!strcmp(value
, "umask"))
1899 if (!strcmp(value
, "group"))
1901 if (!strcmp(value
, "all") ||
1902 !strcmp(value
, "world") ||
1903 !strcmp(value
, "everybody"))
1904 return PERM_EVERYBODY
;
1906 /* Parse octal numbers */
1907 i
= strtol(value
, &endptr
, 8);
1909 /* If not an octal number, maybe true/false? */
1911 return git_config_bool(var
, value
) ? PERM_GROUP
: PERM_UMASK
;
1914 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1915 * a chmod value to restrict to.
1918 case PERM_UMASK
: /* 0 */
1920 case OLD_PERM_GROUP
: /* 1 */
1922 case OLD_PERM_EVERYBODY
: /* 2 */
1923 return PERM_EVERYBODY
;
1926 /* A filemode value was given: 0xxx */
1928 if ((i
& 0600) != 0600)
1929 die(_("problem with core.sharedRepository filemode value "
1930 "(0%.3o).\nThe owner of files must always have "
1931 "read and write permissions."), i
);
1934 * Mask filemode value. Others can not get write permission.
1935 * x flags for directories are handled separately.
1940 void check_repository_format(struct repository_format
*fmt
)
1942 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
1945 check_repository_format_gently(repo_get_git_dir(the_repository
), fmt
, NULL
);
1946 startup_info
->have_repository
= 1;
1947 repo_set_hash_algo(the_repository
, fmt
->hash_algo
);
1948 repo_set_compat_hash_algo(the_repository
, fmt
->compat_hash_algo
);
1949 repo_set_ref_storage_format(the_repository
,
1950 fmt
->ref_storage_format
);
1951 the_repository
->repository_format_worktree_config
=
1952 fmt
->worktree_config
;
1953 the_repository
->repository_format_partial_clone
=
1954 xstrdup_or_null(fmt
->partial_clone
);
1955 clear_repository_format(&repo_fmt
);
1959 * Returns the "prefix", a path to the current working directory
1960 * relative to the work tree root, or NULL, if the current working
1961 * directory is not a strict subdirectory of the work tree root. The
1962 * prefix always ends with a '/' character.
1964 const char *setup_git_directory(void)
1966 return setup_git_directory_gently(NULL
);
1969 const char *resolve_gitdir_gently(const char *suspect
, int *return_error_code
)
1971 if (is_git_directory(suspect
))
1973 return read_gitfile_gently(suspect
, return_error_code
);
1976 /* if any standard file descriptor is missing open it to /dev/null */
1977 void sanitize_stdfds(void)
1979 int fd
= xopen("/dev/null", O_RDWR
);
1988 #ifdef NO_POSIX_GOODIES
1996 die_errno(_("fork failed"));
2001 die_errno(_("setsid failed"));
2010 struct template_dir_cb_data
{
2015 static int template_dir_cb(const char *key
, const char *value
,
2016 const struct config_context
*ctx UNUSED
, void *d
)
2018 struct template_dir_cb_data
*data
= d
;
2020 if (strcmp(key
, "init.templatedir"))
2028 FREE_AND_NULL(data
->path
);
2029 if (!git_config_pathname(&path
, key
, value
))
2030 data
->path
= path
? path
: xstrdup(value
);
2036 const char *get_template_dir(const char *option_template
)
2038 const char *template_dir
= option_template
;
2041 template_dir
= getenv(TEMPLATE_DIR_ENVIRONMENT
);
2042 if (!template_dir
) {
2043 static struct template_dir_cb_data data
;
2045 if (!data
.initialized
) {
2046 git_protected_config(template_dir_cb
, &data
);
2047 data
.initialized
= 1;
2049 template_dir
= data
.path
;
2051 if (!template_dir
) {
2055 dir
= system_path(DEFAULT_GIT_TEMPLATE_DIR
);
2058 return template_dir
;
2061 #ifdef NO_TRUSTABLE_FILEMODE
2062 #define TEST_FILEMODE 0
2064 #define TEST_FILEMODE 1
2067 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
2069 static void copy_templates_1(struct strbuf
*path
, struct strbuf
*template_path
,
2072 size_t path_baselen
= path
->len
;
2073 size_t template_baselen
= template_path
->len
;
2076 /* Note: if ".git/hooks" file exists in the repository being
2077 * re-initialized, /etc/core-git/templates/hooks/update would
2078 * cause "git init" to fail here. I think this is sane but
2079 * it means that the set of templates we ship by default, along
2080 * with the way the namespace under .git/ is organized, should
2081 * be really carefully chosen.
2083 safe_create_dir(path
->buf
, 1);
2084 while ((de
= readdir(dir
)) != NULL
) {
2085 struct stat st_git
, st_template
;
2088 strbuf_setlen(path
, path_baselen
);
2089 strbuf_setlen(template_path
, template_baselen
);
2091 if (de
->d_name
[0] == '.')
2093 strbuf_addstr(path
, de
->d_name
);
2094 strbuf_addstr(template_path
, de
->d_name
);
2095 if (lstat(path
->buf
, &st_git
)) {
2096 if (errno
!= ENOENT
)
2097 die_errno(_("cannot stat '%s'"), path
->buf
);
2102 if (lstat(template_path
->buf
, &st_template
))
2103 die_errno(_("cannot stat template '%s'"), template_path
->buf
);
2105 if (S_ISDIR(st_template
.st_mode
)) {
2106 DIR *subdir
= opendir(template_path
->buf
);
2108 die_errno(_("cannot opendir '%s'"), template_path
->buf
);
2109 strbuf_addch(path
, '/');
2110 strbuf_addch(template_path
, '/');
2111 copy_templates_1(path
, template_path
, subdir
);
2116 else if (S_ISLNK(st_template
.st_mode
)) {
2117 struct strbuf lnk
= STRBUF_INIT
;
2118 if (strbuf_readlink(&lnk
, template_path
->buf
,
2119 st_template
.st_size
) < 0)
2120 die_errno(_("cannot readlink '%s'"), template_path
->buf
);
2121 if (symlink(lnk
.buf
, path
->buf
))
2122 die_errno(_("cannot symlink '%s' '%s'"),
2123 lnk
.buf
, path
->buf
);
2124 strbuf_release(&lnk
);
2126 else if (S_ISREG(st_template
.st_mode
)) {
2127 if (copy_file(path
->buf
, template_path
->buf
, st_template
.st_mode
))
2128 die_errno(_("cannot copy '%s' to '%s'"),
2129 template_path
->buf
, path
->buf
);
2132 error(_("ignoring template %s"), template_path
->buf
);
2136 static void copy_templates(const char *option_template
)
2138 const char *template_dir
= get_template_dir(option_template
);
2139 struct strbuf path
= STRBUF_INIT
;
2140 struct strbuf template_path
= STRBUF_INIT
;
2141 size_t template_len
;
2142 struct repository_format template_format
= REPOSITORY_FORMAT_INIT
;
2143 struct strbuf err
= STRBUF_INIT
;
2145 char *to_free
= NULL
;
2147 if (!template_dir
|| !*template_dir
)
2150 strbuf_addstr(&template_path
, template_dir
);
2151 strbuf_complete(&template_path
, '/');
2152 template_len
= template_path
.len
;
2154 dir
= opendir(template_path
.buf
);
2156 warning(_("templates not found in %s"), template_dir
);
2160 /* Make sure that template is from the correct vintage */
2161 strbuf_addstr(&template_path
, "config");
2162 read_repository_format(&template_format
, template_path
.buf
);
2163 strbuf_setlen(&template_path
, template_len
);
2166 * No mention of version at all is OK, but anything else should be
2169 if (template_format
.version
>= 0 &&
2170 verify_repository_format(&template_format
, &err
) < 0) {
2171 warning(_("not copying templates from '%s': %s"),
2172 template_dir
, err
.buf
);
2173 strbuf_release(&err
);
2174 goto close_free_return
;
2177 strbuf_addstr(&path
, repo_get_common_dir(the_repository
));
2178 strbuf_complete(&path
, '/');
2179 copy_templates_1(&path
, &template_path
, dir
);
2184 strbuf_release(&path
);
2185 strbuf_release(&template_path
);
2186 clear_repository_format(&template_format
);
2190 * If the git_dir is not directly inside the working tree, then git will not
2191 * find it by default, and we need to set the worktree explicitly.
2193 static int needs_work_tree_config(const char *git_dir
, const char *work_tree
)
2195 if (!strcmp(work_tree
, "/") && !strcmp(git_dir
, "/.git"))
2197 if (skip_prefix(git_dir
, work_tree
, &git_dir
) &&
2198 !strcmp(git_dir
, "/.git"))
2203 void initialize_repository_version(int hash_algo
,
2204 enum ref_storage_format ref_storage_format
,
2207 char repo_version_string
[10];
2208 int repo_version
= GIT_REPO_VERSION
;
2211 * Note that we initialize the repository version to 1 when the ref
2212 * storage format is unknown. This is on purpose so that we can add the
2213 * correct object format to the config during git-clone(1). The format
2214 * version will get adjusted by git-clone(1) once it has learned about
2215 * the remote repository's format.
2217 if (hash_algo
!= GIT_HASH_SHA1
||
2218 ref_storage_format
!= REF_STORAGE_FORMAT_FILES
)
2219 repo_version
= GIT_REPO_VERSION_READ
;
2221 /* This forces creation of new config file */
2222 xsnprintf(repo_version_string
, sizeof(repo_version_string
),
2223 "%d", repo_version
);
2224 git_config_set("core.repositoryformatversion", repo_version_string
);
2226 if (hash_algo
!= GIT_HASH_SHA1
&& hash_algo
!= GIT_HASH_UNKNOWN
)
2227 git_config_set("extensions.objectformat",
2228 hash_algos
[hash_algo
].name
);
2230 git_config_set_gently("extensions.objectformat", NULL
);
2232 if (ref_storage_format
!= REF_STORAGE_FORMAT_FILES
)
2233 git_config_set("extensions.refstorage",
2234 ref_storage_format_to_name(ref_storage_format
));
2236 git_config_set_gently("extensions.refstorage", NULL
);
2239 static int is_reinit(void)
2241 struct strbuf buf
= STRBUF_INIT
;
2245 git_path_buf(&buf
, "HEAD");
2246 ret
= !access(buf
.buf
, R_OK
) || readlink(buf
.buf
, junk
, sizeof(junk
) - 1) != -1;
2247 strbuf_release(&buf
);
2251 void create_reference_database(enum ref_storage_format ref_storage_format
,
2252 const char *initial_branch
, int quiet
)
2254 struct strbuf err
= STRBUF_INIT
;
2255 char *to_free
= NULL
;
2256 int reinit
= is_reinit();
2258 repo_set_ref_storage_format(the_repository
, ref_storage_format
);
2259 if (ref_store_create_on_disk(get_main_ref_store(the_repository
), 0, &err
))
2260 die("failed to set up refs db: %s", err
.buf
);
2263 * Point the HEAD symref to the initial branch with if HEAD does
2269 if (!initial_branch
)
2270 initial_branch
= to_free
=
2271 repo_default_branch_name(the_repository
, quiet
);
2273 ref
= xstrfmt("refs/heads/%s", initial_branch
);
2274 if (check_refname_format(ref
, 0) < 0)
2275 die(_("invalid initial branch name: '%s'"),
2278 if (refs_update_symref(get_main_ref_store(the_repository
), "HEAD", ref
, NULL
) < 0)
2283 if (reinit
&& initial_branch
)
2284 warning(_("re-init: ignored --initial-branch=%s"),
2287 strbuf_release(&err
);
2291 static int create_default_files(const char *template_path
,
2292 const char *original_git_dir
,
2293 const struct repository_format
*fmt
,
2294 int init_shared_repository
)
2297 struct strbuf buf
= STRBUF_INIT
;
2301 const char *work_tree
= repo_get_work_tree(the_repository
);
2304 * First copy the templates -- we might have the default
2305 * config file there, in which case we would want to read
2306 * from it after installing.
2308 * Before reading that config, we also need to clear out any cached
2309 * values (since we've just potentially changed what's available on
2312 copy_templates(template_path
);
2314 reset_shared_repository();
2315 git_config(git_default_config
, NULL
);
2317 reinit
= is_reinit();
2320 * We must make sure command-line options continue to override any
2321 * values we might have just re-read from the config.
2323 if (init_shared_repository
!= -1)
2324 set_shared_repository(init_shared_repository
);
2326 is_bare_repository_cfg
= !work_tree
;
2329 * We would have created the above under user's umask -- under
2330 * shared-repository settings, we would need to fix them up.
2332 if (get_shared_repository()) {
2333 adjust_shared_perm(repo_get_git_dir(the_repository
));
2336 initialize_repository_version(fmt
->hash_algo
, fmt
->ref_storage_format
, 0);
2338 /* Check filemode trustability */
2339 path
= git_path_buf(&buf
, "config");
2340 filemode
= TEST_FILEMODE
;
2341 if (TEST_FILEMODE
&& !lstat(path
, &st1
)) {
2343 filemode
= (!chmod(path
, st1
.st_mode
^ S_IXUSR
) &&
2344 !lstat(path
, &st2
) &&
2345 st1
.st_mode
!= st2
.st_mode
&&
2346 !chmod(path
, st1
.st_mode
));
2347 if (filemode
&& !reinit
&& (st1
.st_mode
& S_IXUSR
))
2350 git_config_set("core.filemode", filemode
? "true" : "false");
2352 if (is_bare_repository())
2353 git_config_set("core.bare", "true");
2355 git_config_set("core.bare", "false");
2356 /* allow template config file to override the default */
2357 if (repo_settings_get_log_all_ref_updates(the_repository
) == LOG_REFS_UNSET
)
2358 git_config_set("core.logallrefupdates", "true");
2359 if (needs_work_tree_config(original_git_dir
, work_tree
))
2360 git_config_set("core.worktree", work_tree
);
2364 /* Check if symlink is supported in the work tree */
2365 path
= git_path_buf(&buf
, "tXXXXXX");
2366 if (!close(xmkstemp(path
)) &&
2368 !symlink("testing", path
) &&
2369 !lstat(path
, &st1
) &&
2370 S_ISLNK(st1
.st_mode
))
2371 unlink(path
); /* good */
2373 git_config_set("core.symlinks", "false");
2375 /* Check if the filesystem is case-insensitive */
2376 path
= git_path_buf(&buf
, "CoNfIg");
2377 if (!access(path
, F_OK
))
2378 git_config_set("core.ignorecase", "true");
2379 probe_utf8_pathname_composition();
2382 strbuf_release(&buf
);
2386 static void create_object_directory(void)
2388 struct strbuf path
= STRBUF_INIT
;
2391 strbuf_addstr(&path
, repo_get_object_directory(the_repository
));
2394 safe_create_dir(path
.buf
, 1);
2396 strbuf_setlen(&path
, baselen
);
2397 strbuf_addstr(&path
, "/pack");
2398 safe_create_dir(path
.buf
, 1);
2400 strbuf_setlen(&path
, baselen
);
2401 strbuf_addstr(&path
, "/info");
2402 safe_create_dir(path
.buf
, 1);
2404 strbuf_release(&path
);
2407 static void separate_git_dir(const char *git_dir
, const char *git_link
)
2411 if (!stat(git_link
, &st
)) {
2414 if (S_ISREG(st
.st_mode
))
2415 src
= read_gitfile(git_link
);
2416 else if (S_ISDIR(st
.st_mode
))
2419 die(_("unable to handle file type %d"), (int)st
.st_mode
);
2421 if (rename(src
, git_dir
))
2422 die_errno(_("unable to move %s to %s"), src
, git_dir
);
2423 repair_worktrees(NULL
, NULL
);
2426 write_file(git_link
, "gitdir: %s", git_dir
);
2429 struct default_format_config
{
2431 enum ref_storage_format ref_format
;
2434 static int read_default_format_config(const char *key
, const char *value
,
2435 const struct config_context
*ctx UNUSED
,
2438 struct default_format_config
*cfg
= payload
;
2442 if (!strcmp(key
, "init.defaultobjectformat")) {
2443 ret
= git_config_string(&str
, key
, value
);
2446 cfg
->hash
= hash_algo_by_name(str
);
2447 if (cfg
->hash
== GIT_HASH_UNKNOWN
)
2448 warning(_("unknown hash algorithm '%s'"), str
);
2452 if (!strcmp(key
, "init.defaultrefformat")) {
2453 ret
= git_config_string(&str
, key
, value
);
2456 cfg
->ref_format
= ref_storage_format_by_name(str
);
2457 if (cfg
->ref_format
== REF_STORAGE_FORMAT_UNKNOWN
)
2458 warning(_("unknown ref storage format '%s'"), str
);
2468 static void repository_format_configure(struct repository_format
*repo_fmt
,
2469 int hash
, enum ref_storage_format ref_format
)
2471 struct default_format_config cfg
= {
2472 .hash
= GIT_HASH_UNKNOWN
,
2473 .ref_format
= REF_STORAGE_FORMAT_UNKNOWN
,
2475 struct config_options opts
= {
2476 .respect_includes
= 1,
2478 .ignore_worktree
= 1,
2482 config_with_options(read_default_format_config
, &cfg
, NULL
, NULL
, &opts
);
2485 * If we already have an initialized repo, don't allow the user to
2486 * specify a different algorithm, as that could cause corruption.
2487 * Otherwise, if the user has specified one on the command line, use it.
2489 env
= getenv(GIT_DEFAULT_HASH_ENVIRONMENT
);
2490 if (repo_fmt
->version
>= 0 && hash
!= GIT_HASH_UNKNOWN
&& hash
!= repo_fmt
->hash_algo
)
2491 die(_("attempt to reinitialize repository with different hash"));
2492 else if (hash
!= GIT_HASH_UNKNOWN
)
2493 repo_fmt
->hash_algo
= hash
;
2495 int env_algo
= hash_algo_by_name(env
);
2496 if (env_algo
== GIT_HASH_UNKNOWN
)
2497 die(_("unknown hash algorithm '%s'"), env
);
2498 repo_fmt
->hash_algo
= env_algo
;
2499 } else if (cfg
.hash
!= GIT_HASH_UNKNOWN
) {
2500 repo_fmt
->hash_algo
= cfg
.hash
;
2502 repo_set_hash_algo(the_repository
, repo_fmt
->hash_algo
);
2504 env
= getenv("GIT_DEFAULT_REF_FORMAT");
2505 if (repo_fmt
->version
>= 0 &&
2506 ref_format
!= REF_STORAGE_FORMAT_UNKNOWN
&&
2507 ref_format
!= repo_fmt
->ref_storage_format
) {
2508 die(_("attempt to reinitialize repository with different reference storage format"));
2509 } else if (ref_format
!= REF_STORAGE_FORMAT_UNKNOWN
) {
2510 repo_fmt
->ref_storage_format
= ref_format
;
2512 ref_format
= ref_storage_format_by_name(env
);
2513 if (ref_format
== REF_STORAGE_FORMAT_UNKNOWN
)
2514 die(_("unknown ref storage format '%s'"), env
);
2515 repo_fmt
->ref_storage_format
= ref_format
;
2516 } else if (cfg
.ref_format
!= REF_STORAGE_FORMAT_UNKNOWN
) {
2517 repo_fmt
->ref_storage_format
= cfg
.ref_format
;
2519 repo_set_ref_storage_format(the_repository
, repo_fmt
->ref_storage_format
);
2522 int init_db(const char *git_dir
, const char *real_git_dir
,
2523 const char *template_dir
, int hash
,
2524 enum ref_storage_format ref_storage_format
,
2525 const char *initial_branch
,
2526 int init_shared_repository
, unsigned int flags
)
2529 int exist_ok
= flags
& INIT_DB_EXIST_OK
;
2530 char *original_git_dir
= real_pathdup(git_dir
, 1);
2531 struct repository_format repo_fmt
= REPOSITORY_FORMAT_INIT
;
2536 if (!exist_ok
&& !stat(git_dir
, &st
))
2537 die(_("%s already exists"), git_dir
);
2539 if (!exist_ok
&& !stat(real_git_dir
, &st
))
2540 die(_("%s already exists"), real_git_dir
);
2542 set_git_dir(real_git_dir
, 1);
2543 git_dir
= repo_get_git_dir(the_repository
);
2544 separate_git_dir(git_dir
, original_git_dir
);
2547 set_git_dir(git_dir
, 1);
2548 git_dir
= repo_get_git_dir(the_repository
);
2550 startup_info
->have_repository
= 1;
2553 * Check to see if the repository version is right.
2554 * Note that a newly created repository does not have
2555 * config file, so this will not fail. What we are catching
2556 * is an attempt to reinitialize new repository with an old tool.
2558 check_repository_format(&repo_fmt
);
2560 repository_format_configure(&repo_fmt
, hash
, ref_storage_format
);
2563 * Ensure `core.hidedotfiles` is processed. This must happen after we
2564 * have set up the repository format such that we can evaluate
2565 * includeIf conditions correctly in the case of re-initialization.
2567 git_config(platform_core_config
, NULL
);
2569 safe_create_dir(git_dir
, 0);
2571 reinit
= create_default_files(template_dir
, original_git_dir
,
2572 &repo_fmt
, init_shared_repository
);
2574 if (!(flags
& INIT_DB_SKIP_REFDB
))
2575 create_reference_database(repo_fmt
.ref_storage_format
,
2576 initial_branch
, flags
& INIT_DB_QUIET
);
2577 create_object_directory();
2579 if (get_shared_repository()) {
2581 /* We do not spell "group" and such, so that
2582 * the configuration can be read by older version
2583 * of git. Note, we use octal numbers for new share modes,
2584 * and compatibility values for PERM_GROUP and
2587 if (get_shared_repository() < 0)
2588 /* force to the mode value */
2589 xsnprintf(buf
, sizeof(buf
), "0%o", -get_shared_repository());
2590 else if (get_shared_repository() == PERM_GROUP
)
2591 xsnprintf(buf
, sizeof(buf
), "%d", OLD_PERM_GROUP
);
2592 else if (get_shared_repository() == PERM_EVERYBODY
)
2593 xsnprintf(buf
, sizeof(buf
), "%d", OLD_PERM_EVERYBODY
);
2595 BUG("invalid value for shared_repository");
2596 git_config_set("core.sharedrepository", buf
);
2597 git_config_set("receive.denyNonFastforwards", "true");
2600 if (!(flags
& INIT_DB_QUIET
)) {
2601 int len
= strlen(git_dir
);
2604 printf(get_shared_repository()
2605 ? _("Reinitialized existing shared Git repository in %s%s\n")
2606 : _("Reinitialized existing Git repository in %s%s\n"),
2607 git_dir
, len
&& git_dir
[len
-1] != '/' ? "/" : "");
2609 printf(get_shared_repository()
2610 ? _("Initialized empty shared Git repository in %s%s\n")
2611 : _("Initialized empty Git repository in %s%s\n"),
2612 git_dir
, len
&& git_dir
[len
-1] != '/' ? "/" : "");
2615 clear_repository_format(&repo_fmt
);
2616 free(original_git_dir
);