grep docs: describe --recurse-submodules further and improve formatting a bit
[alt-git.git] / setup.c
blob0b798591c0c5c2b23285ce1c4f8fcfb71caddb14
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"
20 static int inside_git_dir = -1;
21 static int inside_work_tree = -1;
22 static int work_tree_config_is_bogus;
23 enum allowed_bare_repo {
24 ALLOWED_BARE_REPO_EXPLICIT = 0,
25 ALLOWED_BARE_REPO_ALL,
28 static struct startup_info the_startup_info;
29 struct startup_info *startup_info = &the_startup_info;
30 const char *tmp_original_cwd;
33 * The input parameter must contain an absolute path, and it must already be
34 * normalized.
36 * Find the part of an absolute path that lies inside the work tree by
37 * dereferencing symlinks outside the work tree, for example:
38 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
39 * /dir/file (work tree is /) -> dir/file
40 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
41 * /dir/repolink/file (repolink points to /dir/repo) -> file
42 * /dir/repo (exactly equal to work tree) -> (empty string)
44 static int abspath_part_inside_repo(char *path)
46 size_t len;
47 size_t wtlen;
48 char *path0;
49 int off;
50 const char *work_tree = get_git_work_tree();
51 struct strbuf realpath = STRBUF_INIT;
53 if (!work_tree)
54 return -1;
55 wtlen = strlen(work_tree);
56 len = strlen(path);
57 off = offset_1st_component(path);
59 /* check if work tree is already the prefix */
60 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
61 if (path[wtlen] == '/') {
62 memmove(path, path + wtlen + 1, len - wtlen);
63 return 0;
64 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
65 /* work tree is the root, or the whole path */
66 memmove(path, path + wtlen, len - wtlen + 1);
67 return 0;
69 /* work tree might match beginning of a symlink to work tree */
70 off = wtlen;
72 path0 = path;
73 path += off;
75 /* check each '/'-terminated level */
76 while (*path) {
77 path++;
78 if (*path == '/') {
79 *path = '\0';
80 strbuf_realpath(&realpath, path0, 1);
81 if (fspathcmp(realpath.buf, work_tree) == 0) {
82 memmove(path0, path + 1, len - (path - path0));
83 strbuf_release(&realpath);
84 return 0;
86 *path = '/';
90 /* check whole path */
91 strbuf_realpath(&realpath, path0, 1);
92 if (fspathcmp(realpath.buf, work_tree) == 0) {
93 *path0 = '\0';
94 strbuf_release(&realpath);
95 return 0;
98 strbuf_release(&realpath);
99 return -1;
103 * Normalize "path", prepending the "prefix" for relative paths. If
104 * remaining_prefix is not NULL, return the actual prefix still
105 * remains in the path. For example, prefix = sub1/sub2/ and path is
107 * foo -> sub1/sub2/foo (full prefix)
108 * ../foo -> sub1/foo (remaining prefix is sub1/)
109 * ../../bar -> bar (no remaining prefix)
110 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
111 * `pwd`/../bar -> sub1/bar (no remaining prefix)
113 char *prefix_path_gently(const char *prefix, int len,
114 int *remaining_prefix, const char *path)
116 const char *orig = path;
117 char *sanitized;
118 if (is_absolute_path(orig)) {
119 sanitized = xmallocz(strlen(path));
120 if (remaining_prefix)
121 *remaining_prefix = 0;
122 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
123 free(sanitized);
124 return NULL;
126 if (abspath_part_inside_repo(sanitized)) {
127 free(sanitized);
128 return NULL;
130 } else {
131 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
132 if (remaining_prefix)
133 *remaining_prefix = len;
134 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
135 free(sanitized);
136 return NULL;
139 return sanitized;
142 char *prefix_path(const char *prefix, int len, const char *path)
144 char *r = prefix_path_gently(prefix, len, NULL, path);
145 if (!r) {
146 const char *hint_path = get_git_work_tree();
147 if (!hint_path)
148 hint_path = get_git_dir();
149 die(_("'%s' is outside repository at '%s'"), path,
150 absolute_path(hint_path));
152 return r;
155 int path_inside_repo(const char *prefix, const char *path)
157 int len = prefix ? strlen(prefix) : 0;
158 char *r = prefix_path_gently(prefix, len, NULL, path);
159 if (r) {
160 free(r);
161 return 1;
163 return 0;
166 int check_filename(const char *prefix, const char *arg)
168 char *to_free = NULL;
169 struct stat st;
171 if (skip_prefix(arg, ":/", &arg)) {
172 if (!*arg) /* ":/" is root dir, always exists */
173 return 1;
174 prefix = NULL;
175 } else if (skip_prefix(arg, ":!", &arg) ||
176 skip_prefix(arg, ":^", &arg)) {
177 if (!*arg) /* excluding everything is silly, but allowed */
178 return 1;
181 if (prefix)
182 arg = to_free = prefix_filename(prefix, arg);
184 if (!lstat(arg, &st)) {
185 free(to_free);
186 return 1; /* file exists */
188 if (is_missing_file_error(errno)) {
189 free(to_free);
190 return 0; /* file does not exist */
192 die_errno(_("failed to stat '%s'"), arg);
195 static void NORETURN die_verify_filename(struct repository *r,
196 const char *prefix,
197 const char *arg,
198 int diagnose_misspelt_rev)
200 if (!diagnose_misspelt_rev)
201 die(_("%s: no such path in the working tree.\n"
202 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
203 arg);
205 * Saying "'(icase)foo' does not exist in the index" when the
206 * user gave us ":(icase)foo" is just stupid. A magic pathspec
207 * begins with a colon and is followed by a non-alnum; do not
208 * let maybe_die_on_misspelt_object_name() even trigger.
210 if (!(arg[0] == ':' && !isalnum(arg[1])))
211 maybe_die_on_misspelt_object_name(r, arg, prefix);
213 /* ... or fall back the most general message. */
214 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
215 "Use '--' to separate paths from revisions, like this:\n"
216 "'git <command> [<revision>...] -- [<file>...]'"), arg);
221 * Check for arguments that don't resolve as actual files,
222 * but which look sufficiently like pathspecs that we'll consider
223 * them such for the purposes of rev/pathspec DWIM parsing.
225 static int looks_like_pathspec(const char *arg)
227 const char *p;
228 int escaped = 0;
231 * Wildcard characters imply the user is looking to match pathspecs
232 * that aren't in the filesystem. Note that this doesn't include
233 * backslash even though it's a glob special; by itself it doesn't
234 * cause any increase in the match. Likewise ignore backslash-escaped
235 * wildcard characters.
237 for (p = arg; *p; p++) {
238 if (escaped) {
239 escaped = 0;
240 } else if (is_glob_special(*p)) {
241 if (*p == '\\')
242 escaped = 1;
243 else
244 return 1;
248 /* long-form pathspec magic */
249 if (starts_with(arg, ":("))
250 return 1;
252 return 0;
256 * Verify a filename that we got as an argument for a pathspec
257 * entry. Note that a filename that begins with "-" never verifies
258 * as true, because even if such a filename were to exist, we want
259 * it to be preceded by the "--" marker (or we want the user to
260 * use a format like "./-filename")
262 * The "diagnose_misspelt_rev" is used to provide a user-friendly
263 * diagnosis when dying upon finding that "name" is not a pathname.
264 * If set to 1, the diagnosis will try to diagnose "name" as an
265 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
266 * will only complain about an inexisting file.
268 * This function is typically called to check that a "file or rev"
269 * argument is unambiguous. In this case, the caller will want
270 * diagnose_misspelt_rev == 1 when verifying the first non-rev
271 * argument (which could have been a revision), and
272 * diagnose_misspelt_rev == 0 for the next ones (because we already
273 * saw a filename, there's not ambiguity anymore).
275 void verify_filename(const char *prefix,
276 const char *arg,
277 int diagnose_misspelt_rev)
279 if (*arg == '-')
280 die(_("option '%s' must come before non-option arguments"), arg);
281 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
282 return;
283 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
287 * Opposite of the above: the command line did not have -- marker
288 * and we parsed the arg as a refname. It should not be interpretable
289 * as a filename.
291 void verify_non_filename(const char *prefix, const char *arg)
293 if (!is_inside_work_tree() || is_inside_git_dir())
294 return;
295 if (*arg == '-')
296 return; /* flag */
297 if (!check_filename(prefix, arg))
298 return;
299 die(_("ambiguous argument '%s': both revision and filename\n"
300 "Use '--' to separate paths from revisions, like this:\n"
301 "'git <command> [<revision>...] -- [<file>...]'"), arg);
304 int get_common_dir(struct strbuf *sb, const char *gitdir)
306 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
307 if (git_env_common_dir) {
308 strbuf_addstr(sb, git_env_common_dir);
309 return 1;
310 } else {
311 return get_common_dir_noenv(sb, gitdir);
315 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
317 struct strbuf data = STRBUF_INIT;
318 struct strbuf path = STRBUF_INIT;
319 int ret = 0;
321 strbuf_addf(&path, "%s/commondir", gitdir);
322 if (file_exists(path.buf)) {
323 if (strbuf_read_file(&data, path.buf, 0) <= 0)
324 die_errno(_("failed to read %s"), path.buf);
325 while (data.len && (data.buf[data.len - 1] == '\n' ||
326 data.buf[data.len - 1] == '\r'))
327 data.len--;
328 data.buf[data.len] = '\0';
329 strbuf_reset(&path);
330 if (!is_absolute_path(data.buf))
331 strbuf_addf(&path, "%s/", gitdir);
332 strbuf_addbuf(&path, &data);
333 strbuf_add_real_path(sb, path.buf);
334 ret = 1;
335 } else {
336 strbuf_addstr(sb, gitdir);
339 strbuf_release(&data);
340 strbuf_release(&path);
341 return ret;
345 * Test if it looks like we're at a git directory.
346 * We want to see:
348 * - either an objects/ directory _or_ the proper
349 * GIT_OBJECT_DIRECTORY environment variable
350 * - a refs/ directory
351 * - either a HEAD symlink or a HEAD file that is formatted as
352 * a proper "ref:", or a regular file HEAD that has a properly
353 * formatted sha1 object name.
355 int is_git_directory(const char *suspect)
357 struct strbuf path = STRBUF_INIT;
358 int ret = 0;
359 size_t len;
361 /* Check worktree-related signatures */
362 strbuf_addstr(&path, suspect);
363 strbuf_complete(&path, '/');
364 strbuf_addstr(&path, "HEAD");
365 if (validate_headref(path.buf))
366 goto done;
368 strbuf_reset(&path);
369 get_common_dir(&path, suspect);
370 len = path.len;
372 /* Check non-worktree-related signatures */
373 if (getenv(DB_ENVIRONMENT)) {
374 if (access(getenv(DB_ENVIRONMENT), X_OK))
375 goto done;
377 else {
378 strbuf_setlen(&path, len);
379 strbuf_addstr(&path, "/objects");
380 if (access(path.buf, X_OK))
381 goto done;
384 strbuf_setlen(&path, len);
385 strbuf_addstr(&path, "/refs");
386 if (access(path.buf, X_OK))
387 goto done;
389 ret = 1;
390 done:
391 strbuf_release(&path);
392 return ret;
395 int is_nonbare_repository_dir(struct strbuf *path)
397 int ret = 0;
398 int gitfile_error;
399 size_t orig_path_len = path->len;
400 assert(orig_path_len != 0);
401 strbuf_complete(path, '/');
402 strbuf_addstr(path, ".git");
403 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
404 ret = 1;
405 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
406 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
407 ret = 1;
408 strbuf_setlen(path, orig_path_len);
409 return ret;
412 int is_inside_git_dir(void)
414 if (inside_git_dir < 0)
415 inside_git_dir = is_inside_dir(get_git_dir());
416 return inside_git_dir;
419 int is_inside_work_tree(void)
421 if (inside_work_tree < 0)
422 inside_work_tree = is_inside_dir(get_git_work_tree());
423 return inside_work_tree;
426 void setup_work_tree(void)
428 const char *work_tree;
429 static int initialized = 0;
431 if (initialized)
432 return;
434 if (work_tree_config_is_bogus)
435 die(_("unable to set up work tree using invalid config"));
437 work_tree = get_git_work_tree();
438 if (!work_tree || chdir_notify(work_tree))
439 die(_("this operation must be run in a work tree"));
442 * Make sure subsequent git processes find correct worktree
443 * if $GIT_WORK_TREE is set relative
445 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
446 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
448 initialized = 1;
451 static void setup_original_cwd(void)
453 struct strbuf tmp = STRBUF_INIT;
454 const char *worktree = NULL;
455 int offset = -1;
457 if (!tmp_original_cwd)
458 return;
461 * startup_info->original_cwd points to the current working
462 * directory we inherited from our parent process, which is a
463 * directory we want to avoid removing.
465 * For convience, we would like to have the path relative to the
466 * worktree instead of an absolute path.
468 * Yes, startup_info->original_cwd is usually the same as 'prefix',
469 * but differs in two ways:
470 * - prefix has a trailing '/'
471 * - if the user passes '-C' to git, that modifies the prefix but
472 * not startup_info->original_cwd.
475 /* Normalize the directory */
476 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
477 trace2_data_string("setup", the_repository,
478 "realpath-path", tmp_original_cwd);
479 trace2_data_string("setup", the_repository,
480 "realpath-failure", strerror(errno));
481 free((char*)tmp_original_cwd);
482 tmp_original_cwd = NULL;
483 return;
486 free((char*)tmp_original_cwd);
487 tmp_original_cwd = NULL;
488 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
491 * Get our worktree; we only protect the current working directory
492 * if it's in the worktree.
494 worktree = get_git_work_tree();
495 if (!worktree)
496 goto no_prevention_needed;
498 offset = dir_inside_of(startup_info->original_cwd, worktree);
499 if (offset >= 0) {
501 * If startup_info->original_cwd == worktree, that is already
502 * protected and we don't need original_cwd as a secondary
503 * protection measure.
505 if (!*(startup_info->original_cwd + offset))
506 goto no_prevention_needed;
509 * original_cwd was inside worktree; precompose it just as
510 * we do prefix so that built up paths will match
512 startup_info->original_cwd = \
513 precompose_string_if_needed(startup_info->original_cwd
514 + offset);
515 return;
518 no_prevention_needed:
519 free((char*)startup_info->original_cwd);
520 startup_info->original_cwd = NULL;
523 static int read_worktree_config(const char *var, const char *value,
524 const struct config_context *ctx UNUSED,
525 void *vdata)
527 struct repository_format *data = vdata;
529 if (strcmp(var, "core.bare") == 0) {
530 data->is_bare = git_config_bool(var, value);
531 } else if (strcmp(var, "core.worktree") == 0) {
532 if (!value)
533 return config_error_nonbool(var);
534 free(data->work_tree);
535 data->work_tree = xstrdup(value);
537 return 0;
540 enum extension_result {
541 EXTENSION_ERROR = -1, /* compatible with error(), etc */
542 EXTENSION_UNKNOWN = 0,
543 EXTENSION_OK = 1
547 * Do not add new extensions to this function. It handles extensions which are
548 * respected even in v0-format repositories for historical compatibility.
550 static enum extension_result handle_extension_v0(const char *var,
551 const char *value,
552 const char *ext,
553 struct repository_format *data)
555 if (!strcmp(ext, "noop")) {
556 return EXTENSION_OK;
557 } else if (!strcmp(ext, "preciousobjects")) {
558 data->precious_objects = git_config_bool(var, value);
559 return EXTENSION_OK;
560 } else if (!strcmp(ext, "partialclone")) {
561 if (!value)
562 return config_error_nonbool(var);
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;
594 } else if (!strcmp(ext, "refstorage")) {
595 unsigned int format;
597 if (!value)
598 return config_error_nonbool(var);
599 format = ref_storage_format_by_name(value);
600 if (format == REF_STORAGE_FORMAT_UNKNOWN)
601 return error(_("invalid value for '%s': '%s'"),
602 "extensions.refstorage", value);
603 data->ref_storage_format = format;
604 return EXTENSION_OK;
606 return EXTENSION_UNKNOWN;
609 static int check_repo_format(const char *var, const char *value,
610 const struct config_context *ctx, void *vdata)
612 struct repository_format *data = vdata;
613 const char *ext;
615 if (strcmp(var, "core.repositoryformatversion") == 0)
616 data->version = git_config_int(var, value, ctx->kvi);
617 else if (skip_prefix(var, "extensions.", &ext)) {
618 switch (handle_extension_v0(var, value, ext, data)) {
619 case EXTENSION_ERROR:
620 return -1;
621 case EXTENSION_OK:
622 return 0;
623 case EXTENSION_UNKNOWN:
624 break;
627 switch (handle_extension(var, value, ext, data)) {
628 case EXTENSION_ERROR:
629 return -1;
630 case EXTENSION_OK:
631 string_list_append(&data->v1_only_extensions, ext);
632 return 0;
633 case EXTENSION_UNKNOWN:
634 string_list_append(&data->unknown_extensions, ext);
635 return 0;
639 return read_worktree_config(var, value, ctx, vdata);
642 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
644 struct strbuf sb = STRBUF_INIT;
645 struct strbuf err = STRBUF_INIT;
646 int has_common;
648 has_common = get_common_dir(&sb, gitdir);
649 strbuf_addstr(&sb, "/config");
650 read_repository_format(candidate, sb.buf);
651 strbuf_release(&sb);
654 * For historical use of check_repository_format() in git-init,
655 * we treat a missing config as a silent "ok", even when nongit_ok
656 * is unset.
658 if (candidate->version < 0)
659 return 0;
661 if (verify_repository_format(candidate, &err) < 0) {
662 if (nongit_ok) {
663 warning("%s", err.buf);
664 strbuf_release(&err);
665 *nongit_ok = -1;
666 return -1;
668 die("%s", err.buf);
671 repository_format_precious_objects = candidate->precious_objects;
672 string_list_clear(&candidate->unknown_extensions, 0);
673 string_list_clear(&candidate->v1_only_extensions, 0);
675 if (candidate->worktree_config) {
677 * pick up core.bare and core.worktree from per-worktree
678 * config if present
680 strbuf_addf(&sb, "%s/config.worktree", gitdir);
681 git_config_from_file(read_worktree_config, sb.buf, candidate);
682 strbuf_release(&sb);
683 has_common = 0;
686 if (!has_common) {
687 if (candidate->is_bare != -1) {
688 is_bare_repository_cfg = candidate->is_bare;
689 if (is_bare_repository_cfg == 1)
690 inside_work_tree = -1;
692 if (candidate->work_tree) {
693 free(git_work_tree_cfg);
694 git_work_tree_cfg = xstrdup(candidate->work_tree);
695 inside_work_tree = -1;
699 return 0;
702 int upgrade_repository_format(int target_version)
704 struct strbuf sb = STRBUF_INIT;
705 struct strbuf err = STRBUF_INIT;
706 struct strbuf repo_version = STRBUF_INIT;
707 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
708 int ret;
710 strbuf_git_common_path(&sb, the_repository, "config");
711 read_repository_format(&repo_fmt, sb.buf);
712 strbuf_release(&sb);
714 if (repo_fmt.version >= target_version) {
715 ret = 0;
716 goto out;
719 if (verify_repository_format(&repo_fmt, &err) < 0) {
720 ret = error("cannot upgrade repository format from %d to %d: %s",
721 repo_fmt.version, target_version, err.buf);
722 goto out;
724 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr) {
725 ret = error("cannot upgrade repository format: "
726 "unknown extension %s",
727 repo_fmt.unknown_extensions.items[0].string);
728 goto out;
731 strbuf_addf(&repo_version, "%d", target_version);
732 git_config_set("core.repositoryformatversion", repo_version.buf);
734 ret = 1;
736 out:
737 clear_repository_format(&repo_fmt);
738 strbuf_release(&repo_version);
739 strbuf_release(&err);
740 return ret;
743 static void init_repository_format(struct repository_format *format)
745 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
747 memcpy(format, &fresh, sizeof(fresh));
750 int read_repository_format(struct repository_format *format, const char *path)
752 clear_repository_format(format);
753 git_config_from_file(check_repo_format, path, format);
754 if (format->version == -1)
755 clear_repository_format(format);
756 return format->version;
759 void clear_repository_format(struct repository_format *format)
761 string_list_clear(&format->unknown_extensions, 0);
762 string_list_clear(&format->v1_only_extensions, 0);
763 free(format->work_tree);
764 free(format->partial_clone);
765 init_repository_format(format);
768 int verify_repository_format(const struct repository_format *format,
769 struct strbuf *err)
771 if (GIT_REPO_VERSION_READ < format->version) {
772 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
773 GIT_REPO_VERSION_READ, format->version);
774 return -1;
777 if (format->version >= 1 && format->unknown_extensions.nr) {
778 int i;
780 strbuf_addstr(err, Q_("unknown repository extension found:",
781 "unknown repository extensions found:",
782 format->unknown_extensions.nr));
784 for (i = 0; i < format->unknown_extensions.nr; i++)
785 strbuf_addf(err, "\n\t%s",
786 format->unknown_extensions.items[i].string);
787 return -1;
790 if (format->version == 0 && format->v1_only_extensions.nr) {
791 int i;
793 strbuf_addstr(err,
794 Q_("repo version is 0, but v1-only extension found:",
795 "repo version is 0, but v1-only extensions found:",
796 format->v1_only_extensions.nr));
798 for (i = 0; i < format->v1_only_extensions.nr; i++)
799 strbuf_addf(err, "\n\t%s",
800 format->v1_only_extensions.items[i].string);
801 return -1;
804 return 0;
807 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
809 switch (error_code) {
810 case READ_GITFILE_ERR_STAT_FAILED:
811 case READ_GITFILE_ERR_NOT_A_FILE:
812 /* non-fatal; follow return path */
813 break;
814 case READ_GITFILE_ERR_OPEN_FAILED:
815 die_errno(_("error opening '%s'"), path);
816 case READ_GITFILE_ERR_TOO_LARGE:
817 die(_("too large to be a .git file: '%s'"), path);
818 case READ_GITFILE_ERR_READ_FAILED:
819 die(_("error reading %s"), path);
820 case READ_GITFILE_ERR_INVALID_FORMAT:
821 die(_("invalid gitfile format: %s"), path);
822 case READ_GITFILE_ERR_NO_PATH:
823 die(_("no path in gitfile: %s"), path);
824 case READ_GITFILE_ERR_NOT_A_REPO:
825 die(_("not a git repository: %s"), dir);
826 default:
827 BUG("unknown error code");
832 * Try to read the location of the git directory from the .git file,
833 * return path to git directory if found. The return value comes from
834 * a shared buffer.
836 * On failure, if return_error_code is not NULL, return_error_code
837 * will be set to an error code and NULL will be returned. If
838 * return_error_code is NULL the function will die instead (for most
839 * cases).
841 const char *read_gitfile_gently(const char *path, int *return_error_code)
843 const int max_file_size = 1 << 20; /* 1MB */
844 int error_code = 0;
845 char *buf = NULL;
846 char *dir = NULL;
847 const char *slash;
848 struct stat st;
849 int fd;
850 ssize_t len;
851 static struct strbuf realpath = STRBUF_INIT;
853 if (stat(path, &st)) {
854 /* NEEDSWORK: discern between ENOENT vs other errors */
855 error_code = READ_GITFILE_ERR_STAT_FAILED;
856 goto cleanup_return;
858 if (!S_ISREG(st.st_mode)) {
859 error_code = READ_GITFILE_ERR_NOT_A_FILE;
860 goto cleanup_return;
862 if (st.st_size > max_file_size) {
863 error_code = READ_GITFILE_ERR_TOO_LARGE;
864 goto cleanup_return;
866 fd = open(path, O_RDONLY);
867 if (fd < 0) {
868 error_code = READ_GITFILE_ERR_OPEN_FAILED;
869 goto cleanup_return;
871 buf = xmallocz(st.st_size);
872 len = read_in_full(fd, buf, st.st_size);
873 close(fd);
874 if (len != st.st_size) {
875 error_code = READ_GITFILE_ERR_READ_FAILED;
876 goto cleanup_return;
878 if (!starts_with(buf, "gitdir: ")) {
879 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
880 goto cleanup_return;
882 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
883 len--;
884 if (len < 9) {
885 error_code = READ_GITFILE_ERR_NO_PATH;
886 goto cleanup_return;
888 buf[len] = '\0';
889 dir = buf + 8;
891 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
892 size_t pathlen = slash+1 - path;
893 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
894 (int)(len - 8), buf + 8);
895 free(buf);
896 buf = dir;
898 if (!is_git_directory(dir)) {
899 error_code = READ_GITFILE_ERR_NOT_A_REPO;
900 goto cleanup_return;
903 strbuf_realpath(&realpath, dir, 1);
904 path = realpath.buf;
906 cleanup_return:
907 if (return_error_code)
908 *return_error_code = error_code;
909 else if (error_code)
910 read_gitfile_error_die(error_code, path, dir);
912 free(buf);
913 return error_code ? NULL : path;
916 static const char *setup_explicit_git_dir(const char *gitdirenv,
917 struct strbuf *cwd,
918 struct repository_format *repo_fmt,
919 int *nongit_ok)
921 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
922 const char *worktree;
923 char *gitfile;
924 int offset;
926 if (PATH_MAX - 40 < strlen(gitdirenv))
927 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
929 gitfile = (char*)read_gitfile(gitdirenv);
930 if (gitfile) {
931 gitfile = xstrdup(gitfile);
932 gitdirenv = gitfile;
935 if (!is_git_directory(gitdirenv)) {
936 if (nongit_ok) {
937 *nongit_ok = 1;
938 free(gitfile);
939 return NULL;
941 die(_("not a git repository: '%s'"), gitdirenv);
944 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
945 free(gitfile);
946 return NULL;
949 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
950 if (work_tree_env)
951 set_git_work_tree(work_tree_env);
952 else if (is_bare_repository_cfg > 0) {
953 if (git_work_tree_cfg) {
954 /* #22.2, #30 */
955 warning("core.bare and core.worktree do not make sense");
956 work_tree_config_is_bogus = 1;
959 /* #18, #26 */
960 set_git_dir(gitdirenv, 0);
961 free(gitfile);
962 return NULL;
964 else if (git_work_tree_cfg) { /* #6, #14 */
965 if (is_absolute_path(git_work_tree_cfg))
966 set_git_work_tree(git_work_tree_cfg);
967 else {
968 char *core_worktree;
969 if (chdir(gitdirenv))
970 die_errno(_("cannot chdir to '%s'"), gitdirenv);
971 if (chdir(git_work_tree_cfg))
972 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
973 core_worktree = xgetcwd();
974 if (chdir(cwd->buf))
975 die_errno(_("cannot come back to cwd"));
976 set_git_work_tree(core_worktree);
977 free(core_worktree);
980 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
981 /* #16d */
982 set_git_dir(gitdirenv, 0);
983 free(gitfile);
984 return NULL;
986 else /* #2, #10 */
987 set_git_work_tree(".");
989 /* set_git_work_tree() must have been called by now */
990 worktree = get_git_work_tree();
992 /* both get_git_work_tree() and cwd are already normalized */
993 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
994 set_git_dir(gitdirenv, 0);
995 free(gitfile);
996 return NULL;
999 offset = dir_inside_of(cwd->buf, worktree);
1000 if (offset >= 0) { /* cwd inside worktree? */
1001 set_git_dir(gitdirenv, 1);
1002 if (chdir(worktree))
1003 die_errno(_("cannot chdir to '%s'"), worktree);
1004 strbuf_addch(cwd, '/');
1005 free(gitfile);
1006 return cwd->buf + offset;
1009 /* cwd outside worktree */
1010 set_git_dir(gitdirenv, 0);
1011 free(gitfile);
1012 return NULL;
1015 static const char *setup_discovered_git_dir(const char *gitdir,
1016 struct strbuf *cwd, int offset,
1017 struct repository_format *repo_fmt,
1018 int *nongit_ok)
1020 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
1021 return NULL;
1023 /* --work-tree is set without --git-dir; use discovered one */
1024 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1025 char *to_free = NULL;
1026 const char *ret;
1028 if (offset != cwd->len && !is_absolute_path(gitdir))
1029 gitdir = to_free = real_pathdup(gitdir, 1);
1030 if (chdir(cwd->buf))
1031 die_errno(_("cannot come back to cwd"));
1032 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1033 free(to_free);
1034 return ret;
1037 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1038 if (is_bare_repository_cfg > 0) {
1039 set_git_dir(gitdir, (offset != cwd->len));
1040 if (chdir(cwd->buf))
1041 die_errno(_("cannot come back to cwd"));
1042 return NULL;
1045 /* #0, #1, #5, #8, #9, #12, #13 */
1046 set_git_work_tree(".");
1047 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1048 set_git_dir(gitdir, 0);
1049 inside_git_dir = 0;
1050 inside_work_tree = 1;
1051 if (offset >= cwd->len)
1052 return NULL;
1054 /* Make "offset" point past the '/' (already the case for root dirs) */
1055 if (offset != offset_1st_component(cwd->buf))
1056 offset++;
1057 /* Add a '/' at the end */
1058 strbuf_addch(cwd, '/');
1059 return cwd->buf + offset;
1062 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1063 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1064 struct repository_format *repo_fmt,
1065 int *nongit_ok)
1067 int root_len;
1069 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1070 return NULL;
1072 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1074 /* --work-tree is set without --git-dir; use discovered one */
1075 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1076 static const char *gitdir;
1078 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1079 if (chdir(cwd->buf))
1080 die_errno(_("cannot come back to cwd"));
1081 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1084 inside_git_dir = 1;
1085 inside_work_tree = 0;
1086 if (offset != cwd->len) {
1087 if (chdir(cwd->buf))
1088 die_errno(_("cannot come back to cwd"));
1089 root_len = offset_1st_component(cwd->buf);
1090 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1091 set_git_dir(cwd->buf, 0);
1093 else
1094 set_git_dir(".", 0);
1095 return NULL;
1098 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1100 struct stat buf;
1101 if (stat(path, &buf)) {
1102 die_errno(_("failed to stat '%*s%s%s'"),
1103 prefix_len,
1104 prefix ? prefix : "",
1105 prefix ? "/" : "", path);
1107 return buf.st_dev;
1111 * A "string_list_each_func_t" function that canonicalizes an entry
1112 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1113 * discards it if unusable. The presence of an empty entry in
1114 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1115 * subsequent entries.
1117 static int canonicalize_ceiling_entry(struct string_list_item *item,
1118 void *cb_data)
1120 int *empty_entry_found = cb_data;
1121 char *ceil = item->string;
1123 if (!*ceil) {
1124 *empty_entry_found = 1;
1125 return 0;
1126 } else if (!is_absolute_path(ceil)) {
1127 return 0;
1128 } else if (*empty_entry_found) {
1129 /* Keep entry but do not canonicalize it */
1130 return 1;
1131 } else {
1132 char *real_path = real_pathdup(ceil, 0);
1133 if (!real_path) {
1134 return 0;
1136 free(item->string);
1137 item->string = real_path;
1138 return 1;
1142 struct safe_directory_data {
1143 const char *path;
1144 int is_safe;
1147 static int safe_directory_cb(const char *key, const char *value,
1148 const struct config_context *ctx UNUSED, void *d)
1150 struct safe_directory_data *data = d;
1152 if (strcmp(key, "safe.directory"))
1153 return 0;
1155 if (!value || !*value) {
1156 data->is_safe = 0;
1157 } else if (!strcmp(value, "*")) {
1158 data->is_safe = 1;
1159 } else {
1160 const char *interpolated = NULL;
1162 if (!git_config_pathname(&interpolated, key, value) &&
1163 !fspathcmp(data->path, interpolated ? interpolated : value))
1164 data->is_safe = 1;
1166 free((char *)interpolated);
1169 return 0;
1173 * Check if a repository is safe, by verifying the ownership of the
1174 * worktree (if any), the git directory, and the gitfile (if any).
1176 * Exemptions for known-safe repositories can be added via `safe.directory`
1177 * config settings; for non-bare repositories, their worktree needs to be
1178 * added, for bare ones their git directory.
1180 static int ensure_valid_ownership(const char *gitfile,
1181 const char *worktree, const char *gitdir,
1182 struct strbuf *report)
1184 struct safe_directory_data data = {
1185 .path = worktree ? worktree : gitdir
1188 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1189 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1190 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1191 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1192 return 1;
1195 * data.path is the "path" that identifies the repository and it is
1196 * constant regardless of what failed above. data.is_safe should be
1197 * initialized to false, and might be changed by the callback.
1199 git_protected_config(safe_directory_cb, &data);
1201 return data.is_safe;
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;
1246 static int is_implicit_bare_repo(const char *path)
1249 * what we found is a ".git" directory at the root of
1250 * the working tree.
1252 if (ends_with_path_components(path, ".git"))
1253 return 1;
1256 * we are inside $GIT_DIR of a secondary worktree of a
1257 * non-bare repository.
1259 if (strstr(path, "/.git/worktrees/"))
1260 return 1;
1263 * we are inside $GIT_DIR of a worktree of a non-embedded
1264 * submodule, whose superproject is not a bare repository.
1266 if (strstr(path, "/.git/modules/"))
1267 return 1;
1269 return 0;
1273 * We cannot decide in this function whether we are in the work tree or
1274 * not, since the config can only be read _after_ this function was called.
1276 * Also, we avoid changing any global state (such as the current working
1277 * directory) to allow early callers.
1279 * The directory where the search should start needs to be passed in via the
1280 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1281 * the directory where the search ended, and `gitdir` will contain the path of
1282 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1283 * is relative to `dir` (i.e. *not* necessarily the cwd).
1285 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1286 struct strbuf *gitdir,
1287 struct strbuf *report,
1288 int die_on_error)
1290 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1291 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1292 const char *gitdirenv;
1293 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1294 dev_t current_device = 0;
1295 int one_filesystem = 1;
1298 * If GIT_DIR is set explicitly, we're not going
1299 * to do any discovery, but we still do repository
1300 * validation.
1302 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1303 if (gitdirenv) {
1304 strbuf_addstr(gitdir, gitdirenv);
1305 return GIT_DIR_EXPLICIT;
1308 if (env_ceiling_dirs) {
1309 int empty_entry_found = 0;
1311 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1312 filter_string_list(&ceiling_dirs, 0,
1313 canonicalize_ceiling_entry, &empty_entry_found);
1314 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1315 string_list_clear(&ceiling_dirs, 0);
1318 if (ceil_offset < 0)
1319 ceil_offset = min_offset - 2;
1321 if (min_offset && min_offset == dir->len &&
1322 !is_dir_sep(dir->buf[min_offset - 1])) {
1323 strbuf_addch(dir, '/');
1324 min_offset++;
1328 * Test in the following order (relative to the dir):
1329 * - .git (file containing "gitdir: <path>")
1330 * - .git/
1331 * - ./ (bare)
1332 * - ../.git
1333 * - ../.git/
1334 * - ../ (bare)
1335 * - ../../.git
1336 * etc.
1338 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1339 if (one_filesystem)
1340 current_device = get_device_or_die(dir->buf, NULL, 0);
1341 for (;;) {
1342 int offset = dir->len, error_code = 0;
1343 char *gitdir_path = NULL;
1344 char *gitfile = NULL;
1346 if (offset > min_offset)
1347 strbuf_addch(dir, '/');
1348 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1349 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1350 NULL : &error_code);
1351 if (!gitdirenv) {
1352 if (die_on_error ||
1353 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1354 /* NEEDSWORK: fail if .git is not file nor dir */
1355 if (is_git_directory(dir->buf)) {
1356 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1357 gitdir_path = xstrdup(dir->buf);
1359 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1360 return GIT_DIR_INVALID_GITFILE;
1361 } else
1362 gitfile = xstrdup(dir->buf);
1364 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1365 * to check that directory for a repository.
1366 * Now trim that tentative addition away, because we want to
1367 * focus on the real directory we are in.
1369 strbuf_setlen(dir, offset);
1370 if (gitdirenv) {
1371 enum discovery_result ret;
1372 const char *gitdir_candidate =
1373 gitdir_path ? gitdir_path : gitdirenv;
1375 if (ensure_valid_ownership(gitfile, dir->buf,
1376 gitdir_candidate, report)) {
1377 strbuf_addstr(gitdir, gitdirenv);
1378 ret = GIT_DIR_DISCOVERED;
1379 } else
1380 ret = GIT_DIR_INVALID_OWNERSHIP;
1383 * Earlier, during discovery, we might have allocated
1384 * string copies for gitdir_path or gitfile so make
1385 * sure we don't leak by freeing them now, before
1386 * leaving the loop and function.
1388 * Note: gitdirenv will be non-NULL whenever these are
1389 * allocated, therefore we need not take care of releasing
1390 * them outside of this conditional block.
1392 free(gitdir_path);
1393 free(gitfile);
1395 return ret;
1398 if (is_git_directory(dir->buf)) {
1399 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1400 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT &&
1401 !is_implicit_bare_repo(dir->buf))
1402 return GIT_DIR_DISALLOWED_BARE;
1403 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1404 return GIT_DIR_INVALID_OWNERSHIP;
1405 strbuf_addstr(gitdir, ".");
1406 return GIT_DIR_BARE;
1409 if (offset <= min_offset)
1410 return GIT_DIR_HIT_CEILING;
1412 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1413 ; /* continue */
1414 if (offset <= ceil_offset)
1415 return GIT_DIR_HIT_CEILING;
1417 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1418 if (one_filesystem &&
1419 current_device != get_device_or_die(dir->buf, NULL, offset))
1420 return GIT_DIR_HIT_MOUNT_POINT;
1424 enum discovery_result discover_git_directory_reason(struct strbuf *commondir,
1425 struct strbuf *gitdir)
1427 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1428 size_t gitdir_offset = gitdir->len, cwd_len;
1429 size_t commondir_offset = commondir->len;
1430 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1431 enum discovery_result result;
1433 if (strbuf_getcwd(&dir))
1434 return GIT_DIR_CWD_FAILURE;
1436 cwd_len = dir.len;
1437 result = setup_git_directory_gently_1(&dir, gitdir, NULL, 0);
1438 if (result <= 0) {
1439 strbuf_release(&dir);
1440 return result;
1444 * The returned gitdir is relative to dir, and if dir does not reflect
1445 * the current working directory, we simply make the gitdir absolute.
1447 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1448 /* Avoid a trailing "/." */
1449 if (!strcmp(".", gitdir->buf + gitdir_offset))
1450 strbuf_setlen(gitdir, gitdir_offset);
1451 else
1452 strbuf_addch(&dir, '/');
1453 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1456 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1458 strbuf_reset(&dir);
1459 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1460 read_repository_format(&candidate, dir.buf);
1461 strbuf_release(&dir);
1463 if (verify_repository_format(&candidate, &err) < 0) {
1464 warning("ignoring git dir '%s': %s",
1465 gitdir->buf + gitdir_offset, err.buf);
1466 strbuf_release(&err);
1467 strbuf_setlen(commondir, commondir_offset);
1468 strbuf_setlen(gitdir, gitdir_offset);
1469 clear_repository_format(&candidate);
1470 return GIT_DIR_INVALID_FORMAT;
1473 clear_repository_format(&candidate);
1474 return result;
1477 const char *setup_git_directory_gently(int *nongit_ok)
1479 static struct strbuf cwd = STRBUF_INIT;
1480 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1481 const char *prefix = NULL;
1482 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1485 * We may have read an incomplete configuration before
1486 * setting-up the git directory. If so, clear the cache so
1487 * that the next queries to the configuration reload complete
1488 * configuration (including the per-repo config file that we
1489 * ignored previously).
1491 git_config_clear();
1494 * Let's assume that we are in a git repository.
1495 * If it turns out later that we are somewhere else, the value will be
1496 * updated accordingly.
1498 if (nongit_ok)
1499 *nongit_ok = 0;
1501 if (strbuf_getcwd(&cwd))
1502 die_errno(_("Unable to read current working directory"));
1503 strbuf_addbuf(&dir, &cwd);
1505 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1506 case GIT_DIR_EXPLICIT:
1507 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1508 break;
1509 case GIT_DIR_DISCOVERED:
1510 if (dir.len < cwd.len && chdir(dir.buf))
1511 die(_("cannot change to '%s'"), dir.buf);
1512 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1513 &repo_fmt, nongit_ok);
1514 break;
1515 case GIT_DIR_BARE:
1516 if (dir.len < cwd.len && chdir(dir.buf))
1517 die(_("cannot change to '%s'"), dir.buf);
1518 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1519 break;
1520 case GIT_DIR_HIT_CEILING:
1521 if (!nongit_ok)
1522 die(_("not a git repository (or any of the parent directories): %s"),
1523 DEFAULT_GIT_DIR_ENVIRONMENT);
1524 *nongit_ok = 1;
1525 break;
1526 case GIT_DIR_HIT_MOUNT_POINT:
1527 if (!nongit_ok)
1528 die(_("not a git repository (or any parent up to mount point %s)\n"
1529 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1530 dir.buf);
1531 *nongit_ok = 1;
1532 break;
1533 case GIT_DIR_INVALID_OWNERSHIP:
1534 if (!nongit_ok) {
1535 struct strbuf quoted = STRBUF_INIT;
1537 strbuf_complete(&report, '\n');
1538 sq_quote_buf_pretty(&quoted, dir.buf);
1539 die(_("detected dubious ownership in repository at '%s'\n"
1540 "%s"
1541 "To add an exception for this directory, call:\n"
1542 "\n"
1543 "\tgit config --global --add safe.directory %s"),
1544 dir.buf, report.buf, quoted.buf);
1546 *nongit_ok = 1;
1547 break;
1548 case GIT_DIR_DISALLOWED_BARE:
1549 if (!nongit_ok) {
1550 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1551 dir.buf,
1552 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1554 *nongit_ok = 1;
1555 break;
1556 case GIT_DIR_CWD_FAILURE:
1557 case GIT_DIR_INVALID_FORMAT:
1559 * As a safeguard against setup_git_directory_gently_1 returning
1560 * these values, fallthrough to BUG. Otherwise it is possible to
1561 * set startup_info->have_repository to 1 when we did nothing to
1562 * find a repository.
1564 default:
1565 BUG("unhandled setup_git_directory_gently_1() result");
1569 * At this point, nongit_ok is stable. If it is non-NULL and points
1570 * to a non-zero value, then this means that we haven't found a
1571 * repository and that the caller expects startup_info to reflect
1572 * this.
1574 * Regardless of the state of nongit_ok, startup_info->prefix and
1575 * the GIT_PREFIX environment variable must always match. For details
1576 * see Documentation/config/alias.txt.
1578 if (nongit_ok && *nongit_ok)
1579 startup_info->have_repository = 0;
1580 else
1581 startup_info->have_repository = 1;
1584 * Not all paths through the setup code will call 'set_git_dir()' (which
1585 * directly sets up the environment) so in order to guarantee that the
1586 * environment is in a consistent state after setup, explicitly setup
1587 * the environment if we have a repository.
1589 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1590 * code paths so we also need to explicitly setup the environment if
1591 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1592 * GIT_DIR values at some point in the future.
1594 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1595 startup_info->have_repository ||
1596 /* GIT_DIR_EXPLICIT */
1597 getenv(GIT_DIR_ENVIRONMENT)) {
1598 if (!the_repository->gitdir) {
1599 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1600 if (!gitdir)
1601 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1602 setup_git_env(gitdir);
1604 if (startup_info->have_repository) {
1605 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1606 repo_set_ref_storage_format(the_repository,
1607 repo_fmt.ref_storage_format);
1608 the_repository->repository_format_worktree_config =
1609 repo_fmt.worktree_config;
1610 /* take ownership of repo_fmt.partial_clone */
1611 the_repository->repository_format_partial_clone =
1612 repo_fmt.partial_clone;
1613 repo_fmt.partial_clone = NULL;
1617 * Since precompose_string_if_needed() needs to look at
1618 * the core.precomposeunicode configuration, this
1619 * has to happen after the above block that finds
1620 * out where the repository is, i.e. a preparation
1621 * for calling git_config_get_bool().
1623 if (prefix) {
1624 prefix = precompose_string_if_needed(prefix);
1625 startup_info->prefix = prefix;
1626 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1627 } else {
1628 startup_info->prefix = NULL;
1629 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1632 setup_original_cwd();
1634 strbuf_release(&dir);
1635 strbuf_release(&gitdir);
1636 strbuf_release(&report);
1637 clear_repository_format(&repo_fmt);
1639 return prefix;
1642 int git_config_perm(const char *var, const char *value)
1644 int i;
1645 char *endptr;
1647 if (!value)
1648 return PERM_GROUP;
1650 if (!strcmp(value, "umask"))
1651 return PERM_UMASK;
1652 if (!strcmp(value, "group"))
1653 return PERM_GROUP;
1654 if (!strcmp(value, "all") ||
1655 !strcmp(value, "world") ||
1656 !strcmp(value, "everybody"))
1657 return PERM_EVERYBODY;
1659 /* Parse octal numbers */
1660 i = strtol(value, &endptr, 8);
1662 /* If not an octal number, maybe true/false? */
1663 if (*endptr != 0)
1664 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1667 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1668 * a chmod value to restrict to.
1670 switch (i) {
1671 case PERM_UMASK: /* 0 */
1672 return PERM_UMASK;
1673 case OLD_PERM_GROUP: /* 1 */
1674 return PERM_GROUP;
1675 case OLD_PERM_EVERYBODY: /* 2 */
1676 return PERM_EVERYBODY;
1679 /* A filemode value was given: 0xxx */
1681 if ((i & 0600) != 0600)
1682 die(_("problem with core.sharedRepository filemode value "
1683 "(0%.3o).\nThe owner of files must always have "
1684 "read and write permissions."), i);
1687 * Mask filemode value. Others can not get write permission.
1688 * x flags for directories are handled separately.
1690 return -(i & 0666);
1693 void check_repository_format(struct repository_format *fmt)
1695 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1696 if (!fmt)
1697 fmt = &repo_fmt;
1698 check_repository_format_gently(get_git_dir(), fmt, NULL);
1699 startup_info->have_repository = 1;
1700 repo_set_hash_algo(the_repository, fmt->hash_algo);
1701 repo_set_ref_storage_format(the_repository,
1702 fmt->ref_storage_format);
1703 the_repository->repository_format_worktree_config =
1704 fmt->worktree_config;
1705 the_repository->repository_format_partial_clone =
1706 xstrdup_or_null(fmt->partial_clone);
1707 clear_repository_format(&repo_fmt);
1711 * Returns the "prefix", a path to the current working directory
1712 * relative to the work tree root, or NULL, if the current working
1713 * directory is not a strict subdirectory of the work tree root. The
1714 * prefix always ends with a '/' character.
1716 const char *setup_git_directory(void)
1718 return setup_git_directory_gently(NULL);
1721 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1723 if (is_git_directory(suspect))
1724 return suspect;
1725 return read_gitfile_gently(suspect, return_error_code);
1728 /* if any standard file descriptor is missing open it to /dev/null */
1729 void sanitize_stdfds(void)
1731 int fd = xopen("/dev/null", O_RDWR);
1732 while (fd < 2)
1733 fd = xdup(fd);
1734 if (fd > 2)
1735 close(fd);
1738 int daemonize(void)
1740 #ifdef NO_POSIX_GOODIES
1741 errno = ENOSYS;
1742 return -1;
1743 #else
1744 switch (fork()) {
1745 case 0:
1746 break;
1747 case -1:
1748 die_errno(_("fork failed"));
1749 default:
1750 exit(0);
1752 if (setsid() == -1)
1753 die_errno(_("setsid failed"));
1754 close(0);
1755 close(1);
1756 close(2);
1757 sanitize_stdfds();
1758 return 0;
1759 #endif
1762 #ifdef NO_TRUSTABLE_FILEMODE
1763 #define TEST_FILEMODE 0
1764 #else
1765 #define TEST_FILEMODE 1
1766 #endif
1768 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1770 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1771 DIR *dir)
1773 size_t path_baselen = path->len;
1774 size_t template_baselen = template_path->len;
1775 struct dirent *de;
1777 /* Note: if ".git/hooks" file exists in the repository being
1778 * re-initialized, /etc/core-git/templates/hooks/update would
1779 * cause "git init" to fail here. I think this is sane but
1780 * it means that the set of templates we ship by default, along
1781 * with the way the namespace under .git/ is organized, should
1782 * be really carefully chosen.
1784 safe_create_dir(path->buf, 1);
1785 while ((de = readdir(dir)) != NULL) {
1786 struct stat st_git, st_template;
1787 int exists = 0;
1789 strbuf_setlen(path, path_baselen);
1790 strbuf_setlen(template_path, template_baselen);
1792 if (de->d_name[0] == '.')
1793 continue;
1794 strbuf_addstr(path, de->d_name);
1795 strbuf_addstr(template_path, de->d_name);
1796 if (lstat(path->buf, &st_git)) {
1797 if (errno != ENOENT)
1798 die_errno(_("cannot stat '%s'"), path->buf);
1800 else
1801 exists = 1;
1803 if (lstat(template_path->buf, &st_template))
1804 die_errno(_("cannot stat template '%s'"), template_path->buf);
1806 if (S_ISDIR(st_template.st_mode)) {
1807 DIR *subdir = opendir(template_path->buf);
1808 if (!subdir)
1809 die_errno(_("cannot opendir '%s'"), template_path->buf);
1810 strbuf_addch(path, '/');
1811 strbuf_addch(template_path, '/');
1812 copy_templates_1(path, template_path, subdir);
1813 closedir(subdir);
1815 else if (exists)
1816 continue;
1817 else if (S_ISLNK(st_template.st_mode)) {
1818 struct strbuf lnk = STRBUF_INIT;
1819 if (strbuf_readlink(&lnk, template_path->buf,
1820 st_template.st_size) < 0)
1821 die_errno(_("cannot readlink '%s'"), template_path->buf);
1822 if (symlink(lnk.buf, path->buf))
1823 die_errno(_("cannot symlink '%s' '%s'"),
1824 lnk.buf, path->buf);
1825 strbuf_release(&lnk);
1827 else if (S_ISREG(st_template.st_mode)) {
1828 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1829 die_errno(_("cannot copy '%s' to '%s'"),
1830 template_path->buf, path->buf);
1832 else
1833 error(_("ignoring template %s"), template_path->buf);
1837 static void copy_templates(const char *template_dir, const char *init_template_dir)
1839 struct strbuf path = STRBUF_INIT;
1840 struct strbuf template_path = STRBUF_INIT;
1841 size_t template_len;
1842 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1843 struct strbuf err = STRBUF_INIT;
1844 DIR *dir;
1845 char *to_free = NULL;
1847 if (!template_dir)
1848 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1849 if (!template_dir)
1850 template_dir = init_template_dir;
1851 if (!template_dir)
1852 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1853 if (!template_dir[0]) {
1854 free(to_free);
1855 return;
1858 strbuf_addstr(&template_path, template_dir);
1859 strbuf_complete(&template_path, '/');
1860 template_len = template_path.len;
1862 dir = opendir(template_path.buf);
1863 if (!dir) {
1864 warning(_("templates not found in %s"), template_dir);
1865 goto free_return;
1868 /* Make sure that template is from the correct vintage */
1869 strbuf_addstr(&template_path, "config");
1870 read_repository_format(&template_format, template_path.buf);
1871 strbuf_setlen(&template_path, template_len);
1874 * No mention of version at all is OK, but anything else should be
1875 * verified.
1877 if (template_format.version >= 0 &&
1878 verify_repository_format(&template_format, &err) < 0) {
1879 warning(_("not copying templates from '%s': %s"),
1880 template_dir, err.buf);
1881 strbuf_release(&err);
1882 goto close_free_return;
1885 strbuf_addstr(&path, get_git_common_dir());
1886 strbuf_complete(&path, '/');
1887 copy_templates_1(&path, &template_path, dir);
1888 close_free_return:
1889 closedir(dir);
1890 free_return:
1891 free(to_free);
1892 strbuf_release(&path);
1893 strbuf_release(&template_path);
1894 clear_repository_format(&template_format);
1898 * If the git_dir is not directly inside the working tree, then git will not
1899 * find it by default, and we need to set the worktree explicitly.
1901 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1903 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1904 return 0;
1905 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1906 !strcmp(git_dir, "/.git"))
1907 return 0;
1908 return 1;
1911 void initialize_repository_version(int hash_algo,
1912 unsigned int ref_storage_format,
1913 int reinit)
1915 char repo_version_string[10];
1916 int repo_version = GIT_REPO_VERSION;
1919 * Note that we initialize the repository version to 1 when the ref
1920 * storage format is unknown. This is on purpose so that we can add the
1921 * correct object format to the config during git-clone(1). The format
1922 * version will get adjusted by git-clone(1) once it has learned about
1923 * the remote repository's format.
1925 if (hash_algo != GIT_HASH_SHA1 ||
1926 ref_storage_format != REF_STORAGE_FORMAT_FILES)
1927 repo_version = GIT_REPO_VERSION_READ;
1929 /* This forces creation of new config file */
1930 xsnprintf(repo_version_string, sizeof(repo_version_string),
1931 "%d", repo_version);
1932 git_config_set("core.repositoryformatversion", repo_version_string);
1934 if (hash_algo != GIT_HASH_SHA1 && hash_algo != GIT_HASH_UNKNOWN)
1935 git_config_set("extensions.objectformat",
1936 hash_algos[hash_algo].name);
1937 else if (reinit)
1938 git_config_set_gently("extensions.objectformat", NULL);
1940 if (ref_storage_format != REF_STORAGE_FORMAT_FILES)
1941 git_config_set("extensions.refstorage",
1942 ref_storage_format_to_name(ref_storage_format));
1945 static int is_reinit(void)
1947 struct strbuf buf = STRBUF_INIT;
1948 char junk[2];
1949 int ret;
1951 git_path_buf(&buf, "HEAD");
1952 ret = !access(buf.buf, R_OK) || readlink(buf.buf, junk, sizeof(junk) - 1) != -1;
1953 strbuf_release(&buf);
1954 return ret;
1957 void create_reference_database(unsigned int ref_storage_format,
1958 const char *initial_branch, int quiet)
1960 struct strbuf err = STRBUF_INIT;
1961 int reinit = is_reinit();
1963 repo_set_ref_storage_format(the_repository, ref_storage_format);
1964 if (refs_init_db(get_main_ref_store(the_repository), 0, &err))
1965 die("failed to set up refs db: %s", err.buf);
1968 * Point the HEAD symref to the initial branch with if HEAD does
1969 * not yet exist.
1971 if (!reinit) {
1972 char *ref;
1974 if (!initial_branch)
1975 initial_branch = git_default_branch_name(quiet);
1977 ref = xstrfmt("refs/heads/%s", initial_branch);
1978 if (check_refname_format(ref, 0) < 0)
1979 die(_("invalid initial branch name: '%s'"),
1980 initial_branch);
1982 if (create_symref("HEAD", ref, NULL) < 0)
1983 exit(1);
1984 free(ref);
1987 if (reinit && initial_branch)
1988 warning(_("re-init: ignored --initial-branch=%s"),
1989 initial_branch);
1991 strbuf_release(&err);
1994 static int create_default_files(const char *template_path,
1995 const char *original_git_dir,
1996 const struct repository_format *fmt,
1997 int init_shared_repository)
1999 struct stat st1;
2000 struct strbuf buf = STRBUF_INIT;
2001 char *path;
2002 int reinit;
2003 int filemode;
2004 const char *init_template_dir = NULL;
2005 const char *work_tree = get_git_work_tree();
2008 * First copy the templates -- we might have the default
2009 * config file there, in which case we would want to read
2010 * from it after installing.
2012 * Before reading that config, we also need to clear out any cached
2013 * values (since we've just potentially changed what's available on
2014 * disk).
2016 git_config_get_pathname("init.templatedir", &init_template_dir);
2017 copy_templates(template_path, init_template_dir);
2018 free((char *)init_template_dir);
2019 git_config_clear();
2020 reset_shared_repository();
2021 git_config(git_default_config, NULL);
2023 reinit = is_reinit();
2026 * We must make sure command-line options continue to override any
2027 * values we might have just re-read from the config.
2029 if (init_shared_repository != -1)
2030 set_shared_repository(init_shared_repository);
2032 is_bare_repository_cfg = !work_tree;
2035 * We would have created the above under user's umask -- under
2036 * shared-repository settings, we would need to fix them up.
2038 if (get_shared_repository()) {
2039 adjust_shared_perm(get_git_dir());
2042 initialize_repository_version(fmt->hash_algo, fmt->ref_storage_format, 0);
2044 /* Check filemode trustability */
2045 path = git_path_buf(&buf, "config");
2046 filemode = TEST_FILEMODE;
2047 if (TEST_FILEMODE && !lstat(path, &st1)) {
2048 struct stat st2;
2049 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2050 !lstat(path, &st2) &&
2051 st1.st_mode != st2.st_mode &&
2052 !chmod(path, st1.st_mode));
2053 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2054 filemode = 0;
2056 git_config_set("core.filemode", filemode ? "true" : "false");
2058 if (is_bare_repository())
2059 git_config_set("core.bare", "true");
2060 else {
2061 git_config_set("core.bare", "false");
2062 /* allow template config file to override the default */
2063 if (log_all_ref_updates == LOG_REFS_UNSET)
2064 git_config_set("core.logallrefupdates", "true");
2065 if (needs_work_tree_config(original_git_dir, work_tree))
2066 git_config_set("core.worktree", work_tree);
2069 if (!reinit) {
2070 /* Check if symlink is supported in the work tree */
2071 path = git_path_buf(&buf, "tXXXXXX");
2072 if (!close(xmkstemp(path)) &&
2073 !unlink(path) &&
2074 !symlink("testing", path) &&
2075 !lstat(path, &st1) &&
2076 S_ISLNK(st1.st_mode))
2077 unlink(path); /* good */
2078 else
2079 git_config_set("core.symlinks", "false");
2081 /* Check if the filesystem is case-insensitive */
2082 path = git_path_buf(&buf, "CoNfIg");
2083 if (!access(path, F_OK))
2084 git_config_set("core.ignorecase", "true");
2085 probe_utf8_pathname_composition();
2088 strbuf_release(&buf);
2089 return reinit;
2092 static void create_object_directory(void)
2094 struct strbuf path = STRBUF_INIT;
2095 size_t baselen;
2097 strbuf_addstr(&path, get_object_directory());
2098 baselen = path.len;
2100 safe_create_dir(path.buf, 1);
2102 strbuf_setlen(&path, baselen);
2103 strbuf_addstr(&path, "/pack");
2104 safe_create_dir(path.buf, 1);
2106 strbuf_setlen(&path, baselen);
2107 strbuf_addstr(&path, "/info");
2108 safe_create_dir(path.buf, 1);
2110 strbuf_release(&path);
2113 static void separate_git_dir(const char *git_dir, const char *git_link)
2115 struct stat st;
2117 if (!stat(git_link, &st)) {
2118 const char *src;
2120 if (S_ISREG(st.st_mode))
2121 src = read_gitfile(git_link);
2122 else if (S_ISDIR(st.st_mode))
2123 src = git_link;
2124 else
2125 die(_("unable to handle file type %d"), (int)st.st_mode);
2127 if (rename(src, git_dir))
2128 die_errno(_("unable to move %s to %s"), src, git_dir);
2129 repair_worktrees(NULL, NULL);
2132 write_file(git_link, "gitdir: %s", git_dir);
2135 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2137 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2139 * If we already have an initialized repo, don't allow the user to
2140 * specify a different algorithm, as that could cause corruption.
2141 * Otherwise, if the user has specified one on the command line, use it.
2143 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2144 die(_("attempt to reinitialize repository with different hash"));
2145 else if (hash != GIT_HASH_UNKNOWN)
2146 repo_fmt->hash_algo = hash;
2147 else if (env) {
2148 int env_algo = hash_algo_by_name(env);
2149 if (env_algo == GIT_HASH_UNKNOWN)
2150 die(_("unknown hash algorithm '%s'"), env);
2151 repo_fmt->hash_algo = env_algo;
2155 static void validate_ref_storage_format(struct repository_format *repo_fmt,
2156 unsigned int format)
2158 const char *name = getenv("GIT_DEFAULT_REF_FORMAT");
2160 if (repo_fmt->version >= 0 &&
2161 format != REF_STORAGE_FORMAT_UNKNOWN &&
2162 format != repo_fmt->ref_storage_format) {
2163 die(_("attempt to reinitialize repository with different reference storage format"));
2164 } else if (format != REF_STORAGE_FORMAT_UNKNOWN) {
2165 repo_fmt->ref_storage_format = format;
2166 } else if (name) {
2167 format = ref_storage_format_by_name(name);
2168 if (format == REF_STORAGE_FORMAT_UNKNOWN)
2169 die(_("unknown ref storage format '%s'"), name);
2170 repo_fmt->ref_storage_format = format;
2174 int init_db(const char *git_dir, const char *real_git_dir,
2175 const char *template_dir, int hash,
2176 unsigned int ref_storage_format,
2177 const char *initial_branch,
2178 int init_shared_repository, unsigned int flags)
2180 int reinit;
2181 int exist_ok = flags & INIT_DB_EXIST_OK;
2182 char *original_git_dir = real_pathdup(git_dir, 1);
2183 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
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);
2210 /* Check to see if the repository version is right.
2211 * Note that a newly created repository does not have
2212 * config file, so this will not fail. What we are catching
2213 * is an attempt to reinitialize new repository with an old tool.
2215 check_repository_format(&repo_fmt);
2217 validate_hash_algorithm(&repo_fmt, hash);
2218 validate_ref_storage_format(&repo_fmt, ref_storage_format);
2220 reinit = create_default_files(template_dir, original_git_dir,
2221 &repo_fmt, init_shared_repository);
2224 * Now that we have set up both the hash algorithm and the ref storage
2225 * format we can update the repository's settings accordingly.
2227 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
2228 repo_set_ref_storage_format(the_repository, repo_fmt.ref_storage_format);
2230 if (!(flags & INIT_DB_SKIP_REFDB))
2231 create_reference_database(repo_fmt.ref_storage_format,
2232 initial_branch, flags & INIT_DB_QUIET);
2233 create_object_directory();
2235 if (get_shared_repository()) {
2236 char buf[10];
2237 /* We do not spell "group" and such, so that
2238 * the configuration can be read by older version
2239 * of git. Note, we use octal numbers for new share modes,
2240 * and compatibility values for PERM_GROUP and
2241 * PERM_EVERYBODY.
2243 if (get_shared_repository() < 0)
2244 /* force to the mode value */
2245 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2246 else if (get_shared_repository() == PERM_GROUP)
2247 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2248 else if (get_shared_repository() == PERM_EVERYBODY)
2249 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2250 else
2251 BUG("invalid value for shared_repository");
2252 git_config_set("core.sharedrepository", buf);
2253 git_config_set("receive.denyNonFastforwards", "true");
2256 if (!(flags & INIT_DB_QUIET)) {
2257 int len = strlen(git_dir);
2259 if (reinit)
2260 printf(get_shared_repository()
2261 ? _("Reinitialized existing shared Git repository in %s%s\n")
2262 : _("Reinitialized existing Git repository in %s%s\n"),
2263 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2264 else
2265 printf(get_shared_repository()
2266 ? _("Initialized empty shared Git repository in %s%s\n")
2267 : _("Initialized empty Git repository in %s%s\n"),
2268 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2271 clear_repository_format(&repo_fmt);
2272 free(original_git_dir);
2273 return 0;