Merge branch 'fixes/2.45.1/2.42' into maint-2.42
[git/debian.git] / setup.c
blob881935f0956bec94e7c1bc7a897de60fcaac528d
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "exec-cmd.h"
6 #include "gettext.h"
7 #include "object-name.h"
8 #include "refs.h"
9 #include "repository.h"
10 #include "config.h"
11 #include "dir.h"
12 #include "setup.h"
13 #include "string-list.h"
14 #include "chdir-notify.h"
15 #include "path.h"
16 #include "promisor-remote.h"
17 #include "quote.h"
18 #include "trace2.h"
19 #include "worktree.h"
20 #include "exec-cmd.h"
22 static int inside_git_dir = -1;
23 static int inside_work_tree = -1;
24 static int work_tree_config_is_bogus;
25 enum allowed_bare_repo {
26 ALLOWED_BARE_REPO_EXPLICIT = 0,
27 ALLOWED_BARE_REPO_ALL,
30 static struct startup_info the_startup_info;
31 struct startup_info *startup_info = &the_startup_info;
32 const char *tmp_original_cwd;
35 * The input parameter must contain an absolute path, and it must already be
36 * normalized.
38 * Find the part of an absolute path that lies inside the work tree by
39 * dereferencing symlinks outside the work tree, for example:
40 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
41 * /dir/file (work tree is /) -> dir/file
42 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
43 * /dir/repolink/file (repolink points to /dir/repo) -> file
44 * /dir/repo (exactly equal to work tree) -> (empty string)
46 static int abspath_part_inside_repo(char *path)
48 size_t len;
49 size_t wtlen;
50 char *path0;
51 int off;
52 const char *work_tree = get_git_work_tree();
53 struct strbuf realpath = STRBUF_INIT;
55 if (!work_tree)
56 return -1;
57 wtlen = strlen(work_tree);
58 len = strlen(path);
59 off = offset_1st_component(path);
61 /* check if work tree is already the prefix */
62 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
63 if (path[wtlen] == '/') {
64 memmove(path, path + wtlen + 1, len - wtlen);
65 return 0;
66 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
67 /* work tree is the root, or the whole path */
68 memmove(path, path + wtlen, len - wtlen + 1);
69 return 0;
71 /* work tree might match beginning of a symlink to work tree */
72 off = wtlen;
74 path0 = path;
75 path += off;
77 /* check each '/'-terminated level */
78 while (*path) {
79 path++;
80 if (*path == '/') {
81 *path = '\0';
82 strbuf_realpath(&realpath, path0, 1);
83 if (fspathcmp(realpath.buf, work_tree) == 0) {
84 memmove(path0, path + 1, len - (path - path0));
85 strbuf_release(&realpath);
86 return 0;
88 *path = '/';
92 /* check whole path */
93 strbuf_realpath(&realpath, path0, 1);
94 if (fspathcmp(realpath.buf, work_tree) == 0) {
95 *path0 = '\0';
96 strbuf_release(&realpath);
97 return 0;
100 strbuf_release(&realpath);
101 return -1;
105 * Normalize "path", prepending the "prefix" for relative paths. If
106 * remaining_prefix is not NULL, return the actual prefix still
107 * remains in the path. For example, prefix = sub1/sub2/ and path is
109 * foo -> sub1/sub2/foo (full prefix)
110 * ../foo -> sub1/foo (remaining prefix is sub1/)
111 * ../../bar -> bar (no remaining prefix)
112 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
113 * `pwd`/../bar -> sub1/bar (no remaining prefix)
115 char *prefix_path_gently(const char *prefix, int len,
116 int *remaining_prefix, const char *path)
118 const char *orig = path;
119 char *sanitized;
120 if (is_absolute_path(orig)) {
121 sanitized = xmallocz(strlen(path));
122 if (remaining_prefix)
123 *remaining_prefix = 0;
124 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
125 free(sanitized);
126 return NULL;
128 if (abspath_part_inside_repo(sanitized)) {
129 free(sanitized);
130 return NULL;
132 } else {
133 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
134 if (remaining_prefix)
135 *remaining_prefix = len;
136 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
137 free(sanitized);
138 return NULL;
141 return sanitized;
144 char *prefix_path(const char *prefix, int len, const char *path)
146 char *r = prefix_path_gently(prefix, len, NULL, path);
147 if (!r) {
148 const char *hint_path = get_git_work_tree();
149 if (!hint_path)
150 hint_path = get_git_dir();
151 die(_("'%s' is outside repository at '%s'"), path,
152 absolute_path(hint_path));
154 return r;
157 int path_inside_repo(const char *prefix, const char *path)
159 int len = prefix ? strlen(prefix) : 0;
160 char *r = prefix_path_gently(prefix, len, NULL, path);
161 if (r) {
162 free(r);
163 return 1;
165 return 0;
168 int check_filename(const char *prefix, const char *arg)
170 char *to_free = NULL;
171 struct stat st;
173 if (skip_prefix(arg, ":/", &arg)) {
174 if (!*arg) /* ":/" is root dir, always exists */
175 return 1;
176 prefix = NULL;
177 } else if (skip_prefix(arg, ":!", &arg) ||
178 skip_prefix(arg, ":^", &arg)) {
179 if (!*arg) /* excluding everything is silly, but allowed */
180 return 1;
183 if (prefix)
184 arg = to_free = prefix_filename(prefix, arg);
186 if (!lstat(arg, &st)) {
187 free(to_free);
188 return 1; /* file exists */
190 if (is_missing_file_error(errno)) {
191 free(to_free);
192 return 0; /* file does not exist */
194 die_errno(_("failed to stat '%s'"), arg);
197 static void NORETURN die_verify_filename(struct repository *r,
198 const char *prefix,
199 const char *arg,
200 int diagnose_misspelt_rev)
202 if (!diagnose_misspelt_rev)
203 die(_("%s: no such path in the working tree.\n"
204 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
205 arg);
207 * Saying "'(icase)foo' does not exist in the index" when the
208 * user gave us ":(icase)foo" is just stupid. A magic pathspec
209 * begins with a colon and is followed by a non-alnum; do not
210 * let maybe_die_on_misspelt_object_name() even trigger.
212 if (!(arg[0] == ':' && !isalnum(arg[1])))
213 maybe_die_on_misspelt_object_name(r, arg, prefix);
215 /* ... or fall back the most general message. */
216 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
217 "Use '--' to separate paths from revisions, like this:\n"
218 "'git <command> [<revision>...] -- [<file>...]'"), arg);
223 * Check for arguments that don't resolve as actual files,
224 * but which look sufficiently like pathspecs that we'll consider
225 * them such for the purposes of rev/pathspec DWIM parsing.
227 static int looks_like_pathspec(const char *arg)
229 const char *p;
230 int escaped = 0;
233 * Wildcard characters imply the user is looking to match pathspecs
234 * that aren't in the filesystem. Note that this doesn't include
235 * backslash even though it's a glob special; by itself it doesn't
236 * cause any increase in the match. Likewise ignore backslash-escaped
237 * wildcard characters.
239 for (p = arg; *p; p++) {
240 if (escaped) {
241 escaped = 0;
242 } else if (is_glob_special(*p)) {
243 if (*p == '\\')
244 escaped = 1;
245 else
246 return 1;
250 /* long-form pathspec magic */
251 if (starts_with(arg, ":("))
252 return 1;
254 return 0;
258 * Verify a filename that we got as an argument for a pathspec
259 * entry. Note that a filename that begins with "-" never verifies
260 * as true, because even if such a filename were to exist, we want
261 * it to be preceded by the "--" marker (or we want the user to
262 * use a format like "./-filename")
264 * The "diagnose_misspelt_rev" is used to provide a user-friendly
265 * diagnosis when dying upon finding that "name" is not a pathname.
266 * If set to 1, the diagnosis will try to diagnose "name" as an
267 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
268 * will only complain about an inexisting file.
270 * This function is typically called to check that a "file or rev"
271 * argument is unambiguous. In this case, the caller will want
272 * diagnose_misspelt_rev == 1 when verifying the first non-rev
273 * argument (which could have been a revision), and
274 * diagnose_misspelt_rev == 0 for the next ones (because we already
275 * saw a filename, there's not ambiguity anymore).
277 void verify_filename(const char *prefix,
278 const char *arg,
279 int diagnose_misspelt_rev)
281 if (*arg == '-')
282 die(_("option '%s' must come before non-option arguments"), arg);
283 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
284 return;
285 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
289 * Opposite of the above: the command line did not have -- marker
290 * and we parsed the arg as a refname. It should not be interpretable
291 * as a filename.
293 void verify_non_filename(const char *prefix, const char *arg)
295 if (!is_inside_work_tree() || is_inside_git_dir())
296 return;
297 if (*arg == '-')
298 return; /* flag */
299 if (!check_filename(prefix, arg))
300 return;
301 die(_("ambiguous argument '%s': both revision and filename\n"
302 "Use '--' to separate paths from revisions, like this:\n"
303 "'git <command> [<revision>...] -- [<file>...]'"), arg);
306 int get_common_dir(struct strbuf *sb, const char *gitdir)
308 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
309 if (git_env_common_dir) {
310 strbuf_addstr(sb, git_env_common_dir);
311 return 1;
312 } else {
313 return get_common_dir_noenv(sb, gitdir);
317 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
319 struct strbuf data = STRBUF_INIT;
320 struct strbuf path = STRBUF_INIT;
321 int ret = 0;
323 strbuf_addf(&path, "%s/commondir", gitdir);
324 if (file_exists(path.buf)) {
325 if (strbuf_read_file(&data, path.buf, 0) <= 0)
326 die_errno(_("failed to read %s"), path.buf);
327 while (data.len && (data.buf[data.len - 1] == '\n' ||
328 data.buf[data.len - 1] == '\r'))
329 data.len--;
330 data.buf[data.len] = '\0';
331 strbuf_reset(&path);
332 if (!is_absolute_path(data.buf))
333 strbuf_addf(&path, "%s/", gitdir);
334 strbuf_addbuf(&path, &data);
335 strbuf_add_real_path(sb, path.buf);
336 ret = 1;
337 } else {
338 strbuf_addstr(sb, gitdir);
341 strbuf_release(&data);
342 strbuf_release(&path);
343 return ret;
347 * Test if it looks like we're at a git directory.
348 * We want to see:
350 * - either an objects/ directory _or_ the proper
351 * GIT_OBJECT_DIRECTORY environment variable
352 * - a refs/ directory
353 * - either a HEAD symlink or a HEAD file that is formatted as
354 * a proper "ref:", or a regular file HEAD that has a properly
355 * formatted sha1 object name.
357 int is_git_directory(const char *suspect)
359 struct strbuf path = STRBUF_INIT;
360 int ret = 0;
361 size_t len;
363 /* Check worktree-related signatures */
364 strbuf_addstr(&path, suspect);
365 strbuf_complete(&path, '/');
366 strbuf_addstr(&path, "HEAD");
367 if (validate_headref(path.buf))
368 goto done;
370 strbuf_reset(&path);
371 get_common_dir(&path, suspect);
372 len = path.len;
374 /* Check non-worktree-related signatures */
375 if (getenv(DB_ENVIRONMENT)) {
376 if (access(getenv(DB_ENVIRONMENT), X_OK))
377 goto done;
379 else {
380 strbuf_setlen(&path, len);
381 strbuf_addstr(&path, "/objects");
382 if (access(path.buf, X_OK))
383 goto done;
386 strbuf_setlen(&path, len);
387 strbuf_addstr(&path, "/refs");
388 if (access(path.buf, X_OK))
389 goto done;
391 ret = 1;
392 done:
393 strbuf_release(&path);
394 return ret;
397 int is_nonbare_repository_dir(struct strbuf *path)
399 int ret = 0;
400 int gitfile_error;
401 size_t orig_path_len = path->len;
402 assert(orig_path_len != 0);
403 strbuf_complete(path, '/');
404 strbuf_addstr(path, ".git");
405 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
406 ret = 1;
407 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
408 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
409 ret = 1;
410 strbuf_setlen(path, orig_path_len);
411 return ret;
414 int is_inside_git_dir(void)
416 if (inside_git_dir < 0)
417 inside_git_dir = is_inside_dir(get_git_dir());
418 return inside_git_dir;
421 int is_inside_work_tree(void)
423 if (inside_work_tree < 0)
424 inside_work_tree = is_inside_dir(get_git_work_tree());
425 return inside_work_tree;
428 void setup_work_tree(void)
430 const char *work_tree;
431 static int initialized = 0;
433 if (initialized)
434 return;
436 if (work_tree_config_is_bogus)
437 die(_("unable to set up work tree using invalid config"));
439 work_tree = get_git_work_tree();
440 if (!work_tree || chdir_notify(work_tree))
441 die(_("this operation must be run in a work tree"));
444 * Make sure subsequent git processes find correct worktree
445 * if $GIT_WORK_TREE is set relative
447 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
448 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
450 initialized = 1;
453 static void setup_original_cwd(void)
455 struct strbuf tmp = STRBUF_INIT;
456 const char *worktree = NULL;
457 int offset = -1;
459 if (!tmp_original_cwd)
460 return;
463 * startup_info->original_cwd points to the current working
464 * directory we inherited from our parent process, which is a
465 * directory we want to avoid removing.
467 * For convience, we would like to have the path relative to the
468 * worktree instead of an absolute path.
470 * Yes, startup_info->original_cwd is usually the same as 'prefix',
471 * but differs in two ways:
472 * - prefix has a trailing '/'
473 * - if the user passes '-C' to git, that modifies the prefix but
474 * not startup_info->original_cwd.
477 /* Normalize the directory */
478 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
479 trace2_data_string("setup", the_repository,
480 "realpath-path", tmp_original_cwd);
481 trace2_data_string("setup", the_repository,
482 "realpath-failure", strerror(errno));
483 free((char*)tmp_original_cwd);
484 tmp_original_cwd = NULL;
485 return;
488 free((char*)tmp_original_cwd);
489 tmp_original_cwd = NULL;
490 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
493 * Get our worktree; we only protect the current working directory
494 * if it's in the worktree.
496 worktree = get_git_work_tree();
497 if (!worktree)
498 goto no_prevention_needed;
500 offset = dir_inside_of(startup_info->original_cwd, worktree);
501 if (offset >= 0) {
503 * If startup_info->original_cwd == worktree, that is already
504 * protected and we don't need original_cwd as a secondary
505 * protection measure.
507 if (!*(startup_info->original_cwd + offset))
508 goto no_prevention_needed;
511 * original_cwd was inside worktree; precompose it just as
512 * we do prefix so that built up paths will match
514 startup_info->original_cwd = \
515 precompose_string_if_needed(startup_info->original_cwd
516 + offset);
517 return;
520 no_prevention_needed:
521 free((char*)startup_info->original_cwd);
522 startup_info->original_cwd = NULL;
525 static int read_worktree_config(const char *var, const char *value,
526 const struct config_context *ctx UNUSED,
527 void *vdata)
529 struct repository_format *data = vdata;
531 if (strcmp(var, "core.bare") == 0) {
532 data->is_bare = git_config_bool(var, value);
533 } else if (strcmp(var, "core.worktree") == 0) {
534 if (!value)
535 return config_error_nonbool(var);
536 free(data->work_tree);
537 data->work_tree = xstrdup(value);
539 return 0;
542 enum extension_result {
543 EXTENSION_ERROR = -1, /* compatible with error(), etc */
544 EXTENSION_UNKNOWN = 0,
545 EXTENSION_OK = 1
549 * Do not add new extensions to this function. It handles extensions which are
550 * respected even in v0-format repositories for historical compatibility.
552 static enum extension_result handle_extension_v0(const char *var,
553 const char *value,
554 const char *ext,
555 struct repository_format *data)
557 if (!strcmp(ext, "noop")) {
558 return EXTENSION_OK;
559 } else if (!strcmp(ext, "preciousobjects")) {
560 data->precious_objects = git_config_bool(var, value);
561 return EXTENSION_OK;
562 } else if (!strcmp(ext, "partialclone")) {
563 data->partial_clone = xstrdup(value);
564 return EXTENSION_OK;
565 } else if (!strcmp(ext, "worktreeconfig")) {
566 data->worktree_config = git_config_bool(var, value);
567 return EXTENSION_OK;
570 return EXTENSION_UNKNOWN;
574 * Record any new extensions in this function.
576 static enum extension_result handle_extension(const char *var,
577 const char *value,
578 const char *ext,
579 struct repository_format *data)
581 if (!strcmp(ext, "noop-v1")) {
582 return EXTENSION_OK;
583 } else if (!strcmp(ext, "objectformat")) {
584 int format;
586 if (!value)
587 return config_error_nonbool(var);
588 format = hash_algo_by_name(value);
589 if (format == GIT_HASH_UNKNOWN)
590 return error(_("invalid value for '%s': '%s'"),
591 "extensions.objectformat", value);
592 data->hash_algo = format;
593 return EXTENSION_OK;
595 return EXTENSION_UNKNOWN;
598 static int check_repo_format(const char *var, const char *value,
599 const struct config_context *ctx, void *vdata)
601 struct repository_format *data = vdata;
602 const char *ext;
604 if (strcmp(var, "core.repositoryformatversion") == 0)
605 data->version = git_config_int(var, value, ctx->kvi);
606 else if (skip_prefix(var, "extensions.", &ext)) {
607 switch (handle_extension_v0(var, value, ext, data)) {
608 case EXTENSION_ERROR:
609 return -1;
610 case EXTENSION_OK:
611 return 0;
612 case EXTENSION_UNKNOWN:
613 break;
616 switch (handle_extension(var, value, ext, data)) {
617 case EXTENSION_ERROR:
618 return -1;
619 case EXTENSION_OK:
620 string_list_append(&data->v1_only_extensions, ext);
621 return 0;
622 case EXTENSION_UNKNOWN:
623 string_list_append(&data->unknown_extensions, ext);
624 return 0;
628 return read_worktree_config(var, value, ctx, vdata);
631 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
633 struct strbuf sb = STRBUF_INIT;
634 struct strbuf err = STRBUF_INIT;
635 int has_common;
637 has_common = get_common_dir(&sb, gitdir);
638 strbuf_addstr(&sb, "/config");
639 read_repository_format(candidate, sb.buf);
640 strbuf_release(&sb);
643 * For historical use of check_repository_format() in git-init,
644 * we treat a missing config as a silent "ok", even when nongit_ok
645 * is unset.
647 if (candidate->version < 0)
648 return 0;
650 if (verify_repository_format(candidate, &err) < 0) {
651 if (nongit_ok) {
652 warning("%s", err.buf);
653 strbuf_release(&err);
654 *nongit_ok = -1;
655 return -1;
657 die("%s", err.buf);
660 repository_format_precious_objects = candidate->precious_objects;
661 string_list_clear(&candidate->unknown_extensions, 0);
662 string_list_clear(&candidate->v1_only_extensions, 0);
664 if (candidate->worktree_config) {
666 * pick up core.bare and core.worktree from per-worktree
667 * config if present
669 strbuf_addf(&sb, "%s/config.worktree", gitdir);
670 git_config_from_file(read_worktree_config, sb.buf, candidate);
671 strbuf_release(&sb);
672 has_common = 0;
675 if (!has_common) {
676 if (candidate->is_bare != -1) {
677 is_bare_repository_cfg = candidate->is_bare;
678 if (is_bare_repository_cfg == 1)
679 inside_work_tree = -1;
681 if (candidate->work_tree) {
682 free(git_work_tree_cfg);
683 git_work_tree_cfg = xstrdup(candidate->work_tree);
684 inside_work_tree = -1;
688 return 0;
691 int upgrade_repository_format(int target_version)
693 struct strbuf sb = STRBUF_INIT;
694 struct strbuf err = STRBUF_INIT;
695 struct strbuf repo_version = STRBUF_INIT;
696 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
698 strbuf_git_common_path(&sb, the_repository, "config");
699 read_repository_format(&repo_fmt, sb.buf);
700 strbuf_release(&sb);
702 if (repo_fmt.version >= target_version)
703 return 0;
705 if (verify_repository_format(&repo_fmt, &err) < 0) {
706 error("cannot upgrade repository format from %d to %d: %s",
707 repo_fmt.version, target_version, err.buf);
708 strbuf_release(&err);
709 return -1;
711 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
712 return error("cannot upgrade repository format: "
713 "unknown extension %s",
714 repo_fmt.unknown_extensions.items[0].string);
716 strbuf_addf(&repo_version, "%d", target_version);
717 git_config_set("core.repositoryformatversion", repo_version.buf);
718 strbuf_release(&repo_version);
719 return 1;
722 static void init_repository_format(struct repository_format *format)
724 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
726 memcpy(format, &fresh, sizeof(fresh));
729 int read_repository_format(struct repository_format *format, const char *path)
731 clear_repository_format(format);
732 git_config_from_file(check_repo_format, path, format);
733 if (format->version == -1)
734 clear_repository_format(format);
735 return format->version;
738 void clear_repository_format(struct repository_format *format)
740 string_list_clear(&format->unknown_extensions, 0);
741 string_list_clear(&format->v1_only_extensions, 0);
742 free(format->work_tree);
743 free(format->partial_clone);
744 init_repository_format(format);
747 int verify_repository_format(const struct repository_format *format,
748 struct strbuf *err)
750 if (GIT_REPO_VERSION_READ < format->version) {
751 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
752 GIT_REPO_VERSION_READ, format->version);
753 return -1;
756 if (format->version >= 1 && format->unknown_extensions.nr) {
757 int i;
759 strbuf_addstr(err, Q_("unknown repository extension found:",
760 "unknown repository extensions found:",
761 format->unknown_extensions.nr));
763 for (i = 0; i < format->unknown_extensions.nr; i++)
764 strbuf_addf(err, "\n\t%s",
765 format->unknown_extensions.items[i].string);
766 return -1;
769 if (format->version == 0 && format->v1_only_extensions.nr) {
770 int i;
772 strbuf_addstr(err,
773 Q_("repo version is 0, but v1-only extension found:",
774 "repo version is 0, but v1-only extensions found:",
775 format->v1_only_extensions.nr));
777 for (i = 0; i < format->v1_only_extensions.nr; i++)
778 strbuf_addf(err, "\n\t%s",
779 format->v1_only_extensions.items[i].string);
780 return -1;
783 return 0;
786 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
788 switch (error_code) {
789 case READ_GITFILE_ERR_STAT_FAILED:
790 case READ_GITFILE_ERR_NOT_A_FILE:
791 /* non-fatal; follow return path */
792 break;
793 case READ_GITFILE_ERR_OPEN_FAILED:
794 die_errno(_("error opening '%s'"), path);
795 case READ_GITFILE_ERR_TOO_LARGE:
796 die(_("too large to be a .git file: '%s'"), path);
797 case READ_GITFILE_ERR_READ_FAILED:
798 die(_("error reading %s"), path);
799 case READ_GITFILE_ERR_INVALID_FORMAT:
800 die(_("invalid gitfile format: %s"), path);
801 case READ_GITFILE_ERR_NO_PATH:
802 die(_("no path in gitfile: %s"), path);
803 case READ_GITFILE_ERR_NOT_A_REPO:
804 die(_("not a git repository: %s"), dir);
805 default:
806 BUG("unknown error code");
811 * Try to read the location of the git directory from the .git file,
812 * return path to git directory if found. The return value comes from
813 * a shared buffer.
815 * On failure, if return_error_code is not NULL, return_error_code
816 * will be set to an error code and NULL will be returned. If
817 * return_error_code is NULL the function will die instead (for most
818 * cases).
820 const char *read_gitfile_gently(const char *path, int *return_error_code)
822 const int max_file_size = 1 << 20; /* 1MB */
823 int error_code = 0;
824 char *buf = NULL;
825 char *dir = NULL;
826 const char *slash;
827 struct stat st;
828 int fd;
829 ssize_t len;
830 static struct strbuf realpath = STRBUF_INIT;
832 if (stat(path, &st)) {
833 /* NEEDSWORK: discern between ENOENT vs other errors */
834 error_code = READ_GITFILE_ERR_STAT_FAILED;
835 goto cleanup_return;
837 if (!S_ISREG(st.st_mode)) {
838 error_code = READ_GITFILE_ERR_NOT_A_FILE;
839 goto cleanup_return;
841 if (st.st_size > max_file_size) {
842 error_code = READ_GITFILE_ERR_TOO_LARGE;
843 goto cleanup_return;
845 fd = open(path, O_RDONLY);
846 if (fd < 0) {
847 error_code = READ_GITFILE_ERR_OPEN_FAILED;
848 goto cleanup_return;
850 buf = xmallocz(st.st_size);
851 len = read_in_full(fd, buf, st.st_size);
852 close(fd);
853 if (len != st.st_size) {
854 error_code = READ_GITFILE_ERR_READ_FAILED;
855 goto cleanup_return;
857 if (!starts_with(buf, "gitdir: ")) {
858 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
859 goto cleanup_return;
861 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
862 len--;
863 if (len < 9) {
864 error_code = READ_GITFILE_ERR_NO_PATH;
865 goto cleanup_return;
867 buf[len] = '\0';
868 dir = buf + 8;
870 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
871 size_t pathlen = slash+1 - path;
872 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
873 (int)(len - 8), buf + 8);
874 free(buf);
875 buf = dir;
877 if (!is_git_directory(dir)) {
878 error_code = READ_GITFILE_ERR_NOT_A_REPO;
879 goto cleanup_return;
882 strbuf_realpath(&realpath, dir, 1);
883 path = realpath.buf;
885 cleanup_return:
886 if (return_error_code)
887 *return_error_code = error_code;
888 else if (error_code)
889 read_gitfile_error_die(error_code, path, dir);
891 free(buf);
892 return error_code ? NULL : path;
895 static const char *setup_explicit_git_dir(const char *gitdirenv,
896 struct strbuf *cwd,
897 struct repository_format *repo_fmt,
898 int *nongit_ok)
900 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
901 const char *worktree;
902 char *gitfile;
903 int offset;
905 if (PATH_MAX - 40 < strlen(gitdirenv))
906 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
908 gitfile = (char*)read_gitfile(gitdirenv);
909 if (gitfile) {
910 gitfile = xstrdup(gitfile);
911 gitdirenv = gitfile;
914 if (!is_git_directory(gitdirenv)) {
915 if (nongit_ok) {
916 *nongit_ok = 1;
917 free(gitfile);
918 return NULL;
920 die(_("not a git repository: '%s'"), gitdirenv);
923 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
924 free(gitfile);
925 return NULL;
928 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
929 if (work_tree_env)
930 set_git_work_tree(work_tree_env);
931 else if (is_bare_repository_cfg > 0) {
932 if (git_work_tree_cfg) {
933 /* #22.2, #30 */
934 warning("core.bare and core.worktree do not make sense");
935 work_tree_config_is_bogus = 1;
938 /* #18, #26 */
939 set_git_dir(gitdirenv, 0);
940 free(gitfile);
941 return NULL;
943 else if (git_work_tree_cfg) { /* #6, #14 */
944 if (is_absolute_path(git_work_tree_cfg))
945 set_git_work_tree(git_work_tree_cfg);
946 else {
947 char *core_worktree;
948 if (chdir(gitdirenv))
949 die_errno(_("cannot chdir to '%s'"), gitdirenv);
950 if (chdir(git_work_tree_cfg))
951 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
952 core_worktree = xgetcwd();
953 if (chdir(cwd->buf))
954 die_errno(_("cannot come back to cwd"));
955 set_git_work_tree(core_worktree);
956 free(core_worktree);
959 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
960 /* #16d */
961 set_git_dir(gitdirenv, 0);
962 free(gitfile);
963 return NULL;
965 else /* #2, #10 */
966 set_git_work_tree(".");
968 /* set_git_work_tree() must have been called by now */
969 worktree = get_git_work_tree();
971 /* both get_git_work_tree() and cwd are already normalized */
972 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
973 set_git_dir(gitdirenv, 0);
974 free(gitfile);
975 return NULL;
978 offset = dir_inside_of(cwd->buf, worktree);
979 if (offset >= 0) { /* cwd inside worktree? */
980 set_git_dir(gitdirenv, 1);
981 if (chdir(worktree))
982 die_errno(_("cannot chdir to '%s'"), worktree);
983 strbuf_addch(cwd, '/');
984 free(gitfile);
985 return cwd->buf + offset;
988 /* cwd outside worktree */
989 set_git_dir(gitdirenv, 0);
990 free(gitfile);
991 return NULL;
994 static const char *setup_discovered_git_dir(const char *gitdir,
995 struct strbuf *cwd, int offset,
996 struct repository_format *repo_fmt,
997 int *nongit_ok)
999 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1000 return NULL;
1002 /* --work-tree is set without --git-dir; use discovered one */
1003 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1004 char *to_free = NULL;
1005 const char *ret;
1007 if (offset != cwd->len && !is_absolute_path(gitdir))
1008 gitdir = to_free = real_pathdup(gitdir, 1);
1009 if (chdir(cwd->buf))
1010 die_errno(_("cannot come back to cwd"));
1011 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1012 free(to_free);
1013 return ret;
1016 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1017 if (is_bare_repository_cfg > 0) {
1018 set_git_dir(gitdir, (offset != cwd->len));
1019 if (chdir(cwd->buf))
1020 die_errno(_("cannot come back to cwd"));
1021 return NULL;
1024 /* #0, #1, #5, #8, #9, #12, #13 */
1025 set_git_work_tree(".");
1026 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1027 set_git_dir(gitdir, 0);
1028 inside_git_dir = 0;
1029 inside_work_tree = 1;
1030 if (offset >= cwd->len)
1031 return NULL;
1033 /* Make "offset" point past the '/' (already the case for root dirs) */
1034 if (offset != offset_1st_component(cwd->buf))
1035 offset++;
1036 /* Add a '/' at the end */
1037 strbuf_addch(cwd, '/');
1038 return cwd->buf + offset;
1041 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1042 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1043 struct repository_format *repo_fmt,
1044 int *nongit_ok)
1046 int root_len;
1048 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1049 return NULL;
1051 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1053 /* --work-tree is set without --git-dir; use discovered one */
1054 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1055 static const char *gitdir;
1057 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1058 if (chdir(cwd->buf))
1059 die_errno(_("cannot come back to cwd"));
1060 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1063 inside_git_dir = 1;
1064 inside_work_tree = 0;
1065 if (offset != cwd->len) {
1066 if (chdir(cwd->buf))
1067 die_errno(_("cannot come back to cwd"));
1068 root_len = offset_1st_component(cwd->buf);
1069 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1070 set_git_dir(cwd->buf, 0);
1072 else
1073 set_git_dir(".", 0);
1074 return NULL;
1077 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1079 struct stat buf;
1080 if (stat(path, &buf)) {
1081 die_errno(_("failed to stat '%*s%s%s'"),
1082 prefix_len,
1083 prefix ? prefix : "",
1084 prefix ? "/" : "", path);
1086 return buf.st_dev;
1090 * A "string_list_each_func_t" function that canonicalizes an entry
1091 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1092 * discards it if unusable. The presence of an empty entry in
1093 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1094 * subsequent entries.
1096 static int canonicalize_ceiling_entry(struct string_list_item *item,
1097 void *cb_data)
1099 int *empty_entry_found = cb_data;
1100 char *ceil = item->string;
1102 if (!*ceil) {
1103 *empty_entry_found = 1;
1104 return 0;
1105 } else if (!is_absolute_path(ceil)) {
1106 return 0;
1107 } else if (*empty_entry_found) {
1108 /* Keep entry but do not canonicalize it */
1109 return 1;
1110 } else {
1111 char *real_path = real_pathdup(ceil, 0);
1112 if (!real_path) {
1113 return 0;
1115 free(item->string);
1116 item->string = real_path;
1117 return 1;
1121 struct safe_directory_data {
1122 const char *path;
1123 int is_safe;
1126 static int safe_directory_cb(const char *key, const char *value,
1127 const struct config_context *ctx UNUSED, void *d)
1129 struct safe_directory_data *data = d;
1131 if (strcmp(key, "safe.directory"))
1132 return 0;
1134 if (!value || !*value) {
1135 data->is_safe = 0;
1136 } else if (!strcmp(value, "*")) {
1137 data->is_safe = 1;
1138 } else {
1139 const char *interpolated = NULL;
1141 if (!git_config_pathname(&interpolated, key, value) &&
1142 !fspathcmp(data->path, interpolated ? interpolated : value))
1143 data->is_safe = 1;
1145 free((char *)interpolated);
1148 return 0;
1152 * Check if a repository is safe, by verifying the ownership of the
1153 * worktree (if any), the git directory, and the gitfile (if any).
1155 * Exemptions for known-safe repositories can be added via `safe.directory`
1156 * config settings; for non-bare repositories, their worktree needs to be
1157 * added, for bare ones their git directory.
1159 static int ensure_valid_ownership(const char *gitfile,
1160 const char *worktree, const char *gitdir,
1161 struct strbuf *report)
1163 struct safe_directory_data data = {
1164 .path = worktree ? worktree : gitdir
1167 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1168 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1169 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1170 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1171 return 1;
1174 * data.path is the "path" that identifies the repository and it is
1175 * constant regardless of what failed above. data.is_safe should be
1176 * initialized to false, and might be changed by the callback.
1178 git_protected_config(safe_directory_cb, &data);
1180 return data.is_safe;
1183 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1184 const char *gitdir)
1186 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1187 const char *path;
1189 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1190 return;
1192 strbuf_complete(&report, '\n');
1193 path = gitfile ? gitfile : gitdir;
1194 sq_quote_buf_pretty(&quoted, path);
1196 die(_("detected dubious ownership in repository at '%s'\n"
1197 "%s"
1198 "To add an exception for this directory, call:\n"
1199 "\n"
1200 "\tgit config --global --add safe.directory %s"),
1201 path, report.buf, quoted.buf);
1204 static int allowed_bare_repo_cb(const char *key, const char *value,
1205 const struct config_context *ctx UNUSED,
1206 void *d)
1208 enum allowed_bare_repo *allowed_bare_repo = d;
1210 if (strcasecmp(key, "safe.bareRepository"))
1211 return 0;
1213 if (!strcmp(value, "explicit")) {
1214 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1215 return 0;
1217 if (!strcmp(value, "all")) {
1218 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1219 return 0;
1221 return -1;
1224 static enum allowed_bare_repo get_allowed_bare_repo(void)
1226 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1227 git_protected_config(allowed_bare_repo_cb, &result);
1228 return result;
1231 static const char *allowed_bare_repo_to_string(
1232 enum allowed_bare_repo allowed_bare_repo)
1234 switch (allowed_bare_repo) {
1235 case ALLOWED_BARE_REPO_EXPLICIT:
1236 return "explicit";
1237 case ALLOWED_BARE_REPO_ALL:
1238 return "all";
1239 default:
1240 BUG("invalid allowed_bare_repo %d",
1241 allowed_bare_repo);
1243 return NULL;
1247 * We cannot decide in this function whether we are in the work tree or
1248 * not, since the config can only be read _after_ this function was called.
1250 * Also, we avoid changing any global state (such as the current working
1251 * directory) to allow early callers.
1253 * The directory where the search should start needs to be passed in via the
1254 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1255 * the directory where the search ended, and `gitdir` will contain the path of
1256 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1257 * is relative to `dir` (i.e. *not* necessarily the cwd).
1259 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1260 struct strbuf *gitdir,
1261 struct strbuf *report,
1262 int die_on_error)
1264 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1265 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1266 const char *gitdirenv;
1267 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1268 dev_t current_device = 0;
1269 int one_filesystem = 1;
1272 * If GIT_DIR is set explicitly, we're not going
1273 * to do any discovery, but we still do repository
1274 * validation.
1276 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1277 if (gitdirenv) {
1278 strbuf_addstr(gitdir, gitdirenv);
1279 return GIT_DIR_EXPLICIT;
1282 if (env_ceiling_dirs) {
1283 int empty_entry_found = 0;
1285 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1286 filter_string_list(&ceiling_dirs, 0,
1287 canonicalize_ceiling_entry, &empty_entry_found);
1288 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1289 string_list_clear(&ceiling_dirs, 0);
1292 if (ceil_offset < 0)
1293 ceil_offset = min_offset - 2;
1295 if (min_offset && min_offset == dir->len &&
1296 !is_dir_sep(dir->buf[min_offset - 1])) {
1297 strbuf_addch(dir, '/');
1298 min_offset++;
1302 * Test in the following order (relative to the dir):
1303 * - .git (file containing "gitdir: <path>")
1304 * - .git/
1305 * - ./ (bare)
1306 * - ../.git
1307 * - ../.git/
1308 * - ../ (bare)
1309 * - ../../.git
1310 * etc.
1312 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1313 if (one_filesystem)
1314 current_device = get_device_or_die(dir->buf, NULL, 0);
1315 for (;;) {
1316 int offset = dir->len, error_code = 0;
1317 char *gitdir_path = NULL;
1318 char *gitfile = NULL;
1320 if (offset > min_offset)
1321 strbuf_addch(dir, '/');
1322 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1323 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1324 NULL : &error_code);
1325 if (!gitdirenv) {
1326 if (die_on_error ||
1327 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1328 /* NEEDSWORK: fail if .git is not file nor dir */
1329 if (is_git_directory(dir->buf)) {
1330 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1331 gitdir_path = xstrdup(dir->buf);
1333 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1334 return GIT_DIR_INVALID_GITFILE;
1335 } else
1336 gitfile = xstrdup(dir->buf);
1338 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1339 * to check that directory for a repository.
1340 * Now trim that tentative addition away, because we want to
1341 * focus on the real directory we are in.
1343 strbuf_setlen(dir, offset);
1344 if (gitdirenv) {
1345 enum discovery_result ret;
1346 const char *gitdir_candidate =
1347 gitdir_path ? gitdir_path : gitdirenv;
1349 if (ensure_valid_ownership(gitfile, dir->buf,
1350 gitdir_candidate, report)) {
1351 strbuf_addstr(gitdir, gitdirenv);
1352 ret = GIT_DIR_DISCOVERED;
1353 } else
1354 ret = GIT_DIR_INVALID_OWNERSHIP;
1357 * Earlier, during discovery, we might have allocated
1358 * string copies for gitdir_path or gitfile so make
1359 * sure we don't leak by freeing them now, before
1360 * leaving the loop and function.
1362 * Note: gitdirenv will be non-NULL whenever these are
1363 * allocated, therefore we need not take care of releasing
1364 * them outside of this conditional block.
1366 free(gitdir_path);
1367 free(gitfile);
1369 return ret;
1372 if (is_git_directory(dir->buf)) {
1373 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1374 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1375 return GIT_DIR_DISALLOWED_BARE;
1376 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1377 return GIT_DIR_INVALID_OWNERSHIP;
1378 strbuf_addstr(gitdir, ".");
1379 return GIT_DIR_BARE;
1382 if (offset <= min_offset)
1383 return GIT_DIR_HIT_CEILING;
1385 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1386 ; /* continue */
1387 if (offset <= ceil_offset)
1388 return GIT_DIR_HIT_CEILING;
1390 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1391 if (one_filesystem &&
1392 current_device != get_device_or_die(dir->buf, NULL, offset))
1393 return GIT_DIR_HIT_MOUNT_POINT;
1397 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1398 struct strbuf *gitdir)
1400 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1401 size_t gitdir_offset = gitdir->len, cwd_len;
1402 size_t commondir_offset = commondir->len;
1403 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1404 enum discovery_result result;
1406 if (strbuf_getcwd(&dir))
1407 return GIT_DIR_CWD_FAILURE;
1409 cwd_len = dir.len;
1410 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1411 if (result <= 0) {
1412 strbuf_release(&dir);
1413 return result;
1417 * The returned gitdir is relative to dir, and if dir does not reflect
1418 * the current working directory, we simply make the gitdir absolute.
1420 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1421 /* Avoid a trailing "/." */
1422 if (!strcmp(".", gitdir->buf + gitdir_offset))
1423 strbuf_setlen(gitdir, gitdir_offset);
1424 else
1425 strbuf_addch(&dir, '/');
1426 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1429 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1431 strbuf_reset(&dir);
1432 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1433 read_repository_format(&candidate, dir.buf);
1434 strbuf_release(&dir);
1436 if (verify_repository_format(&candidate, &err) < 0) {
1437 warning("ignoring git dir '%s': %s",
1438 gitdir->buf + gitdir_offset, err.buf);
1439 strbuf_release(&err);
1440 strbuf_setlen(commondir, commondir_offset);
1441 strbuf_setlen(gitdir, gitdir_offset);
1442 clear_repository_format(&candidate);
1443 return GIT_DIR_INVALID_FORMAT;
1446 clear_repository_format(&candidate);
1447 return result;
1450 const char *setup_git_directory_gently(int *nongit_ok)
1452 static struct strbuf cwd = STRBUF_INIT;
1453 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1454 const char *prefix = NULL;
1455 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1458 * We may have read an incomplete configuration before
1459 * setting-up the git directory. If so, clear the cache so
1460 * that the next queries to the configuration reload complete
1461 * configuration (including the per-repo config file that we
1462 * ignored previously).
1464 git_config_clear();
1467 * Let's assume that we are in a git repository.
1468 * If it turns out later that we are somewhere else, the value will be
1469 * updated accordingly.
1471 if (nongit_ok)
1472 *nongit_ok = 0;
1474 if (strbuf_getcwd(&cwd))
1475 die_errno(_("Unable to read current working directory"));
1476 strbuf_addbuf(&dir, &cwd);
1478 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1479 case GIT_DIR_EXPLICIT:
1480 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1481 break;
1482 case GIT_DIR_DISCOVERED:
1483 if (dir.len < cwd.len && chdir(dir.buf))
1484 die(_("cannot change to '%s'"), dir.buf);
1485 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1486 &repo_fmt, nongit_ok);
1487 break;
1488 case GIT_DIR_BARE:
1489 if (dir.len < cwd.len && chdir(dir.buf))
1490 die(_("cannot change to '%s'"), dir.buf);
1491 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1492 break;
1493 case GIT_DIR_HIT_CEILING:
1494 if (!nongit_ok)
1495 die(_("not a git repository (or any of the parent directories): %s"),
1496 DEFAULT_GIT_DIR_ENVIRONMENT);
1497 *nongit_ok = 1;
1498 break;
1499 case GIT_DIR_HIT_MOUNT_POINT:
1500 if (!nongit_ok)
1501 die(_("not a git repository (or any parent up to mount point %s)\n"
1502 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1503 dir.buf);
1504 *nongit_ok = 1;
1505 break;
1506 case GIT_DIR_INVALID_OWNERSHIP:
1507 if (!nongit_ok) {
1508 struct strbuf quoted = STRBUF_INIT;
1510 strbuf_complete(&report, '\n');
1511 sq_quote_buf_pretty(&quoted, dir.buf);
1512 die(_("detected dubious ownership in repository at '%s'\n"
1513 "%s"
1514 "To add an exception for this directory, call:\n"
1515 "\n"
1516 "\tgit config --global --add safe.directory %s"),
1517 dir.buf, report.buf, quoted.buf);
1519 *nongit_ok = 1;
1520 break;
1521 case GIT_DIR_DISALLOWED_BARE:
1522 if (!nongit_ok) {
1523 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1524 dir.buf,
1525 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1527 *nongit_ok = 1;
1528 break;
1529 case GIT_DIR_CWD_FAILURE:
1530 case GIT_DIR_INVALID_FORMAT:
1532 * As a safeguard against setup_git_directory_gently_1 returning
1533 * these values, fallthrough to BUG. Otherwise it is possible to
1534 * set startup_info->have_repository to 1 when we did nothing to
1535 * find a repository.
1537 default:
1538 BUG("unhandled setup_git_directory_gently_1() result");
1542 * At this point, nongit_ok is stable. If it is non-NULL and points
1543 * to a non-zero value, then this means that we haven't found a
1544 * repository and that the caller expects startup_info to reflect
1545 * this.
1547 * Regardless of the state of nongit_ok, startup_info->prefix and
1548 * the GIT_PREFIX environment variable must always match. For details
1549 * see Documentation/config/alias.txt.
1551 if (nongit_ok && *nongit_ok)
1552 startup_info->have_repository = 0;
1553 else
1554 startup_info->have_repository = 1;
1557 * Not all paths through the setup code will call 'set_git_dir()' (which
1558 * directly sets up the environment) so in order to guarantee that the
1559 * environment is in a consistent state after setup, explicitly setup
1560 * the environment if we have a repository.
1562 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1563 * code paths so we also need to explicitly setup the environment if
1564 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1565 * GIT_DIR values at some point in the future.
1567 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1568 startup_info->have_repository ||
1569 /* GIT_DIR_EXPLICIT */
1570 getenv(GIT_DIR_ENVIRONMENT)) {
1571 if (!the_repository->gitdir) {
1572 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1573 if (!gitdir)
1574 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1575 setup_git_env(gitdir);
1577 if (startup_info->have_repository) {
1578 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1579 the_repository->repository_format_worktree_config =
1580 repo_fmt.worktree_config;
1581 /* take ownership of repo_fmt.partial_clone */
1582 the_repository->repository_format_partial_clone =
1583 repo_fmt.partial_clone;
1584 repo_fmt.partial_clone = NULL;
1588 * Since precompose_string_if_needed() needs to look at
1589 * the core.precomposeunicode configuration, this
1590 * has to happen after the above block that finds
1591 * out where the repository is, i.e. a preparation
1592 * for calling git_config_get_bool().
1594 if (prefix) {
1595 prefix = precompose_string_if_needed(prefix);
1596 startup_info->prefix = prefix;
1597 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1598 } else {
1599 startup_info->prefix = NULL;
1600 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1603 setup_original_cwd();
1605 strbuf_release(&dir);
1606 strbuf_release(&gitdir);
1607 strbuf_release(&report);
1608 clear_repository_format(&repo_fmt);
1610 return prefix;
1613 int git_config_perm(const char *var, const char *value)
1615 int i;
1616 char *endptr;
1618 if (!value)
1619 return PERM_GROUP;
1621 if (!strcmp(value, "umask"))
1622 return PERM_UMASK;
1623 if (!strcmp(value, "group"))
1624 return PERM_GROUP;
1625 if (!strcmp(value, "all") ||
1626 !strcmp(value, "world") ||
1627 !strcmp(value, "everybody"))
1628 return PERM_EVERYBODY;
1630 /* Parse octal numbers */
1631 i = strtol(value, &endptr, 8);
1633 /* If not an octal number, maybe true/false? */
1634 if (*endptr != 0)
1635 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1638 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1639 * a chmod value to restrict to.
1641 switch (i) {
1642 case PERM_UMASK: /* 0 */
1643 return PERM_UMASK;
1644 case OLD_PERM_GROUP: /* 1 */
1645 return PERM_GROUP;
1646 case OLD_PERM_EVERYBODY: /* 2 */
1647 return PERM_EVERYBODY;
1650 /* A filemode value was given: 0xxx */
1652 if ((i & 0600) != 0600)
1653 die(_("problem with core.sharedRepository filemode value "
1654 "(0%.3o).\nThe owner of files must always have "
1655 "read and write permissions."), i);
1658 * Mask filemode value. Others can not get write permission.
1659 * x flags for directories are handled separately.
1661 return -(i & 0666);
1664 void check_repository_format(struct repository_format *fmt)
1666 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1667 if (!fmt)
1668 fmt = &repo_fmt;
1669 check_repository_format_gently(get_git_dir(), fmt, NULL);
1670 startup_info->have_repository = 1;
1671 repo_set_hash_algo(the_repository, fmt->hash_algo);
1672 the_repository->repository_format_worktree_config =
1673 fmt->worktree_config;
1674 the_repository->repository_format_partial_clone =
1675 xstrdup_or_null(fmt->partial_clone);
1676 clear_repository_format(&repo_fmt);
1680 * Returns the "prefix", a path to the current working directory
1681 * relative to the work tree root, or NULL, if the current working
1682 * directory is not a strict subdirectory of the work tree root. The
1683 * prefix always ends with a '/' character.
1685 const char *setup_git_directory(void)
1687 return setup_git_directory_gently(NULL);
1690 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1692 if (is_git_directory(suspect))
1693 return suspect;
1694 return read_gitfile_gently(suspect, return_error_code);
1697 /* if any standard file descriptor is missing open it to /dev/null */
1698 void sanitize_stdfds(void)
1700 int fd = xopen("/dev/null", O_RDWR);
1701 while (fd < 2)
1702 fd = xdup(fd);
1703 if (fd > 2)
1704 close(fd);
1707 int daemonize(void)
1709 #ifdef NO_POSIX_GOODIES
1710 errno = ENOSYS;
1711 return -1;
1712 #else
1713 switch (fork()) {
1714 case 0:
1715 break;
1716 case -1:
1717 die_errno(_("fork failed"));
1718 default:
1719 exit(0);
1721 if (setsid() == -1)
1722 die_errno(_("setsid failed"));
1723 close(0);
1724 close(1);
1725 close(2);
1726 sanitize_stdfds();
1727 return 0;
1728 #endif
1731 struct template_dir_cb_data {
1732 char *path;
1733 int initialized;
1736 static int template_dir_cb(const char *key, const char *value,
1737 const struct config_context *ctx, void *d)
1739 struct template_dir_cb_data *data = d;
1741 if (strcmp(key, "init.templatedir"))
1742 return 0;
1744 if (!value) {
1745 data->path = NULL;
1746 } else {
1747 char *path = NULL;
1749 FREE_AND_NULL(data->path);
1750 if (!git_config_pathname((const char **)&path, key, value))
1751 data->path = path ? path : xstrdup(value);
1754 return 0;
1757 const char *get_template_dir(const char *option_template)
1759 const char *template_dir = option_template;
1761 if (!template_dir)
1762 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1763 if (!template_dir) {
1764 static struct template_dir_cb_data data;
1766 if (!data.initialized) {
1767 git_protected_config(template_dir_cb, &data);
1768 data.initialized = 1;
1770 template_dir = data.path;
1772 if (!template_dir) {
1773 static char *dir;
1775 if (!dir)
1776 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1777 template_dir = dir;
1779 return template_dir;
1782 #ifdef NO_TRUSTABLE_FILEMODE
1783 #define TEST_FILEMODE 0
1784 #else
1785 #define TEST_FILEMODE 1
1786 #endif
1788 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1790 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1791 DIR *dir)
1793 size_t path_baselen = path->len;
1794 size_t template_baselen = template_path->len;
1795 struct dirent *de;
1797 /* Note: if ".git/hooks" file exists in the repository being
1798 * re-initialized, /etc/core-git/templates/hooks/update would
1799 * cause "git init" to fail here. I think this is sane but
1800 * it means that the set of templates we ship by default, along
1801 * with the way the namespace under .git/ is organized, should
1802 * be really carefully chosen.
1804 safe_create_dir(path->buf, 1);
1805 while ((de = readdir(dir)) != NULL) {
1806 struct stat st_git, st_template;
1807 int exists = 0;
1809 strbuf_setlen(path, path_baselen);
1810 strbuf_setlen(template_path, template_baselen);
1812 if (de->d_name[0] == '.')
1813 continue;
1814 strbuf_addstr(path, de->d_name);
1815 strbuf_addstr(template_path, de->d_name);
1816 if (lstat(path->buf, &st_git)) {
1817 if (errno != ENOENT)
1818 die_errno(_("cannot stat '%s'"), path->buf);
1820 else
1821 exists = 1;
1823 if (lstat(template_path->buf, &st_template))
1824 die_errno(_("cannot stat template '%s'"), template_path->buf);
1826 if (S_ISDIR(st_template.st_mode)) {
1827 DIR *subdir = opendir(template_path->buf);
1828 if (!subdir)
1829 die_errno(_("cannot opendir '%s'"), template_path->buf);
1830 strbuf_addch(path, '/');
1831 strbuf_addch(template_path, '/');
1832 copy_templates_1(path, template_path, subdir);
1833 closedir(subdir);
1835 else if (exists)
1836 continue;
1837 else if (S_ISLNK(st_template.st_mode)) {
1838 struct strbuf lnk = STRBUF_INIT;
1839 if (strbuf_readlink(&lnk, template_path->buf,
1840 st_template.st_size) < 0)
1841 die_errno(_("cannot readlink '%s'"), template_path->buf);
1842 if (symlink(lnk.buf, path->buf))
1843 die_errno(_("cannot symlink '%s' '%s'"),
1844 lnk.buf, path->buf);
1845 strbuf_release(&lnk);
1847 else if (S_ISREG(st_template.st_mode)) {
1848 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1849 die_errno(_("cannot copy '%s' to '%s'"),
1850 template_path->buf, path->buf);
1852 else
1853 error(_("ignoring template %s"), template_path->buf);
1857 static void copy_templates(const char *option_template)
1859 const char *template_dir = get_template_dir(option_template);
1860 struct strbuf path = STRBUF_INIT;
1861 struct strbuf template_path = STRBUF_INIT;
1862 size_t template_len;
1863 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1864 struct strbuf err = STRBUF_INIT;
1865 DIR *dir;
1866 char *to_free = NULL;
1868 if (!template_dir || !*template_dir)
1869 return;
1871 strbuf_addstr(&template_path, template_dir);
1872 strbuf_complete(&template_path, '/');
1873 template_len = template_path.len;
1875 dir = opendir(template_path.buf);
1876 if (!dir) {
1877 warning(_("templates not found in %s"), template_dir);
1878 goto free_return;
1881 /* Make sure that template is from the correct vintage */
1882 strbuf_addstr(&template_path, "config");
1883 read_repository_format(&template_format, template_path.buf);
1884 strbuf_setlen(&template_path, template_len);
1887 * No mention of version at all is OK, but anything else should be
1888 * verified.
1890 if (template_format.version >= 0 &&
1891 verify_repository_format(&template_format, &err) < 0) {
1892 warning(_("not copying templates from '%s': %s"),
1893 template_dir, err.buf);
1894 strbuf_release(&err);
1895 goto close_free_return;
1898 strbuf_addstr(&path, get_git_common_dir());
1899 strbuf_complete(&path, '/');
1900 copy_templates_1(&path, &template_path, dir);
1901 close_free_return:
1902 closedir(dir);
1903 free_return:
1904 free(to_free);
1905 strbuf_release(&path);
1906 strbuf_release(&template_path);
1907 clear_repository_format(&template_format);
1911 * If the git_dir is not directly inside the working tree, then git will not
1912 * find it by default, and we need to set the worktree explicitly.
1914 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1916 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1917 return 0;
1918 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1919 !strcmp(git_dir, "/.git"))
1920 return 0;
1921 return 1;
1924 void initialize_repository_version(int hash_algo, int reinit)
1926 char repo_version_string[10];
1927 int repo_version = GIT_REPO_VERSION;
1929 if (hash_algo != GIT_HASH_SHA1)
1930 repo_version = GIT_REPO_VERSION_READ;
1932 /* This forces creation of new config file */
1933 xsnprintf(repo_version_string, sizeof(repo_version_string),
1934 "%d", repo_version);
1935 git_config_set("core.repositoryformatversion", repo_version_string);
1937 if (hash_algo != GIT_HASH_SHA1)
1938 git_config_set("extensions.objectformat",
1939 hash_algos[hash_algo].name);
1940 else if (reinit)
1941 git_config_set_gently("extensions.objectformat", NULL);
1944 static int create_default_files(const char *template_path,
1945 const char *original_git_dir,
1946 const char *initial_branch,
1947 const struct repository_format *fmt,
1948 int prev_bare_repository,
1949 int init_shared_repository,
1950 int quiet)
1952 struct stat st1;
1953 struct strbuf buf = STRBUF_INIT;
1954 char *path;
1955 char junk[2];
1956 int reinit;
1957 int filemode;
1958 struct strbuf err = STRBUF_INIT;
1959 const char *work_tree = get_git_work_tree();
1962 * First copy the templates -- we might have the default
1963 * config file there, in which case we would want to read
1964 * from it after installing.
1966 * Before reading that config, we also need to clear out any cached
1967 * values (since we've just potentially changed what's available on
1968 * disk).
1970 copy_templates(template_path);
1971 git_config_clear();
1972 reset_shared_repository();
1973 git_config(git_default_config, NULL);
1976 * We must make sure command-line options continue to override any
1977 * values we might have just re-read from the config.
1979 if (init_shared_repository != -1)
1980 set_shared_repository(init_shared_repository);
1982 * TODO: heed core.bare from config file in templates if no
1983 * command-line override given
1985 is_bare_repository_cfg = prev_bare_repository || !work_tree;
1986 /* TODO (continued):
1988 * Unfortunately, the line above is equivalent to
1989 * is_bare_repository_cfg = !work_tree;
1990 * which ignores the config entirely even if no `--[no-]bare`
1991 * command line option was present.
1993 * To see why, note that before this function, there was this call:
1994 * prev_bare_repository = is_bare_repository()
1995 * expanding the right hand side:
1996 * = is_bare_repository_cfg && !get_git_work_tree()
1997 * = is_bare_repository_cfg && !work_tree
1998 * note that the last simplification above is valid because nothing
1999 * calls repo_init() or set_git_work_tree() between any of the
2000 * relevant calls in the code, and thus the !get_git_work_tree()
2001 * calls will return the same result each time. So, what we are
2002 * interested in computing is the right hand side of the line of
2003 * code just above this comment:
2004 * prev_bare_repository || !work_tree
2005 * = is_bare_repository_cfg && !work_tree || !work_tree
2006 * = !work_tree
2007 * because "A && !B || !B == !B" for all boolean values of A & B.
2011 * We would have created the above under user's umask -- under
2012 * shared-repository settings, we would need to fix them up.
2014 if (get_shared_repository()) {
2015 adjust_shared_perm(get_git_dir());
2019 * We need to create a "refs" dir in any case so that older
2020 * versions of git can tell that this is a repository.
2022 safe_create_dir(git_path("refs"), 1);
2023 adjust_shared_perm(git_path("refs"));
2025 if (refs_init_db(&err))
2026 die("failed to set up refs db: %s", err.buf);
2029 * Point the HEAD symref to the initial branch with if HEAD does
2030 * not yet exist.
2032 path = git_path_buf(&buf, "HEAD");
2033 reinit = (!access(path, R_OK)
2034 || readlink(path, junk, sizeof(junk)-1) != -1);
2035 if (!reinit) {
2036 char *ref;
2038 if (!initial_branch)
2039 initial_branch = git_default_branch_name(quiet);
2041 ref = xstrfmt("refs/heads/%s", initial_branch);
2042 if (check_refname_format(ref, 0) < 0)
2043 die(_("invalid initial branch name: '%s'"),
2044 initial_branch);
2046 if (create_symref("HEAD", ref, NULL) < 0)
2047 exit(1);
2048 free(ref);
2051 initialize_repository_version(fmt->hash_algo, 0);
2053 /* Check filemode trustability */
2054 path = git_path_buf(&buf, "config");
2055 filemode = TEST_FILEMODE;
2056 if (TEST_FILEMODE && !lstat(path, &st1)) {
2057 struct stat st2;
2058 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2059 !lstat(path, &st2) &&
2060 st1.st_mode != st2.st_mode &&
2061 !chmod(path, st1.st_mode));
2062 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2063 filemode = 0;
2065 git_config_set("core.filemode", filemode ? "true" : "false");
2067 if (is_bare_repository())
2068 git_config_set("core.bare", "true");
2069 else {
2070 git_config_set("core.bare", "false");
2071 /* allow template config file to override the default */
2072 if (log_all_ref_updates == LOG_REFS_UNSET)
2073 git_config_set("core.logallrefupdates", "true");
2074 if (needs_work_tree_config(original_git_dir, work_tree))
2075 git_config_set("core.worktree", work_tree);
2078 if (!reinit) {
2079 /* Check if symlink is supported in the work tree */
2080 path = git_path_buf(&buf, "tXXXXXX");
2081 if (!close(xmkstemp(path)) &&
2082 !unlink(path) &&
2083 !symlink("testing", path) &&
2084 !lstat(path, &st1) &&
2085 S_ISLNK(st1.st_mode))
2086 unlink(path); /* good */
2087 else
2088 git_config_set("core.symlinks", "false");
2090 /* Check if the filesystem is case-insensitive */
2091 path = git_path_buf(&buf, "CoNfIg");
2092 if (!access(path, F_OK))
2093 git_config_set("core.ignorecase", "true");
2094 probe_utf8_pathname_composition();
2097 strbuf_release(&buf);
2098 return reinit;
2101 static void create_object_directory(void)
2103 struct strbuf path = STRBUF_INIT;
2104 size_t baselen;
2106 strbuf_addstr(&path, get_object_directory());
2107 baselen = path.len;
2109 safe_create_dir(path.buf, 1);
2111 strbuf_setlen(&path, baselen);
2112 strbuf_addstr(&path, "/pack");
2113 safe_create_dir(path.buf, 1);
2115 strbuf_setlen(&path, baselen);
2116 strbuf_addstr(&path, "/info");
2117 safe_create_dir(path.buf, 1);
2119 strbuf_release(&path);
2122 static void separate_git_dir(const char *git_dir, const char *git_link)
2124 struct stat st;
2126 if (!stat(git_link, &st)) {
2127 const char *src;
2129 if (S_ISREG(st.st_mode))
2130 src = read_gitfile(git_link);
2131 else if (S_ISDIR(st.st_mode))
2132 src = git_link;
2133 else
2134 die(_("unable to handle file type %d"), (int)st.st_mode);
2136 if (rename(src, git_dir))
2137 die_errno(_("unable to move %s to %s"), src, git_dir);
2138 repair_worktrees(NULL, NULL);
2141 write_file(git_link, "gitdir: %s", git_dir);
2144 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2146 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2148 * If we already have an initialized repo, don't allow the user to
2149 * specify a different algorithm, as that could cause corruption.
2150 * Otherwise, if the user has specified one on the command line, use it.
2152 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2153 die(_("attempt to reinitialize repository with different hash"));
2154 else if (hash != GIT_HASH_UNKNOWN)
2155 repo_fmt->hash_algo = hash;
2156 else if (env) {
2157 int env_algo = hash_algo_by_name(env);
2158 if (env_algo == GIT_HASH_UNKNOWN)
2159 die(_("unknown hash algorithm '%s'"), env);
2160 repo_fmt->hash_algo = env_algo;
2164 int init_db(const char *git_dir, const char *real_git_dir,
2165 const char *template_dir, int hash, const char *initial_branch,
2166 int init_shared_repository, unsigned int flags)
2168 int reinit;
2169 int exist_ok = flags & INIT_DB_EXIST_OK;
2170 char *original_git_dir = real_pathdup(git_dir, 1);
2171 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2172 int prev_bare_repository;
2174 if (real_git_dir) {
2175 struct stat st;
2177 if (!exist_ok && !stat(git_dir, &st))
2178 die(_("%s already exists"), git_dir);
2180 if (!exist_ok && !stat(real_git_dir, &st))
2181 die(_("%s already exists"), real_git_dir);
2183 set_git_dir(real_git_dir, 1);
2184 git_dir = get_git_dir();
2185 separate_git_dir(git_dir, original_git_dir);
2187 else {
2188 set_git_dir(git_dir, 1);
2189 git_dir = get_git_dir();
2191 startup_info->have_repository = 1;
2193 /* Ensure `core.hidedotfiles` is processed */
2194 git_config(platform_core_config, NULL);
2196 safe_create_dir(git_dir, 0);
2198 prev_bare_repository = is_bare_repository();
2200 /* Check to see if the repository version is right.
2201 * Note that a newly created repository does not have
2202 * config file, so this will not fail. What we are catching
2203 * is an attempt to reinitialize new repository with an old tool.
2205 check_repository_format(&repo_fmt);
2207 validate_hash_algorithm(&repo_fmt, hash);
2209 reinit = create_default_files(template_dir, original_git_dir,
2210 initial_branch, &repo_fmt,
2211 prev_bare_repository,
2212 init_shared_repository,
2213 flags & INIT_DB_QUIET);
2214 if (reinit && initial_branch)
2215 warning(_("re-init: ignored --initial-branch=%s"),
2216 initial_branch);
2218 create_object_directory();
2220 if (get_shared_repository()) {
2221 char buf[10];
2222 /* We do not spell "group" and such, so that
2223 * the configuration can be read by older version
2224 * of git. Note, we use octal numbers for new share modes,
2225 * and compatibility values for PERM_GROUP and
2226 * PERM_EVERYBODY.
2228 if (get_shared_repository() < 0)
2229 /* force to the mode value */
2230 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2231 else if (get_shared_repository() == PERM_GROUP)
2232 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2233 else if (get_shared_repository() == PERM_EVERYBODY)
2234 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2235 else
2236 BUG("invalid value for shared_repository");
2237 git_config_set("core.sharedrepository", buf);
2238 git_config_set("receive.denyNonFastforwards", "true");
2241 if (!(flags & INIT_DB_QUIET)) {
2242 int len = strlen(git_dir);
2244 if (reinit)
2245 printf(get_shared_repository()
2246 ? _("Reinitialized existing shared Git repository in %s%s\n")
2247 : _("Reinitialized existing Git repository in %s%s\n"),
2248 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2249 else
2250 printf(get_shared_repository()
2251 ? _("Initialized empty shared Git repository in %s%s\n")
2252 : _("Initialized empty Git repository in %s%s\n"),
2253 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2256 free(original_git_dir);
2257 return 0;