push: avoid showing false negotiation errors
[git/gitster.git] / setup.c
bloba4de5c7b5a28eb23c8a0af616c37c1ba9f38e9ac
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 "quote.h"
17 #include "trace2.h"
18 #include "worktree.h"
19 #include "exec-cmd.h"
21 static int inside_git_dir = -1;
22 static int inside_work_tree = -1;
23 static int work_tree_config_is_bogus;
24 enum allowed_bare_repo {
25 ALLOWED_BARE_REPO_EXPLICIT = 0,
26 ALLOWED_BARE_REPO_ALL,
29 static struct startup_info the_startup_info;
30 struct startup_info *startup_info = &the_startup_info;
31 const char *tmp_original_cwd;
34 * The input parameter must contain an absolute path, and it must already be
35 * normalized.
37 * Find the part of an absolute path that lies inside the work tree by
38 * dereferencing symlinks outside the work tree, for example:
39 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
40 * /dir/file (work tree is /) -> dir/file
41 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
42 * /dir/repolink/file (repolink points to /dir/repo) -> file
43 * /dir/repo (exactly equal to work tree) -> (empty string)
45 static int abspath_part_inside_repo(char *path)
47 size_t len;
48 size_t wtlen;
49 char *path0;
50 int off;
51 const char *work_tree = get_git_work_tree();
52 struct strbuf realpath = STRBUF_INIT;
54 if (!work_tree)
55 return -1;
56 wtlen = strlen(work_tree);
57 len = strlen(path);
58 off = offset_1st_component(path);
60 /* check if work tree is already the prefix */
61 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
62 if (path[wtlen] == '/') {
63 memmove(path, path + wtlen + 1, len - wtlen);
64 return 0;
65 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
66 /* work tree is the root, or the whole path */
67 memmove(path, path + wtlen, len - wtlen + 1);
68 return 0;
70 /* work tree might match beginning of a symlink to work tree */
71 off = wtlen;
73 path0 = path;
74 path += off;
76 /* check each '/'-terminated level */
77 while (*path) {
78 path++;
79 if (*path == '/') {
80 *path = '\0';
81 strbuf_realpath(&realpath, path0, 1);
82 if (fspathcmp(realpath.buf, work_tree) == 0) {
83 memmove(path0, path + 1, len - (path - path0));
84 strbuf_release(&realpath);
85 return 0;
87 *path = '/';
91 /* check whole path */
92 strbuf_realpath(&realpath, path0, 1);
93 if (fspathcmp(realpath.buf, work_tree) == 0) {
94 *path0 = '\0';
95 strbuf_release(&realpath);
96 return 0;
99 strbuf_release(&realpath);
100 return -1;
104 * Normalize "path", prepending the "prefix" for relative paths. If
105 * remaining_prefix is not NULL, return the actual prefix still
106 * remains in the path. For example, prefix = sub1/sub2/ and path is
108 * foo -> sub1/sub2/foo (full prefix)
109 * ../foo -> sub1/foo (remaining prefix is sub1/)
110 * ../../bar -> bar (no remaining prefix)
111 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
112 * `pwd`/../bar -> sub1/bar (no remaining prefix)
114 char *prefix_path_gently(const char *prefix, int len,
115 int *remaining_prefix, const char *path)
117 const char *orig = path;
118 char *sanitized;
119 if (is_absolute_path(orig)) {
120 sanitized = xmallocz(strlen(path));
121 if (remaining_prefix)
122 *remaining_prefix = 0;
123 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
124 free(sanitized);
125 return NULL;
127 if (abspath_part_inside_repo(sanitized)) {
128 free(sanitized);
129 return NULL;
131 } else {
132 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
133 if (remaining_prefix)
134 *remaining_prefix = len;
135 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
136 free(sanitized);
137 return NULL;
140 return sanitized;
143 char *prefix_path(const char *prefix, int len, const char *path)
145 char *r = prefix_path_gently(prefix, len, NULL, path);
146 if (!r) {
147 const char *hint_path = get_git_work_tree();
148 if (!hint_path)
149 hint_path = get_git_dir();
150 die(_("'%s' is outside repository at '%s'"), path,
151 absolute_path(hint_path));
153 return r;
156 int path_inside_repo(const char *prefix, const char *path)
158 int len = prefix ? strlen(prefix) : 0;
159 char *r = prefix_path_gently(prefix, len, NULL, path);
160 if (r) {
161 free(r);
162 return 1;
164 return 0;
167 int check_filename(const char *prefix, const char *arg)
169 char *to_free = NULL;
170 struct stat st;
172 if (skip_prefix(arg, ":/", &arg)) {
173 if (!*arg) /* ":/" is root dir, always exists */
174 return 1;
175 prefix = NULL;
176 } else if (skip_prefix(arg, ":!", &arg) ||
177 skip_prefix(arg, ":^", &arg)) {
178 if (!*arg) /* excluding everything is silly, but allowed */
179 return 1;
182 if (prefix)
183 arg = to_free = prefix_filename(prefix, arg);
185 if (!lstat(arg, &st)) {
186 free(to_free);
187 return 1; /* file exists */
189 if (is_missing_file_error(errno)) {
190 free(to_free);
191 return 0; /* file does not exist */
193 die_errno(_("failed to stat '%s'"), arg);
196 static void NORETURN die_verify_filename(struct repository *r,
197 const char *prefix,
198 const char *arg,
199 int diagnose_misspelt_rev)
201 if (!diagnose_misspelt_rev)
202 die(_("%s: no such path in the working tree.\n"
203 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
204 arg);
206 * Saying "'(icase)foo' does not exist in the index" when the
207 * user gave us ":(icase)foo" is just stupid. A magic pathspec
208 * begins with a colon and is followed by a non-alnum; do not
209 * let maybe_die_on_misspelt_object_name() even trigger.
211 if (!(arg[0] == ':' && !isalnum(arg[1])))
212 maybe_die_on_misspelt_object_name(r, arg, prefix);
214 /* ... or fall back the most general message. */
215 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
216 "Use '--' to separate paths from revisions, like this:\n"
217 "'git <command> [<revision>...] -- [<file>...]'"), arg);
222 * Check for arguments that don't resolve as actual files,
223 * but which look sufficiently like pathspecs that we'll consider
224 * them such for the purposes of rev/pathspec DWIM parsing.
226 static int looks_like_pathspec(const char *arg)
228 const char *p;
229 int escaped = 0;
232 * Wildcard characters imply the user is looking to match pathspecs
233 * that aren't in the filesystem. Note that this doesn't include
234 * backslash even though it's a glob special; by itself it doesn't
235 * cause any increase in the match. Likewise ignore backslash-escaped
236 * wildcard characters.
238 for (p = arg; *p; p++) {
239 if (escaped) {
240 escaped = 0;
241 } else if (is_glob_special(*p)) {
242 if (*p == '\\')
243 escaped = 1;
244 else
245 return 1;
249 /* long-form pathspec magic */
250 if (starts_with(arg, ":("))
251 return 1;
253 return 0;
257 * Verify a filename that we got as an argument for a pathspec
258 * entry. Note that a filename that begins with "-" never verifies
259 * as true, because even if such a filename were to exist, we want
260 * it to be preceded by the "--" marker (or we want the user to
261 * use a format like "./-filename")
263 * The "diagnose_misspelt_rev" is used to provide a user-friendly
264 * diagnosis when dying upon finding that "name" is not a pathname.
265 * If set to 1, the diagnosis will try to diagnose "name" as an
266 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
267 * will only complain about an inexisting file.
269 * This function is typically called to check that a "file or rev"
270 * argument is unambiguous. In this case, the caller will want
271 * diagnose_misspelt_rev == 1 when verifying the first non-rev
272 * argument (which could have been a revision), and
273 * diagnose_misspelt_rev == 0 for the next ones (because we already
274 * saw a filename, there's not ambiguity anymore).
276 void verify_filename(const char *prefix,
277 const char *arg,
278 int diagnose_misspelt_rev)
280 if (*arg == '-')
281 die(_("option '%s' must come before non-option arguments"), arg);
282 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
283 return;
284 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
288 * Opposite of the above: the command line did not have -- marker
289 * and we parsed the arg as a refname. It should not be interpretable
290 * as a filename.
292 void verify_non_filename(const char *prefix, const char *arg)
294 if (!is_inside_work_tree() || is_inside_git_dir())
295 return;
296 if (*arg == '-')
297 return; /* flag */
298 if (!check_filename(prefix, arg))
299 return;
300 die(_("ambiguous argument '%s': both revision and filename\n"
301 "Use '--' to separate paths from revisions, like this:\n"
302 "'git <command> [<revision>...] -- [<file>...]'"), arg);
305 int get_common_dir(struct strbuf *sb, const char *gitdir)
307 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
308 if (git_env_common_dir) {
309 strbuf_addstr(sb, git_env_common_dir);
310 return 1;
311 } else {
312 return get_common_dir_noenv(sb, gitdir);
316 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
318 struct strbuf data = STRBUF_INIT;
319 struct strbuf path = STRBUF_INIT;
320 int ret = 0;
322 strbuf_addf(&path, "%s/commondir", gitdir);
323 if (file_exists(path.buf)) {
324 if (strbuf_read_file(&data, path.buf, 0) <= 0)
325 die_errno(_("failed to read %s"), path.buf);
326 while (data.len && (data.buf[data.len - 1] == '\n' ||
327 data.buf[data.len - 1] == '\r'))
328 data.len--;
329 data.buf[data.len] = '\0';
330 strbuf_reset(&path);
331 if (!is_absolute_path(data.buf))
332 strbuf_addf(&path, "%s/", gitdir);
333 strbuf_addbuf(&path, &data);
334 strbuf_add_real_path(sb, path.buf);
335 ret = 1;
336 } else {
337 strbuf_addstr(sb, gitdir);
340 strbuf_release(&data);
341 strbuf_release(&path);
342 return ret;
346 * Test if it looks like we're at a git directory.
347 * We want to see:
349 * - either an objects/ directory _or_ the proper
350 * GIT_OBJECT_DIRECTORY environment variable
351 * - a refs/ directory
352 * - either a HEAD symlink or a HEAD file that is formatted as
353 * a proper "ref:", or a regular file HEAD that has a properly
354 * formatted sha1 object name.
356 int is_git_directory(const char *suspect)
358 struct strbuf path = STRBUF_INIT;
359 int ret = 0;
360 size_t len;
362 /* Check worktree-related signatures */
363 strbuf_addstr(&path, suspect);
364 strbuf_complete(&path, '/');
365 strbuf_addstr(&path, "HEAD");
366 if (validate_headref(path.buf))
367 goto done;
369 strbuf_reset(&path);
370 get_common_dir(&path, suspect);
371 len = path.len;
373 /* Check non-worktree-related signatures */
374 if (getenv(DB_ENVIRONMENT)) {
375 if (access(getenv(DB_ENVIRONMENT), X_OK))
376 goto done;
378 else {
379 strbuf_setlen(&path, len);
380 strbuf_addstr(&path, "/objects");
381 if (access(path.buf, X_OK))
382 goto done;
385 strbuf_setlen(&path, len);
386 strbuf_addstr(&path, "/refs");
387 if (access(path.buf, X_OK))
388 goto done;
390 ret = 1;
391 done:
392 strbuf_release(&path);
393 return ret;
396 int is_nonbare_repository_dir(struct strbuf *path)
398 int ret = 0;
399 int gitfile_error;
400 size_t orig_path_len = path->len;
401 assert(orig_path_len != 0);
402 strbuf_complete(path, '/');
403 strbuf_addstr(path, ".git");
404 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
405 ret = 1;
406 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
407 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
408 ret = 1;
409 strbuf_setlen(path, orig_path_len);
410 return ret;
413 int is_inside_git_dir(void)
415 if (inside_git_dir < 0)
416 inside_git_dir = is_inside_dir(get_git_dir());
417 return inside_git_dir;
420 int is_inside_work_tree(void)
422 if (inside_work_tree < 0)
423 inside_work_tree = is_inside_dir(get_git_work_tree());
424 return inside_work_tree;
427 void setup_work_tree(void)
429 const char *work_tree;
430 static int initialized = 0;
432 if (initialized)
433 return;
435 if (work_tree_config_is_bogus)
436 die(_("unable to set up work tree using invalid config"));
438 work_tree = get_git_work_tree();
439 if (!work_tree || chdir_notify(work_tree))
440 die(_("this operation must be run in a work tree"));
443 * Make sure subsequent git processes find correct worktree
444 * if $GIT_WORK_TREE is set relative
446 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
447 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
449 initialized = 1;
452 static void setup_original_cwd(void)
454 struct strbuf tmp = STRBUF_INIT;
455 const char *worktree = NULL;
456 int offset = -1;
458 if (!tmp_original_cwd)
459 return;
462 * startup_info->original_cwd points to the current working
463 * directory we inherited from our parent process, which is a
464 * directory we want to avoid removing.
466 * For convience, we would like to have the path relative to the
467 * worktree instead of an absolute path.
469 * Yes, startup_info->original_cwd is usually the same as 'prefix',
470 * but differs in two ways:
471 * - prefix has a trailing '/'
472 * - if the user passes '-C' to git, that modifies the prefix but
473 * not startup_info->original_cwd.
476 /* Normalize the directory */
477 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
478 trace2_data_string("setup", the_repository,
479 "realpath-path", tmp_original_cwd);
480 trace2_data_string("setup", the_repository,
481 "realpath-failure", strerror(errno));
482 free((char*)tmp_original_cwd);
483 tmp_original_cwd = NULL;
484 return;
487 free((char*)tmp_original_cwd);
488 tmp_original_cwd = NULL;
489 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
492 * Get our worktree; we only protect the current working directory
493 * if it's in the worktree.
495 worktree = get_git_work_tree();
496 if (!worktree)
497 goto no_prevention_needed;
499 offset = dir_inside_of(startup_info->original_cwd, worktree);
500 if (offset >= 0) {
502 * If startup_info->original_cwd == worktree, that is already
503 * protected and we don't need original_cwd as a secondary
504 * protection measure.
506 if (!*(startup_info->original_cwd + offset))
507 goto no_prevention_needed;
510 * original_cwd was inside worktree; precompose it just as
511 * we do prefix so that built up paths will match
513 startup_info->original_cwd = \
514 precompose_string_if_needed(startup_info->original_cwd
515 + offset);
516 return;
519 no_prevention_needed:
520 free((char*)startup_info->original_cwd);
521 startup_info->original_cwd = NULL;
524 static int read_worktree_config(const char *var, const char *value,
525 const struct config_context *ctx UNUSED,
526 void *vdata)
528 struct repository_format *data = vdata;
530 if (strcmp(var, "core.bare") == 0) {
531 data->is_bare = git_config_bool(var, value);
532 } else if (strcmp(var, "core.worktree") == 0) {
533 if (!value)
534 return config_error_nonbool(var);
535 free(data->work_tree);
536 data->work_tree = xstrdup(value);
538 return 0;
541 enum extension_result {
542 EXTENSION_ERROR = -1, /* compatible with error(), etc */
543 EXTENSION_UNKNOWN = 0,
544 EXTENSION_OK = 1
548 * Do not add new extensions to this function. It handles extensions which are
549 * respected even in v0-format repositories for historical compatibility.
551 static enum extension_result handle_extension_v0(const char *var,
552 const char *value,
553 const char *ext,
554 struct repository_format *data)
556 if (!strcmp(ext, "noop")) {
557 return EXTENSION_OK;
558 } else if (!strcmp(ext, "preciousobjects")) {
559 data->precious_objects = git_config_bool(var, value);
560 return EXTENSION_OK;
561 } else if (!strcmp(ext, "partialclone")) {
562 if (!value)
563 return config_error_nonbool(var);
564 data->partial_clone = xstrdup(value);
565 return EXTENSION_OK;
566 } else if (!strcmp(ext, "worktreeconfig")) {
567 data->worktree_config = git_config_bool(var, value);
568 return EXTENSION_OK;
571 return EXTENSION_UNKNOWN;
575 * Record any new extensions in this function.
577 static enum extension_result handle_extension(const char *var,
578 const char *value,
579 const char *ext,
580 struct repository_format *data)
582 if (!strcmp(ext, "noop-v1")) {
583 return EXTENSION_OK;
584 } else if (!strcmp(ext, "objectformat")) {
585 int format;
587 if (!value)
588 return config_error_nonbool(var);
589 format = hash_algo_by_name(value);
590 if (format == GIT_HASH_UNKNOWN)
591 return error(_("invalid value for '%s': '%s'"),
592 "extensions.objectformat", value);
593 data->hash_algo = format;
594 return EXTENSION_OK;
596 return EXTENSION_UNKNOWN;
599 static int check_repo_format(const char *var, const char *value,
600 const struct config_context *ctx, void *vdata)
602 struct repository_format *data = vdata;
603 const char *ext;
605 if (strcmp(var, "core.repositoryformatversion") == 0)
606 data->version = git_config_int(var, value, ctx->kvi);
607 else if (skip_prefix(var, "extensions.", &ext)) {
608 switch (handle_extension_v0(var, value, ext, data)) {
609 case EXTENSION_ERROR:
610 return -1;
611 case EXTENSION_OK:
612 return 0;
613 case EXTENSION_UNKNOWN:
614 break;
617 switch (handle_extension(var, value, ext, data)) {
618 case EXTENSION_ERROR:
619 return -1;
620 case EXTENSION_OK:
621 string_list_append(&data->v1_only_extensions, ext);
622 return 0;
623 case EXTENSION_UNKNOWN:
624 string_list_append(&data->unknown_extensions, ext);
625 return 0;
629 return read_worktree_config(var, value, ctx, vdata);
632 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
634 struct strbuf sb = STRBUF_INIT;
635 struct strbuf err = STRBUF_INIT;
636 int has_common;
638 has_common = get_common_dir(&sb, gitdir);
639 strbuf_addstr(&sb, "/config");
640 read_repository_format(candidate, sb.buf);
641 strbuf_release(&sb);
644 * For historical use of check_repository_format() in git-init,
645 * we treat a missing config as a silent "ok", even when nongit_ok
646 * is unset.
648 if (candidate->version < 0)
649 return 0;
651 if (verify_repository_format(candidate, &err) < 0) {
652 if (nongit_ok) {
653 warning("%s", err.buf);
654 strbuf_release(&err);
655 *nongit_ok = -1;
656 return -1;
658 die("%s", err.buf);
661 repository_format_precious_objects = candidate->precious_objects;
662 string_list_clear(&candidate->unknown_extensions, 0);
663 string_list_clear(&candidate->v1_only_extensions, 0);
665 if (candidate->worktree_config) {
667 * pick up core.bare and core.worktree from per-worktree
668 * config if present
670 strbuf_addf(&sb, "%s/config.worktree", gitdir);
671 git_config_from_file(read_worktree_config, sb.buf, candidate);
672 strbuf_release(&sb);
673 has_common = 0;
676 if (!has_common) {
677 if (candidate->is_bare != -1) {
678 is_bare_repository_cfg = candidate->is_bare;
679 if (is_bare_repository_cfg == 1)
680 inside_work_tree = -1;
682 if (candidate->work_tree) {
683 free(git_work_tree_cfg);
684 git_work_tree_cfg = xstrdup(candidate->work_tree);
685 inside_work_tree = -1;
689 return 0;
692 int upgrade_repository_format(int target_version)
694 struct strbuf sb = STRBUF_INIT;
695 struct strbuf err = STRBUF_INIT;
696 struct strbuf repo_version = STRBUF_INIT;
697 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
698 int ret;
700 strbuf_git_common_path(&sb, the_repository, "config");
701 read_repository_format(&repo_fmt, sb.buf);
702 strbuf_release(&sb);
704 if (repo_fmt.version >= target_version) {
705 ret = 0;
706 goto out;
709 if (verify_repository_format(&repo_fmt, &err) < 0) {
710 ret = error("cannot upgrade repository format from %d to %d: %s",
711 repo_fmt.version, target_version, err.buf);
712 goto out;
714 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
715 ret = error("cannot upgrade repository format: "
716 "unknown extension %s",
717 repo_fmt.unknown_extensions.items[0].string);
718 goto out;
721 strbuf_addf(&repo_version, "%d", target_version);
722 git_config_set("core.repositoryformatversion", repo_version.buf);
724 ret = 1;
726 out:
727 clear_repository_format(&repo_fmt);
728 strbuf_release(&repo_version);
729 strbuf_release(&err);
730 return ret;
733 static void init_repository_format(struct repository_format *format)
735 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
737 memcpy(format, &fresh, sizeof(fresh));
740 int read_repository_format(struct repository_format *format, const char *path)
742 clear_repository_format(format);
743 git_config_from_file(check_repo_format, path, format);
744 if (format->version == -1)
745 clear_repository_format(format);
746 return format->version;
749 void clear_repository_format(struct repository_format *format)
751 string_list_clear(&format->unknown_extensions, 0);
752 string_list_clear(&format->v1_only_extensions, 0);
753 free(format->work_tree);
754 free(format->partial_clone);
755 init_repository_format(format);
758 int verify_repository_format(const struct repository_format *format,
759 struct strbuf *err)
761 if (GIT_REPO_VERSION_READ < format->version) {
762 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
763 GIT_REPO_VERSION_READ, format->version);
764 return -1;
767 if (format->version >= 1 && format->unknown_extensions.nr) {
768 int i;
770 strbuf_addstr(err, Q_("unknown repository extension found:",
771 "unknown repository extensions found:",
772 format->unknown_extensions.nr));
774 for (i = 0; i < format->unknown_extensions.nr; i++)
775 strbuf_addf(err, "\n\t%s",
776 format->unknown_extensions.items[i].string);
777 return -1;
780 if (format->version == 0 && format->v1_only_extensions.nr) {
781 int i;
783 strbuf_addstr(err,
784 Q_("repo version is 0, but v1-only extension found:",
785 "repo version is 0, but v1-only extensions found:",
786 format->v1_only_extensions.nr));
788 for (i = 0; i < format->v1_only_extensions.nr; i++)
789 strbuf_addf(err, "\n\t%s",
790 format->v1_only_extensions.items[i].string);
791 return -1;
794 return 0;
797 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
799 switch (error_code) {
800 case READ_GITFILE_ERR_STAT_FAILED:
801 case READ_GITFILE_ERR_NOT_A_FILE:
802 /* non-fatal; follow return path */
803 break;
804 case READ_GITFILE_ERR_OPEN_FAILED:
805 die_errno(_("error opening '%s'"), path);
806 case READ_GITFILE_ERR_TOO_LARGE:
807 die(_("too large to be a .git file: '%s'"), path);
808 case READ_GITFILE_ERR_READ_FAILED:
809 die(_("error reading %s"), path);
810 case READ_GITFILE_ERR_INVALID_FORMAT:
811 die(_("invalid gitfile format: %s"), path);
812 case READ_GITFILE_ERR_NO_PATH:
813 die(_("no path in gitfile: %s"), path);
814 case READ_GITFILE_ERR_NOT_A_REPO:
815 die(_("not a git repository: %s"), dir);
816 default:
817 BUG("unknown error code");
822 * Try to read the location of the git directory from the .git file,
823 * return path to git directory if found. The return value comes from
824 * a shared buffer.
826 * On failure, if return_error_code is not NULL, return_error_code
827 * will be set to an error code and NULL will be returned. If
828 * return_error_code is NULL the function will die instead (for most
829 * cases).
831 const char *read_gitfile_gently(const char *path, int *return_error_code)
833 const int max_file_size = 1 << 20; /* 1MB */
834 int error_code = 0;
835 char *buf = NULL;
836 char *dir = NULL;
837 const char *slash;
838 struct stat st;
839 int fd;
840 ssize_t len;
841 static struct strbuf realpath = STRBUF_INIT;
843 if (stat(path, &st)) {
844 /* NEEDSWORK: discern between ENOENT vs other errors */
845 error_code = READ_GITFILE_ERR_STAT_FAILED;
846 goto cleanup_return;
848 if (!S_ISREG(st.st_mode)) {
849 error_code = READ_GITFILE_ERR_NOT_A_FILE;
850 goto cleanup_return;
852 if (st.st_size > max_file_size) {
853 error_code = READ_GITFILE_ERR_TOO_LARGE;
854 goto cleanup_return;
856 fd = open(path, O_RDONLY);
857 if (fd < 0) {
858 error_code = READ_GITFILE_ERR_OPEN_FAILED;
859 goto cleanup_return;
861 buf = xmallocz(st.st_size);
862 len = read_in_full(fd, buf, st.st_size);
863 close(fd);
864 if (len != st.st_size) {
865 error_code = READ_GITFILE_ERR_READ_FAILED;
866 goto cleanup_return;
868 if (!starts_with(buf, "gitdir: ")) {
869 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
870 goto cleanup_return;
872 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
873 len--;
874 if (len < 9) {
875 error_code = READ_GITFILE_ERR_NO_PATH;
876 goto cleanup_return;
878 buf[len] = '\0';
879 dir = buf + 8;
881 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
882 size_t pathlen = slash+1 - path;
883 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
884 (int)(len - 8), buf + 8);
885 free(buf);
886 buf = dir;
888 if (!is_git_directory(dir)) {
889 error_code = READ_GITFILE_ERR_NOT_A_REPO;
890 goto cleanup_return;
893 strbuf_realpath(&realpath, dir, 1);
894 path = realpath.buf;
896 cleanup_return:
897 if (return_error_code)
898 *return_error_code = error_code;
899 else if (error_code)
900 read_gitfile_error_die(error_code, path, dir);
902 free(buf);
903 return error_code ? NULL : path;
906 static const char *setup_explicit_git_dir(const char *gitdirenv,
907 struct strbuf *cwd,
908 struct repository_format *repo_fmt,
909 int *nongit_ok)
911 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
912 const char *worktree;
913 char *gitfile;
914 int offset;
916 if (PATH_MAX - 40 < strlen(gitdirenv))
917 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
919 gitfile = (char*)read_gitfile(gitdirenv);
920 if (gitfile) {
921 gitfile = xstrdup(gitfile);
922 gitdirenv = gitfile;
925 if (!is_git_directory(gitdirenv)) {
926 if (nongit_ok) {
927 *nongit_ok = 1;
928 free(gitfile);
929 return NULL;
931 die(_("not a git repository: '%s'"), gitdirenv);
934 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
935 free(gitfile);
936 return NULL;
939 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
940 if (work_tree_env)
941 set_git_work_tree(work_tree_env);
942 else if (is_bare_repository_cfg > 0) {
943 if (git_work_tree_cfg) {
944 /* #22.2, #30 */
945 warning("core.bare and core.worktree do not make sense");
946 work_tree_config_is_bogus = 1;
949 /* #18, #26 */
950 set_git_dir(gitdirenv, 0);
951 free(gitfile);
952 return NULL;
954 else if (git_work_tree_cfg) { /* #6, #14 */
955 if (is_absolute_path(git_work_tree_cfg))
956 set_git_work_tree(git_work_tree_cfg);
957 else {
958 char *core_worktree;
959 if (chdir(gitdirenv))
960 die_errno(_("cannot chdir to '%s'"), gitdirenv);
961 if (chdir(git_work_tree_cfg))
962 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
963 core_worktree = xgetcwd();
964 if (chdir(cwd->buf))
965 die_errno(_("cannot come back to cwd"));
966 set_git_work_tree(core_worktree);
967 free(core_worktree);
970 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
971 /* #16d */
972 set_git_dir(gitdirenv, 0);
973 free(gitfile);
974 return NULL;
976 else /* #2, #10 */
977 set_git_work_tree(".");
979 /* set_git_work_tree() must have been called by now */
980 worktree = get_git_work_tree();
982 /* both get_git_work_tree() and cwd are already normalized */
983 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
984 set_git_dir(gitdirenv, 0);
985 free(gitfile);
986 return NULL;
989 offset = dir_inside_of(cwd->buf, worktree);
990 if (offset >= 0) { /* cwd inside worktree? */
991 set_git_dir(gitdirenv, 1);
992 if (chdir(worktree))
993 die_errno(_("cannot chdir to '%s'"), worktree);
994 strbuf_addch(cwd, '/');
995 free(gitfile);
996 return cwd->buf + offset;
999 /* cwd outside worktree */
1000 set_git_dir(gitdirenv, 0);
1001 free(gitfile);
1002 return NULL;
1005 static const char *setup_discovered_git_dir(const char *gitdir,
1006 struct strbuf *cwd, int offset,
1007 struct repository_format *repo_fmt,
1008 int *nongit_ok)
1010 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1011 return NULL;
1013 /* --work-tree is set without --git-dir; use discovered one */
1014 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1015 char *to_free = NULL;
1016 const char *ret;
1018 if (offset != cwd->len && !is_absolute_path(gitdir))
1019 gitdir = to_free = real_pathdup(gitdir, 1);
1020 if (chdir(cwd->buf))
1021 die_errno(_("cannot come back to cwd"));
1022 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1023 free(to_free);
1024 return ret;
1027 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1028 if (is_bare_repository_cfg > 0) {
1029 set_git_dir(gitdir, (offset != cwd->len));
1030 if (chdir(cwd->buf))
1031 die_errno(_("cannot come back to cwd"));
1032 return NULL;
1035 /* #0, #1, #5, #8, #9, #12, #13 */
1036 set_git_work_tree(".");
1037 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1038 set_git_dir(gitdir, 0);
1039 inside_git_dir = 0;
1040 inside_work_tree = 1;
1041 if (offset >= cwd->len)
1042 return NULL;
1044 /* Make "offset" point past the '/' (already the case for root dirs) */
1045 if (offset != offset_1st_component(cwd->buf))
1046 offset++;
1047 /* Add a '/' at the end */
1048 strbuf_addch(cwd, '/');
1049 return cwd->buf + offset;
1052 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1053 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1054 struct repository_format *repo_fmt,
1055 int *nongit_ok)
1057 int root_len;
1059 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1060 return NULL;
1062 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1064 /* --work-tree is set without --git-dir; use discovered one */
1065 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1066 static const char *gitdir;
1068 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1069 if (chdir(cwd->buf))
1070 die_errno(_("cannot come back to cwd"));
1071 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1074 inside_git_dir = 1;
1075 inside_work_tree = 0;
1076 if (offset != cwd->len) {
1077 if (chdir(cwd->buf))
1078 die_errno(_("cannot come back to cwd"));
1079 root_len = offset_1st_component(cwd->buf);
1080 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1081 set_git_dir(cwd->buf, 0);
1083 else
1084 set_git_dir(".", 0);
1085 return NULL;
1088 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1090 struct stat buf;
1091 if (stat(path, &buf)) {
1092 die_errno(_("failed to stat '%*s%s%s'"),
1093 prefix_len,
1094 prefix ? prefix : "",
1095 prefix ? "/" : "", path);
1097 return buf.st_dev;
1101 * A "string_list_each_func_t" function that canonicalizes an entry
1102 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1103 * discards it if unusable. The presence of an empty entry in
1104 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1105 * subsequent entries.
1107 static int canonicalize_ceiling_entry(struct string_list_item *item,
1108 void *cb_data)
1110 int *empty_entry_found = cb_data;
1111 char *ceil = item->string;
1113 if (!*ceil) {
1114 *empty_entry_found = 1;
1115 return 0;
1116 } else if (!is_absolute_path(ceil)) {
1117 return 0;
1118 } else if (*empty_entry_found) {
1119 /* Keep entry but do not canonicalize it */
1120 return 1;
1121 } else {
1122 char *real_path = real_pathdup(ceil, 0);
1123 if (!real_path) {
1124 return 0;
1126 free(item->string);
1127 item->string = real_path;
1128 return 1;
1132 struct safe_directory_data {
1133 const char *path;
1134 int is_safe;
1137 static int safe_directory_cb(const char *key, const char *value,
1138 const struct config_context *ctx UNUSED, void *d)
1140 struct safe_directory_data *data = d;
1142 if (strcmp(key, "safe.directory"))
1143 return 0;
1145 if (!value || !*value) {
1146 data->is_safe = 0;
1147 } else if (!strcmp(value, "*")) {
1148 data->is_safe = 1;
1149 } else {
1150 const char *interpolated = NULL;
1152 if (!git_config_pathname(&interpolated, key, value) &&
1153 !fspathcmp(data->path, interpolated ? interpolated : value))
1154 data->is_safe = 1;
1156 free((char *)interpolated);
1159 return 0;
1163 * Check if a repository is safe, by verifying the ownership of the
1164 * worktree (if any), the git directory, and the gitfile (if any).
1166 * Exemptions for known-safe repositories can be added via `safe.directory`
1167 * config settings; for non-bare repositories, their worktree needs to be
1168 * added, for bare ones their git directory.
1170 static int ensure_valid_ownership(const char *gitfile,
1171 const char *worktree, const char *gitdir,
1172 struct strbuf *report)
1174 struct safe_directory_data data = {
1175 .path = worktree ? worktree : gitdir
1178 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1179 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1180 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1181 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1182 return 1;
1185 * data.path is the "path" that identifies the repository and it is
1186 * constant regardless of what failed above. data.is_safe should be
1187 * initialized to false, and might be changed by the callback.
1189 git_protected_config(safe_directory_cb, &data);
1191 return data.is_safe;
1194 void die_upon_dubious_ownership(const char *gitfile, const char *worktree,
1195 const char *gitdir)
1197 struct strbuf report = STRBUF_INIT, quoted = STRBUF_INIT;
1198 const char *path;
1200 if (ensure_valid_ownership(gitfile, worktree, gitdir, &report))
1201 return;
1203 strbuf_complete(&report, '\n');
1204 path = gitfile ? gitfile : gitdir;
1205 sq_quote_buf_pretty(&quoted, path);
1207 die(_("detected dubious ownership in repository at '%s'\n"
1208 "%s"
1209 "To add an exception for this directory, call:\n"
1210 "\n"
1211 "\tgit config --global --add safe.directory %s"),
1212 path, report.buf, quoted.buf);
1215 static int allowed_bare_repo_cb(const char *key, const char *value,
1216 const struct config_context *ctx UNUSED,
1217 void *d)
1219 enum allowed_bare_repo *allowed_bare_repo = d;
1221 if (strcasecmp(key, "safe.bareRepository"))
1222 return 0;
1224 if (!strcmp(value, "explicit")) {
1225 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1226 return 0;
1228 if (!strcmp(value, "all")) {
1229 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1230 return 0;
1232 return -1;
1235 static enum allowed_bare_repo get_allowed_bare_repo(void)
1237 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1238 git_protected_config(allowed_bare_repo_cb, &result);
1239 return result;
1242 static const char *allowed_bare_repo_to_string(
1243 enum allowed_bare_repo allowed_bare_repo)
1245 switch (allowed_bare_repo) {
1246 case ALLOWED_BARE_REPO_EXPLICIT:
1247 return "explicit";
1248 case ALLOWED_BARE_REPO_ALL:
1249 return "all";
1250 default:
1251 BUG("invalid allowed_bare_repo %d",
1252 allowed_bare_repo);
1254 return NULL;
1258 * We cannot decide in this function whether we are in the work tree or
1259 * not, since the config can only be read _after_ this function was called.
1261 * Also, we avoid changing any global state (such as the current working
1262 * directory) to allow early callers.
1264 * The directory where the search should start needs to be passed in via the
1265 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1266 * the directory where the search ended, and `gitdir` will contain the path of
1267 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1268 * is relative to `dir` (i.e. *not* necessarily the cwd).
1270 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1271 struct strbuf *gitdir,
1272 struct strbuf *report,
1273 int die_on_error)
1275 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1276 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1277 const char *gitdirenv;
1278 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1279 dev_t current_device = 0;
1280 int one_filesystem = 1;
1283 * If GIT_DIR is set explicitly, we're not going
1284 * to do any discovery, but we still do repository
1285 * validation.
1287 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1288 if (gitdirenv) {
1289 strbuf_addstr(gitdir, gitdirenv);
1290 return GIT_DIR_EXPLICIT;
1293 if (env_ceiling_dirs) {
1294 int empty_entry_found = 0;
1296 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1297 filter_string_list(&ceiling_dirs, 0,
1298 canonicalize_ceiling_entry, &empty_entry_found);
1299 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1300 string_list_clear(&ceiling_dirs, 0);
1303 if (ceil_offset < 0)
1304 ceil_offset = min_offset - 2;
1306 if (min_offset && min_offset == dir->len &&
1307 !is_dir_sep(dir->buf[min_offset - 1])) {
1308 strbuf_addch(dir, '/');
1309 min_offset++;
1313 * Test in the following order (relative to the dir):
1314 * - .git (file containing "gitdir: <path>")
1315 * - .git/
1316 * - ./ (bare)
1317 * - ../.git
1318 * - ../.git/
1319 * - ../ (bare)
1320 * - ../../.git
1321 * etc.
1323 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1324 if (one_filesystem)
1325 current_device = get_device_or_die(dir->buf, NULL, 0);
1326 for (;;) {
1327 int offset = dir->len, error_code = 0;
1328 char *gitdir_path = NULL;
1329 char *gitfile = NULL;
1331 if (offset > min_offset)
1332 strbuf_addch(dir, '/');
1333 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1334 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1335 NULL : &error_code);
1336 if (!gitdirenv) {
1337 if (die_on_error ||
1338 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1339 /* NEEDSWORK: fail if .git is not file nor dir */
1340 if (is_git_directory(dir->buf)) {
1341 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1342 gitdir_path = xstrdup(dir->buf);
1344 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1345 return GIT_DIR_INVALID_GITFILE;
1346 } else
1347 gitfile = xstrdup(dir->buf);
1349 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1350 * to check that directory for a repository.
1351 * Now trim that tentative addition away, because we want to
1352 * focus on the real directory we are in.
1354 strbuf_setlen(dir, offset);
1355 if (gitdirenv) {
1356 enum discovery_result ret;
1357 const char *gitdir_candidate =
1358 gitdir_path ? gitdir_path : gitdirenv;
1360 if (ensure_valid_ownership(gitfile, dir->buf,
1361 gitdir_candidate, report)) {
1362 strbuf_addstr(gitdir, gitdirenv);
1363 ret = GIT_DIR_DISCOVERED;
1364 } else
1365 ret = GIT_DIR_INVALID_OWNERSHIP;
1368 * Earlier, during discovery, we might have allocated
1369 * string copies for gitdir_path or gitfile so make
1370 * sure we don't leak by freeing them now, before
1371 * leaving the loop and function.
1373 * Note: gitdirenv will be non-NULL whenever these are
1374 * allocated, therefore we need not take care of releasing
1375 * them outside of this conditional block.
1377 free(gitdir_path);
1378 free(gitfile);
1380 return ret;
1383 if (is_git_directory(dir->buf)) {
1384 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1385 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1386 return GIT_DIR_DISALLOWED_BARE;
1387 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1388 return GIT_DIR_INVALID_OWNERSHIP;
1389 strbuf_addstr(gitdir, ".");
1390 return GIT_DIR_BARE;
1393 if (offset <= min_offset)
1394 return GIT_DIR_HIT_CEILING;
1396 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1397 ; /* continue */
1398 if (offset <= ceil_offset)
1399 return GIT_DIR_HIT_CEILING;
1401 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1402 if (one_filesystem &&
1403 current_device != get_device_or_die(dir->buf, NULL, offset))
1404 return GIT_DIR_HIT_MOUNT_POINT;
1408 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1409 struct strbuf *gitdir)
1411 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1412 size_t gitdir_offset = gitdir->len, cwd_len;
1413 size_t commondir_offset = commondir->len;
1414 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1415 enum discovery_result result;
1417 if (strbuf_getcwd(&dir))
1418 return GIT_DIR_CWD_FAILURE;
1420 cwd_len = dir.len;
1421 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1422 if (result <= 0) {
1423 strbuf_release(&dir);
1424 return result;
1428 * The returned gitdir is relative to dir, and if dir does not reflect
1429 * the current working directory, we simply make the gitdir absolute.
1431 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1432 /* Avoid a trailing "/." */
1433 if (!strcmp(".", gitdir->buf + gitdir_offset))
1434 strbuf_setlen(gitdir, gitdir_offset);
1435 else
1436 strbuf_addch(&dir, '/');
1437 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1440 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1442 strbuf_reset(&dir);
1443 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1444 read_repository_format(&candidate, dir.buf);
1445 strbuf_release(&dir);
1447 if (verify_repository_format(&candidate, &err) < 0) {
1448 warning("ignoring git dir '%s': %s",
1449 gitdir->buf + gitdir_offset, err.buf);
1450 strbuf_release(&err);
1451 strbuf_setlen(commondir, commondir_offset);
1452 strbuf_setlen(gitdir, gitdir_offset);
1453 clear_repository_format(&candidate);
1454 return GIT_DIR_INVALID_FORMAT;
1457 clear_repository_format(&candidate);
1458 return result;
1461 const char *setup_git_directory_gently(int *nongit_ok)
1463 static struct strbuf cwd = STRBUF_INIT;
1464 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1465 const char *prefix = NULL;
1466 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1469 * We may have read an incomplete configuration before
1470 * setting-up the git directory. If so, clear the cache so
1471 * that the next queries to the configuration reload complete
1472 * configuration (including the per-repo config file that we
1473 * ignored previously).
1475 git_config_clear();
1478 * Let's assume that we are in a git repository.
1479 * If it turns out later that we are somewhere else, the value will be
1480 * updated accordingly.
1482 if (nongit_ok)
1483 *nongit_ok = 0;
1485 if (strbuf_getcwd(&cwd))
1486 die_errno(_("Unable to read current working directory"));
1487 strbuf_addbuf(&dir, &cwd);
1489 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1490 case GIT_DIR_EXPLICIT:
1491 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1492 break;
1493 case GIT_DIR_DISCOVERED:
1494 if (dir.len < cwd.len && chdir(dir.buf))
1495 die(_("cannot change to '%s'"), dir.buf);
1496 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1497 &repo_fmt, nongit_ok);
1498 break;
1499 case GIT_DIR_BARE:
1500 if (dir.len < cwd.len && chdir(dir.buf))
1501 die(_("cannot change to '%s'"), dir.buf);
1502 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1503 break;
1504 case GIT_DIR_HIT_CEILING:
1505 if (!nongit_ok)
1506 die(_("not a git repository (or any of the parent directories): %s"),
1507 DEFAULT_GIT_DIR_ENVIRONMENT);
1508 *nongit_ok = 1;
1509 break;
1510 case GIT_DIR_HIT_MOUNT_POINT:
1511 if (!nongit_ok)
1512 die(_("not a git repository (or any parent up to mount point %s)\n"
1513 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1514 dir.buf);
1515 *nongit_ok = 1;
1516 break;
1517 case GIT_DIR_INVALID_OWNERSHIP:
1518 if (!nongit_ok) {
1519 struct strbuf quoted = STRBUF_INIT;
1521 strbuf_complete(&report, '\n');
1522 sq_quote_buf_pretty(&quoted, dir.buf);
1523 die(_("detected dubious ownership in repository at '%s'\n"
1524 "%s"
1525 "To add an exception for this directory, call:\n"
1526 "\n"
1527 "\tgit config --global --add safe.directory %s"),
1528 dir.buf, report.buf, quoted.buf);
1530 *nongit_ok = 1;
1531 break;
1532 case GIT_DIR_DISALLOWED_BARE:
1533 if (!nongit_ok) {
1534 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1535 dir.buf,
1536 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1538 *nongit_ok = 1;
1539 break;
1540 case GIT_DIR_CWD_FAILURE:
1541 case GIT_DIR_INVALID_FORMAT:
1543 * As a safeguard against setup_git_directory_gently_1 returning
1544 * these values, fallthrough to BUG. Otherwise it is possible to
1545 * set startup_info->have_repository to 1 when we did nothing to
1546 * find a repository.
1548 default:
1549 BUG("unhandled setup_git_directory_gently_1() result");
1553 * At this point, nongit_ok is stable. If it is non-NULL and points
1554 * to a non-zero value, then this means that we haven't found a
1555 * repository and that the caller expects startup_info to reflect
1556 * this.
1558 * Regardless of the state of nongit_ok, startup_info->prefix and
1559 * the GIT_PREFIX environment variable must always match. For details
1560 * see Documentation/config/alias.txt.
1562 if (nongit_ok && *nongit_ok)
1563 startup_info->have_repository = 0;
1564 else
1565 startup_info->have_repository = 1;
1568 * Not all paths through the setup code will call 'set_git_dir()' (which
1569 * directly sets up the environment) so in order to guarantee that the
1570 * environment is in a consistent state after setup, explicitly setup
1571 * the environment if we have a repository.
1573 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1574 * code paths so we also need to explicitly setup the environment if
1575 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1576 * GIT_DIR values at some point in the future.
1578 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1579 startup_info->have_repository ||
1580 /* GIT_DIR_EXPLICIT */
1581 getenv(GIT_DIR_ENVIRONMENT)) {
1582 if (!the_repository->gitdir) {
1583 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1584 if (!gitdir)
1585 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1586 setup_git_env(gitdir);
1588 if (startup_info->have_repository) {
1589 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1590 the_repository->repository_format_worktree_config =
1591 repo_fmt.worktree_config;
1592 /* take ownership of repo_fmt.partial_clone */
1593 the_repository->repository_format_partial_clone =
1594 repo_fmt.partial_clone;
1595 repo_fmt.partial_clone = NULL;
1599 * Since precompose_string_if_needed() needs to look at
1600 * the core.precomposeunicode configuration, this
1601 * has to happen after the above block that finds
1602 * out where the repository is, i.e. a preparation
1603 * for calling git_config_get_bool().
1605 if (prefix) {
1606 prefix = precompose_string_if_needed(prefix);
1607 startup_info->prefix = prefix;
1608 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1609 } else {
1610 startup_info->prefix = NULL;
1611 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1614 setup_original_cwd();
1616 strbuf_release(&dir);
1617 strbuf_release(&gitdir);
1618 strbuf_release(&report);
1619 clear_repository_format(&repo_fmt);
1621 return prefix;
1624 int git_config_perm(const char *var, const char *value)
1626 int i;
1627 char *endptr;
1629 if (!value)
1630 return PERM_GROUP;
1632 if (!strcmp(value, "umask"))
1633 return PERM_UMASK;
1634 if (!strcmp(value, "group"))
1635 return PERM_GROUP;
1636 if (!strcmp(value, "all") ||
1637 !strcmp(value, "world") ||
1638 !strcmp(value, "everybody"))
1639 return PERM_EVERYBODY;
1641 /* Parse octal numbers */
1642 i = strtol(value, &endptr, 8);
1644 /* If not an octal number, maybe true/false? */
1645 if (*endptr != 0)
1646 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1649 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1650 * a chmod value to restrict to.
1652 switch (i) {
1653 case PERM_UMASK: /* 0 */
1654 return PERM_UMASK;
1655 case OLD_PERM_GROUP: /* 1 */
1656 return PERM_GROUP;
1657 case OLD_PERM_EVERYBODY: /* 2 */
1658 return PERM_EVERYBODY;
1661 /* A filemode value was given: 0xxx */
1663 if ((i & 0600) != 0600)
1664 die(_("problem with core.sharedRepository filemode value "
1665 "(0%.3o).\nThe owner of files must always have "
1666 "read and write permissions."), i);
1669 * Mask filemode value. Others can not get write permission.
1670 * x flags for directories are handled separately.
1672 return -(i & 0666);
1675 void check_repository_format(struct repository_format *fmt)
1677 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1678 if (!fmt)
1679 fmt = &repo_fmt;
1680 check_repository_format_gently(get_git_dir(), fmt, NULL);
1681 startup_info->have_repository = 1;
1682 repo_set_hash_algo(the_repository, fmt->hash_algo);
1683 the_repository->repository_format_worktree_config =
1684 fmt->worktree_config;
1685 the_repository->repository_format_partial_clone =
1686 xstrdup_or_null(fmt->partial_clone);
1687 clear_repository_format(&repo_fmt);
1691 * Returns the "prefix", a path to the current working directory
1692 * relative to the work tree root, or NULL, if the current working
1693 * directory is not a strict subdirectory of the work tree root. The
1694 * prefix always ends with a '/' character.
1696 const char *setup_git_directory(void)
1698 return setup_git_directory_gently(NULL);
1701 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1703 if (is_git_directory(suspect))
1704 return suspect;
1705 return read_gitfile_gently(suspect, return_error_code);
1708 /* if any standard file descriptor is missing open it to /dev/null */
1709 void sanitize_stdfds(void)
1711 int fd = xopen("/dev/null", O_RDWR);
1712 while (fd < 2)
1713 fd = xdup(fd);
1714 if (fd > 2)
1715 close(fd);
1718 int daemonize(void)
1720 #ifdef NO_POSIX_GOODIES
1721 errno = ENOSYS;
1722 return -1;
1723 #else
1724 switch (fork()) {
1725 case 0:
1726 break;
1727 case -1:
1728 die_errno(_("fork failed"));
1729 default:
1730 exit(0);
1732 if (setsid() == -1)
1733 die_errno(_("setsid failed"));
1734 close(0);
1735 close(1);
1736 close(2);
1737 sanitize_stdfds();
1738 return 0;
1739 #endif
1742 struct template_dir_cb_data {
1743 char *path;
1744 int initialized;
1747 static int template_dir_cb(const char *key, const char *value,
1748 const struct config_context *ctx, void *d)
1750 struct template_dir_cb_data *data = d;
1752 if (strcmp(key, "init.templatedir"))
1753 return 0;
1755 if (!value) {
1756 data->path = NULL;
1757 } else {
1758 char *path = NULL;
1760 FREE_AND_NULL(data->path);
1761 if (!git_config_pathname((const char **)&path, key, value))
1762 data->path = path ? path : xstrdup(value);
1765 return 0;
1768 const char *get_template_dir(const char *option_template)
1770 const char *template_dir = option_template;
1772 if (!template_dir)
1773 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1774 if (!template_dir) {
1775 static struct template_dir_cb_data data;
1777 if (!data.initialized) {
1778 git_protected_config(template_dir_cb, &data);
1779 data.initialized = 1;
1781 template_dir = data.path;
1783 if (!template_dir) {
1784 static char *dir;
1786 if (!dir)
1787 dir = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1788 template_dir = dir;
1790 return template_dir;
1793 #ifdef NO_TRUSTABLE_FILEMODE
1794 #define TEST_FILEMODE 0
1795 #else
1796 #define TEST_FILEMODE 1
1797 #endif
1799 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1801 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1802 DIR *dir)
1804 size_t path_baselen = path->len;
1805 size_t template_baselen = template_path->len;
1806 struct dirent *de;
1808 /* Note: if ".git/hooks" file exists in the repository being
1809 * re-initialized, /etc/core-git/templates/hooks/update would
1810 * cause "git init" to fail here. I think this is sane but
1811 * it means that the set of templates we ship by default, along
1812 * with the way the namespace under .git/ is organized, should
1813 * be really carefully chosen.
1815 safe_create_dir(path->buf, 1);
1816 while ((de = readdir(dir)) != NULL) {
1817 struct stat st_git, st_template;
1818 int exists = 0;
1820 strbuf_setlen(path, path_baselen);
1821 strbuf_setlen(template_path, template_baselen);
1823 if (de->d_name[0] == '.')
1824 continue;
1825 strbuf_addstr(path, de->d_name);
1826 strbuf_addstr(template_path, de->d_name);
1827 if (lstat(path->buf, &st_git)) {
1828 if (errno != ENOENT)
1829 die_errno(_("cannot stat '%s'"), path->buf);
1831 else
1832 exists = 1;
1834 if (lstat(template_path->buf, &st_template))
1835 die_errno(_("cannot stat template '%s'"), template_path->buf);
1837 if (S_ISDIR(st_template.st_mode)) {
1838 DIR *subdir = opendir(template_path->buf);
1839 if (!subdir)
1840 die_errno(_("cannot opendir '%s'"), template_path->buf);
1841 strbuf_addch(path, '/');
1842 strbuf_addch(template_path, '/');
1843 copy_templates_1(path, template_path, subdir);
1844 closedir(subdir);
1846 else if (exists)
1847 continue;
1848 else if (S_ISLNK(st_template.st_mode)) {
1849 struct strbuf lnk = STRBUF_INIT;
1850 if (strbuf_readlink(&lnk, template_path->buf,
1851 st_template.st_size) < 0)
1852 die_errno(_("cannot readlink '%s'"), template_path->buf);
1853 if (symlink(lnk.buf, path->buf))
1854 die_errno(_("cannot symlink '%s' '%s'"),
1855 lnk.buf, path->buf);
1856 strbuf_release(&lnk);
1858 else if (S_ISREG(st_template.st_mode)) {
1859 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1860 die_errno(_("cannot copy '%s' to '%s'"),
1861 template_path->buf, path->buf);
1863 else
1864 error(_("ignoring template %s"), template_path->buf);
1868 static void copy_templates(const char *option_template)
1870 const char *template_dir = get_template_dir(option_template);
1871 struct strbuf path = STRBUF_INIT;
1872 struct strbuf template_path = STRBUF_INIT;
1873 size_t template_len;
1874 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1875 struct strbuf err = STRBUF_INIT;
1876 DIR *dir;
1877 char *to_free = NULL;
1879 if (!template_dir || !*template_dir)
1880 return;
1882 strbuf_addstr(&template_path, template_dir);
1883 strbuf_complete(&template_path, '/');
1884 template_len = template_path.len;
1886 dir = opendir(template_path.buf);
1887 if (!dir) {
1888 warning(_("templates not found in %s"), template_dir);
1889 goto free_return;
1892 /* Make sure that template is from the correct vintage */
1893 strbuf_addstr(&template_path, "config");
1894 read_repository_format(&template_format, template_path.buf);
1895 strbuf_setlen(&template_path, template_len);
1898 * No mention of version at all is OK, but anything else should be
1899 * verified.
1901 if (template_format.version >= 0 &&
1902 verify_repository_format(&template_format, &err) < 0) {
1903 warning(_("not copying templates from '%s': %s"),
1904 template_dir, err.buf);
1905 strbuf_release(&err);
1906 goto close_free_return;
1909 strbuf_addstr(&path, get_git_common_dir());
1910 strbuf_complete(&path, '/');
1911 copy_templates_1(&path, &template_path, dir);
1912 close_free_return:
1913 closedir(dir);
1914 free_return:
1915 free(to_free);
1916 strbuf_release(&path);
1917 strbuf_release(&template_path);
1918 clear_repository_format(&template_format);
1922 * If the git_dir is not directly inside the working tree, then git will not
1923 * find it by default, and we need to set the worktree explicitly.
1925 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1927 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1928 return 0;
1929 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1930 !strcmp(git_dir, "/.git"))
1931 return 0;
1932 return 1;
1935 void initialize_repository_version(int hash_algo, int reinit)
1937 char repo_version_string[10];
1938 int repo_version = GIT_REPO_VERSION;
1940 if (hash_algo != GIT_HASH_SHA1)
1941 repo_version = GIT_REPO_VERSION_READ;
1943 /* This forces creation of new config file */
1944 xsnprintf(repo_version_string, sizeof(repo_version_string),
1945 "%d", repo_version);
1946 git_config_set("core.repositoryformatversion", repo_version_string);
1948 if (hash_algo != GIT_HASH_SHA1)
1949 git_config_set("extensions.objectformat",
1950 hash_algos[hash_algo].name);
1951 else if (reinit)
1952 git_config_set_gently("extensions.objectformat", NULL);
1955 static int create_default_files(const char *template_path,
1956 const char *original_git_dir,
1957 const char *initial_branch,
1958 const struct repository_format *fmt,
1959 int prev_bare_repository,
1960 int init_shared_repository,
1961 int quiet)
1963 struct stat st1;
1964 struct strbuf buf = STRBUF_INIT;
1965 char *path;
1966 char junk[2];
1967 int reinit;
1968 int filemode;
1969 struct strbuf err = STRBUF_INIT;
1970 const char *work_tree = get_git_work_tree();
1973 * First copy the templates -- we might have the default
1974 * config file there, in which case we would want to read
1975 * from it after installing.
1977 * Before reading that config, we also need to clear out any cached
1978 * values (since we've just potentially changed what's available on
1979 * disk).
1981 copy_templates(template_path);
1982 git_config_clear();
1983 reset_shared_repository();
1984 git_config(git_default_config, NULL);
1987 * We must make sure command-line options continue to override any
1988 * values we might have just re-read from the config.
1990 if (init_shared_repository != -1)
1991 set_shared_repository(init_shared_repository);
1993 * TODO: heed core.bare from config file in templates if no
1994 * command-line override given
1996 is_bare_repository_cfg = prev_bare_repository || !work_tree;
1997 /* TODO (continued):
1999 * Unfortunately, the line above is equivalent to
2000 * is_bare_repository_cfg = !work_tree;
2001 * which ignores the config entirely even if no `--[no-]bare`
2002 * command line option was present.
2004 * To see why, note that before this function, there was this call:
2005 * prev_bare_repository = is_bare_repository()
2006 * expanding the right hand side:
2007 * = is_bare_repository_cfg && !get_git_work_tree()
2008 * = is_bare_repository_cfg && !work_tree
2009 * note that the last simplification above is valid because nothing
2010 * calls repo_init() or set_git_work_tree() between any of the
2011 * relevant calls in the code, and thus the !get_git_work_tree()
2012 * calls will return the same result each time. So, what we are
2013 * interested in computing is the right hand side of the line of
2014 * code just above this comment:
2015 * prev_bare_repository || !work_tree
2016 * = is_bare_repository_cfg && !work_tree || !work_tree
2017 * = !work_tree
2018 * because "A && !B || !B == !B" for all boolean values of A & B.
2022 * We would have created the above under user's umask -- under
2023 * shared-repository settings, we would need to fix them up.
2025 if (get_shared_repository()) {
2026 adjust_shared_perm(get_git_dir());
2030 * We need to create a "refs" dir in any case so that older
2031 * versions of git can tell that this is a repository.
2033 safe_create_dir(git_path("refs"), 1);
2034 adjust_shared_perm(git_path("refs"));
2036 if (refs_init_db(&err))
2037 die("failed to set up refs db: %s", err.buf);
2040 * Point the HEAD symref to the initial branch with if HEAD does
2041 * not yet exist.
2043 path = git_path_buf(&buf, "HEAD");
2044 reinit = (!access(path, R_OK)
2045 || readlink(path, junk, sizeof(junk)-1) != -1);
2046 if (!reinit) {
2047 char *ref;
2049 if (!initial_branch)
2050 initial_branch = git_default_branch_name(quiet);
2052 ref = xstrfmt("refs/heads/%s", initial_branch);
2053 if (check_refname_format(ref, 0) < 0)
2054 die(_("invalid initial branch name: '%s'"),
2055 initial_branch);
2057 if (create_symref("HEAD", ref, NULL) < 0)
2058 exit(1);
2059 free(ref);
2062 initialize_repository_version(fmt->hash_algo, 0);
2064 /* Check filemode trustability */
2065 path = git_path_buf(&buf, "config");
2066 filemode = TEST_FILEMODE;
2067 if (TEST_FILEMODE && !lstat(path, &st1)) {
2068 struct stat st2;
2069 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2070 !lstat(path, &st2) &&
2071 st1.st_mode != st2.st_mode &&
2072 !chmod(path, st1.st_mode));
2073 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2074 filemode = 0;
2076 git_config_set("core.filemode", filemode ? "true" : "false");
2078 if (is_bare_repository())
2079 git_config_set("core.bare", "true");
2080 else {
2081 git_config_set("core.bare", "false");
2082 /* allow template config file to override the default */
2083 if (log_all_ref_updates == LOG_REFS_UNSET)
2084 git_config_set("core.logallrefupdates", "true");
2085 if (needs_work_tree_config(original_git_dir, work_tree))
2086 git_config_set("core.worktree", work_tree);
2089 if (!reinit) {
2090 /* Check if symlink is supported in the work tree */
2091 path = git_path_buf(&buf, "tXXXXXX");
2092 if (!close(xmkstemp(path)) &&
2093 !unlink(path) &&
2094 !symlink("testing", path) &&
2095 !lstat(path, &st1) &&
2096 S_ISLNK(st1.st_mode))
2097 unlink(path); /* good */
2098 else
2099 git_config_set("core.symlinks", "false");
2101 /* Check if the filesystem is case-insensitive */
2102 path = git_path_buf(&buf, "CoNfIg");
2103 if (!access(path, F_OK))
2104 git_config_set("core.ignorecase", "true");
2105 probe_utf8_pathname_composition();
2108 strbuf_release(&buf);
2109 return reinit;
2112 static void create_object_directory(void)
2114 struct strbuf path = STRBUF_INIT;
2115 size_t baselen;
2117 strbuf_addstr(&path, get_object_directory());
2118 baselen = path.len;
2120 safe_create_dir(path.buf, 1);
2122 strbuf_setlen(&path, baselen);
2123 strbuf_addstr(&path, "/pack");
2124 safe_create_dir(path.buf, 1);
2126 strbuf_setlen(&path, baselen);
2127 strbuf_addstr(&path, "/info");
2128 safe_create_dir(path.buf, 1);
2130 strbuf_release(&path);
2133 static void separate_git_dir(const char *git_dir, const char *git_link)
2135 struct stat st;
2137 if (!stat(git_link, &st)) {
2138 const char *src;
2140 if (S_ISREG(st.st_mode))
2141 src = read_gitfile(git_link);
2142 else if (S_ISDIR(st.st_mode))
2143 src = git_link;
2144 else
2145 die(_("unable to handle file type %d"), (int)st.st_mode);
2147 if (rename(src, git_dir))
2148 die_errno(_("unable to move %s to %s"), src, git_dir);
2149 repair_worktrees(NULL, NULL);
2152 write_file(git_link, "gitdir: %s", git_dir);
2155 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2157 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2159 * If we already have an initialized repo, don't allow the user to
2160 * specify a different algorithm, as that could cause corruption.
2161 * Otherwise, if the user has specified one on the command line, use it.
2163 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2164 die(_("attempt to reinitialize repository with different hash"));
2165 else if (hash != GIT_HASH_UNKNOWN)
2166 repo_fmt->hash_algo = hash;
2167 else if (env) {
2168 int env_algo = hash_algo_by_name(env);
2169 if (env_algo == GIT_HASH_UNKNOWN)
2170 die(_("unknown hash algorithm '%s'"), env);
2171 repo_fmt->hash_algo = env_algo;
2175 int init_db(const char *git_dir, const char *real_git_dir,
2176 const char *template_dir, int hash, const char *initial_branch,
2177 int init_shared_repository, unsigned int flags)
2179 int reinit;
2180 int exist_ok = flags & INIT_DB_EXIST_OK;
2181 char *original_git_dir = real_pathdup(git_dir, 1);
2182 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2183 int prev_bare_repository;
2185 if (real_git_dir) {
2186 struct stat st;
2188 if (!exist_ok && !stat(git_dir, &st))
2189 die(_("%s already exists"), git_dir);
2191 if (!exist_ok && !stat(real_git_dir, &st))
2192 die(_("%s already exists"), real_git_dir);
2194 set_git_dir(real_git_dir, 1);
2195 git_dir = get_git_dir();
2196 separate_git_dir(git_dir, original_git_dir);
2198 else {
2199 set_git_dir(git_dir, 1);
2200 git_dir = get_git_dir();
2202 startup_info->have_repository = 1;
2204 /* Ensure `core.hidedotfiles` is processed */
2205 git_config(platform_core_config, NULL);
2207 safe_create_dir(git_dir, 0);
2209 prev_bare_repository = is_bare_repository();
2211 /* Check to see if the repository version is right.
2212 * Note that a newly created repository does not have
2213 * config file, so this will not fail. What we are catching
2214 * is an attempt to reinitialize new repository with an old tool.
2216 check_repository_format(&repo_fmt);
2218 validate_hash_algorithm(&repo_fmt, hash);
2220 reinit = create_default_files(template_dir, original_git_dir,
2221 initial_branch, &repo_fmt,
2222 prev_bare_repository,
2223 init_shared_repository,
2224 flags & INIT_DB_QUIET);
2225 if (reinit && initial_branch)
2226 warning(_("re-init: ignored --initial-branch=%s"),
2227 initial_branch);
2229 create_object_directory();
2231 if (get_shared_repository()) {
2232 char buf[10];
2233 /* We do not spell "group" and such, so that
2234 * the configuration can be read by older version
2235 * of git. Note, we use octal numbers for new share modes,
2236 * and compatibility values for PERM_GROUP and
2237 * PERM_EVERYBODY.
2239 if (get_shared_repository() < 0)
2240 /* force to the mode value */
2241 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2242 else if (get_shared_repository() == PERM_GROUP)
2243 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2244 else if (get_shared_repository() == PERM_EVERYBODY)
2245 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2246 else
2247 BUG("invalid value for shared_repository");
2248 git_config_set("core.sharedrepository", buf);
2249 git_config_set("receive.denyNonFastforwards", "true");
2252 if (!(flags & INIT_DB_QUIET)) {
2253 int len = strlen(git_dir);
2255 if (reinit)
2256 printf(get_shared_repository()
2257 ? _("Reinitialized existing shared Git repository in %s%s\n")
2258 : _("Reinitialized existing Git repository in %s%s\n"),
2259 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2260 else
2261 printf(get_shared_repository()
2262 ? _("Initialized empty shared Git repository in %s%s\n")
2263 : _("Initialized empty Git repository in %s%s\n"),
2264 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2267 clear_repository_format(&repo_fmt);
2268 free(original_git_dir);
2269 return 0;