builtin.h: remove unneccessary includes
[alt-git.git] / setup.c
blobef55ad7cda3cccd15e4032154b90739608db69d0
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "copy.h"
4 #include "environment.h"
5 #include "exec-cmd.h"
6 #include "gettext.h"
7 #include "object-name.h"
8 #include "refs.h"
9 #include "repository.h"
10 #include "config.h"
11 #include "dir.h"
12 #include "setup.h"
13 #include "string-list.h"
14 #include "chdir-notify.h"
15 #include "path.h"
16 #include "promisor-remote.h"
17 #include "quote.h"
18 #include "trace2.h"
19 #include "worktree.h"
20 #include "wrapper.h"
22 static int inside_git_dir = -1;
23 static int inside_work_tree = -1;
24 static int work_tree_config_is_bogus;
25 enum allowed_bare_repo {
26 ALLOWED_BARE_REPO_EXPLICIT = 0,
27 ALLOWED_BARE_REPO_ALL,
30 static struct startup_info the_startup_info;
31 struct startup_info *startup_info = &the_startup_info;
32 const char *tmp_original_cwd;
35 * The input parameter must contain an absolute path, and it must already be
36 * normalized.
38 * Find the part of an absolute path that lies inside the work tree by
39 * dereferencing symlinks outside the work tree, for example:
40 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
41 * /dir/file (work tree is /) -> dir/file
42 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
43 * /dir/repolink/file (repolink points to /dir/repo) -> file
44 * /dir/repo (exactly equal to work tree) -> (empty string)
46 static int abspath_part_inside_repo(char *path)
48 size_t len;
49 size_t wtlen;
50 char *path0;
51 int off;
52 const char *work_tree = get_git_work_tree();
53 struct strbuf realpath = STRBUF_INIT;
55 if (!work_tree)
56 return -1;
57 wtlen = strlen(work_tree);
58 len = strlen(path);
59 off = offset_1st_component(path);
61 /* check if work tree is already the prefix */
62 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
63 if (path[wtlen] == '/') {
64 memmove(path, path + wtlen + 1, len - wtlen);
65 return 0;
66 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
67 /* work tree is the root, or the whole path */
68 memmove(path, path + wtlen, len - wtlen + 1);
69 return 0;
71 /* work tree might match beginning of a symlink to work tree */
72 off = wtlen;
74 path0 = path;
75 path += off;
77 /* check each '/'-terminated level */
78 while (*path) {
79 path++;
80 if (*path == '/') {
81 *path = '\0';
82 strbuf_realpath(&realpath, path0, 1);
83 if (fspathcmp(realpath.buf, work_tree) == 0) {
84 memmove(path0, path + 1, len - (path - path0));
85 strbuf_release(&realpath);
86 return 0;
88 *path = '/';
92 /* check whole path */
93 strbuf_realpath(&realpath, path0, 1);
94 if (fspathcmp(realpath.buf, work_tree) == 0) {
95 *path0 = '\0';
96 strbuf_release(&realpath);
97 return 0;
100 strbuf_release(&realpath);
101 return -1;
105 * Normalize "path", prepending the "prefix" for relative paths. If
106 * remaining_prefix is not NULL, return the actual prefix still
107 * remains in the path. For example, prefix = sub1/sub2/ and path is
109 * foo -> sub1/sub2/foo (full prefix)
110 * ../foo -> sub1/foo (remaining prefix is sub1/)
111 * ../../bar -> bar (no remaining prefix)
112 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
113 * `pwd`/../bar -> sub1/bar (no remaining prefix)
115 char *prefix_path_gently(const char *prefix, int len,
116 int *remaining_prefix, const char *path)
118 const char *orig = path;
119 char *sanitized;
120 if (is_absolute_path(orig)) {
121 sanitized = xmallocz(strlen(path));
122 if (remaining_prefix)
123 *remaining_prefix = 0;
124 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
125 free(sanitized);
126 return NULL;
128 if (abspath_part_inside_repo(sanitized)) {
129 free(sanitized);
130 return NULL;
132 } else {
133 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
134 if (remaining_prefix)
135 *remaining_prefix = len;
136 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
137 free(sanitized);
138 return NULL;
141 return sanitized;
144 char *prefix_path(const char *prefix, int len, const char *path)
146 char *r = prefix_path_gently(prefix, len, NULL, path);
147 if (!r) {
148 const char *hint_path = get_git_work_tree();
149 if (!hint_path)
150 hint_path = get_git_dir();
151 die(_("'%s' is outside repository at '%s'"), path,
152 absolute_path(hint_path));
154 return r;
157 int path_inside_repo(const char *prefix, const char *path)
159 int len = prefix ? strlen(prefix) : 0;
160 char *r = prefix_path_gently(prefix, len, NULL, path);
161 if (r) {
162 free(r);
163 return 1;
165 return 0;
168 int check_filename(const char *prefix, const char *arg)
170 char *to_free = NULL;
171 struct stat st;
173 if (skip_prefix(arg, ":/", &arg)) {
174 if (!*arg) /* ":/" is root dir, always exists */
175 return 1;
176 prefix = NULL;
177 } else if (skip_prefix(arg, ":!", &arg) ||
178 skip_prefix(arg, ":^", &arg)) {
179 if (!*arg) /* excluding everything is silly, but allowed */
180 return 1;
183 if (prefix)
184 arg = to_free = prefix_filename(prefix, arg);
186 if (!lstat(arg, &st)) {
187 free(to_free);
188 return 1; /* file exists */
190 if (is_missing_file_error(errno)) {
191 free(to_free);
192 return 0; /* file does not exist */
194 die_errno(_("failed to stat '%s'"), arg);
197 static void NORETURN die_verify_filename(struct repository *r,
198 const char *prefix,
199 const char *arg,
200 int diagnose_misspelt_rev)
202 if (!diagnose_misspelt_rev)
203 die(_("%s: no such path in the working tree.\n"
204 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
205 arg);
207 * Saying "'(icase)foo' does not exist in the index" when the
208 * user gave us ":(icase)foo" is just stupid. A magic pathspec
209 * begins with a colon and is followed by a non-alnum; do not
210 * let maybe_die_on_misspelt_object_name() even trigger.
212 if (!(arg[0] == ':' && !isalnum(arg[1])))
213 maybe_die_on_misspelt_object_name(r, arg, prefix);
215 /* ... or fall back the most general message. */
216 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
217 "Use '--' to separate paths from revisions, like this:\n"
218 "'git <command> [<revision>...] -- [<file>...]'"), arg);
223 * Check for arguments that don't resolve as actual files,
224 * but which look sufficiently like pathspecs that we'll consider
225 * them such for the purposes of rev/pathspec DWIM parsing.
227 static int looks_like_pathspec(const char *arg)
229 const char *p;
230 int escaped = 0;
233 * Wildcard characters imply the user is looking to match pathspecs
234 * that aren't in the filesystem. Note that this doesn't include
235 * backslash even though it's a glob special; by itself it doesn't
236 * cause any increase in the match. Likewise ignore backslash-escaped
237 * wildcard characters.
239 for (p = arg; *p; p++) {
240 if (escaped) {
241 escaped = 0;
242 } else if (is_glob_special(*p)) {
243 if (*p == '\\')
244 escaped = 1;
245 else
246 return 1;
250 /* long-form pathspec magic */
251 if (starts_with(arg, ":("))
252 return 1;
254 return 0;
258 * Verify a filename that we got as an argument for a pathspec
259 * entry. Note that a filename that begins with "-" never verifies
260 * as true, because even if such a filename were to exist, we want
261 * it to be preceded by the "--" marker (or we want the user to
262 * use a format like "./-filename")
264 * The "diagnose_misspelt_rev" is used to provide a user-friendly
265 * diagnosis when dying upon finding that "name" is not a pathname.
266 * If set to 1, the diagnosis will try to diagnose "name" as an
267 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
268 * will only complain about an inexisting file.
270 * This function is typically called to check that a "file or rev"
271 * argument is unambiguous. In this case, the caller will want
272 * diagnose_misspelt_rev == 1 when verifying the first non-rev
273 * argument (which could have been a revision), and
274 * diagnose_misspelt_rev == 0 for the next ones (because we already
275 * saw a filename, there's not ambiguity anymore).
277 void verify_filename(const char *prefix,
278 const char *arg,
279 int diagnose_misspelt_rev)
281 if (*arg == '-')
282 die(_("option '%s' must come before non-option arguments"), arg);
283 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
284 return;
285 die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
289 * Opposite of the above: the command line did not have -- marker
290 * and we parsed the arg as a refname. It should not be interpretable
291 * as a filename.
293 void verify_non_filename(const char *prefix, const char *arg)
295 if (!is_inside_work_tree() || is_inside_git_dir())
296 return;
297 if (*arg == '-')
298 return; /* flag */
299 if (!check_filename(prefix, arg))
300 return;
301 die(_("ambiguous argument '%s': both revision and filename\n"
302 "Use '--' to separate paths from revisions, like this:\n"
303 "'git <command> [<revision>...] -- [<file>...]'"), arg);
306 int get_common_dir(struct strbuf *sb, const char *gitdir)
308 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
309 if (git_env_common_dir) {
310 strbuf_addstr(sb, git_env_common_dir);
311 return 1;
312 } else {
313 return get_common_dir_noenv(sb, gitdir);
317 int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
319 struct strbuf data = STRBUF_INIT;
320 struct strbuf path = STRBUF_INIT;
321 int ret = 0;
323 strbuf_addf(&path, "%s/commondir", gitdir);
324 if (file_exists(path.buf)) {
325 if (strbuf_read_file(&data, path.buf, 0) <= 0)
326 die_errno(_("failed to read %s"), path.buf);
327 while (data.len && (data.buf[data.len - 1] == '\n' ||
328 data.buf[data.len - 1] == '\r'))
329 data.len--;
330 data.buf[data.len] = '\0';
331 strbuf_reset(&path);
332 if (!is_absolute_path(data.buf))
333 strbuf_addf(&path, "%s/", gitdir);
334 strbuf_addbuf(&path, &data);
335 strbuf_add_real_path(sb, path.buf);
336 ret = 1;
337 } else {
338 strbuf_addstr(sb, gitdir);
341 strbuf_release(&data);
342 strbuf_release(&path);
343 return ret;
347 * Test if it looks like we're at a git directory.
348 * We want to see:
350 * - either an objects/ directory _or_ the proper
351 * GIT_OBJECT_DIRECTORY environment variable
352 * - a refs/ directory
353 * - either a HEAD symlink or a HEAD file that is formatted as
354 * a proper "ref:", or a regular file HEAD that has a properly
355 * formatted sha1 object name.
357 int is_git_directory(const char *suspect)
359 struct strbuf path = STRBUF_INIT;
360 int ret = 0;
361 size_t len;
363 /* Check worktree-related signatures */
364 strbuf_addstr(&path, suspect);
365 strbuf_complete(&path, '/');
366 strbuf_addstr(&path, "HEAD");
367 if (validate_headref(path.buf))
368 goto done;
370 strbuf_reset(&path);
371 get_common_dir(&path, suspect);
372 len = path.len;
374 /* Check non-worktree-related signatures */
375 if (getenv(DB_ENVIRONMENT)) {
376 if (access(getenv(DB_ENVIRONMENT), X_OK))
377 goto done;
379 else {
380 strbuf_setlen(&path, len);
381 strbuf_addstr(&path, "/objects");
382 if (access(path.buf, X_OK))
383 goto done;
386 strbuf_setlen(&path, len);
387 strbuf_addstr(&path, "/refs");
388 if (access(path.buf, X_OK))
389 goto done;
391 ret = 1;
392 done:
393 strbuf_release(&path);
394 return ret;
397 int is_nonbare_repository_dir(struct strbuf *path)
399 int ret = 0;
400 int gitfile_error;
401 size_t orig_path_len = path->len;
402 assert(orig_path_len != 0);
403 strbuf_complete(path, '/');
404 strbuf_addstr(path, ".git");
405 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
406 ret = 1;
407 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
408 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
409 ret = 1;
410 strbuf_setlen(path, orig_path_len);
411 return ret;
414 int is_inside_git_dir(void)
416 if (inside_git_dir < 0)
417 inside_git_dir = is_inside_dir(get_git_dir());
418 return inside_git_dir;
421 int is_inside_work_tree(void)
423 if (inside_work_tree < 0)
424 inside_work_tree = is_inside_dir(get_git_work_tree());
425 return inside_work_tree;
428 void setup_work_tree(void)
430 const char *work_tree;
431 static int initialized = 0;
433 if (initialized)
434 return;
436 if (work_tree_config_is_bogus)
437 die(_("unable to set up work tree using invalid config"));
439 work_tree = get_git_work_tree();
440 if (!work_tree || chdir_notify(work_tree))
441 die(_("this operation must be run in a work tree"));
444 * Make sure subsequent git processes find correct worktree
445 * if $GIT_WORK_TREE is set relative
447 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
448 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
450 initialized = 1;
453 static void setup_original_cwd(void)
455 struct strbuf tmp = STRBUF_INIT;
456 const char *worktree = NULL;
457 int offset = -1;
459 if (!tmp_original_cwd)
460 return;
463 * startup_info->original_cwd points to the current working
464 * directory we inherited from our parent process, which is a
465 * directory we want to avoid removing.
467 * For convience, we would like to have the path relative to the
468 * worktree instead of an absolute path.
470 * Yes, startup_info->original_cwd is usually the same as 'prefix',
471 * but differs in two ways:
472 * - prefix has a trailing '/'
473 * - if the user passes '-C' to git, that modifies the prefix but
474 * not startup_info->original_cwd.
477 /* Normalize the directory */
478 if (!strbuf_realpath(&tmp, tmp_original_cwd, 0)) {
479 trace2_data_string("setup", the_repository,
480 "realpath-path", tmp_original_cwd);
481 trace2_data_string("setup", the_repository,
482 "realpath-failure", strerror(errno));
483 free((char*)tmp_original_cwd);
484 tmp_original_cwd = NULL;
485 return;
488 free((char*)tmp_original_cwd);
489 tmp_original_cwd = NULL;
490 startup_info->original_cwd = strbuf_detach(&tmp, NULL);
493 * Get our worktree; we only protect the current working directory
494 * if it's in the worktree.
496 worktree = get_git_work_tree();
497 if (!worktree)
498 goto no_prevention_needed;
500 offset = dir_inside_of(startup_info->original_cwd, worktree);
501 if (offset >= 0) {
503 * If startup_info->original_cwd == worktree, that is already
504 * protected and we don't need original_cwd as a secondary
505 * protection measure.
507 if (!*(startup_info->original_cwd + offset))
508 goto no_prevention_needed;
511 * original_cwd was inside worktree; precompose it just as
512 * we do prefix so that built up paths will match
514 startup_info->original_cwd = \
515 precompose_string_if_needed(startup_info->original_cwd
516 + offset);
517 return;
520 no_prevention_needed:
521 free((char*)startup_info->original_cwd);
522 startup_info->original_cwd = NULL;
525 static int read_worktree_config(const char *var, const char *value, 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 data->partial_clone = xstrdup(value);
562 return EXTENSION_OK;
563 } else if (!strcmp(ext, "worktreeconfig")) {
564 data->worktree_config = git_config_bool(var, value);
565 return EXTENSION_OK;
568 return EXTENSION_UNKNOWN;
572 * Record any new extensions in this function.
574 static enum extension_result handle_extension(const char *var,
575 const char *value,
576 const char *ext,
577 struct repository_format *data)
579 if (!strcmp(ext, "noop-v1")) {
580 return EXTENSION_OK;
581 } else if (!strcmp(ext, "objectformat")) {
582 int format;
584 if (!value)
585 return config_error_nonbool(var);
586 format = hash_algo_by_name(value);
587 if (format == GIT_HASH_UNKNOWN)
588 return error(_("invalid value for '%s': '%s'"),
589 "extensions.objectformat", value);
590 data->hash_algo = format;
591 return EXTENSION_OK;
593 return EXTENSION_UNKNOWN;
596 static int check_repo_format(const char *var, const char *value, void *vdata)
598 struct repository_format *data = vdata;
599 const char *ext;
601 if (strcmp(var, "core.repositoryformatversion") == 0)
602 data->version = git_config_int(var, value);
603 else if (skip_prefix(var, "extensions.", &ext)) {
604 switch (handle_extension_v0(var, value, ext, data)) {
605 case EXTENSION_ERROR:
606 return -1;
607 case EXTENSION_OK:
608 return 0;
609 case EXTENSION_UNKNOWN:
610 break;
613 switch (handle_extension(var, value, ext, data)) {
614 case EXTENSION_ERROR:
615 return -1;
616 case EXTENSION_OK:
617 string_list_append(&data->v1_only_extensions, ext);
618 return 0;
619 case EXTENSION_UNKNOWN:
620 string_list_append(&data->unknown_extensions, ext);
621 return 0;
625 return read_worktree_config(var, value, vdata);
628 static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
630 struct strbuf sb = STRBUF_INIT;
631 struct strbuf err = STRBUF_INIT;
632 int has_common;
634 has_common = get_common_dir(&sb, gitdir);
635 strbuf_addstr(&sb, "/config");
636 read_repository_format(candidate, sb.buf);
637 strbuf_release(&sb);
640 * For historical use of check_repository_format() in git-init,
641 * we treat a missing config as a silent "ok", even when nongit_ok
642 * is unset.
644 if (candidate->version < 0)
645 return 0;
647 if (verify_repository_format(candidate, &err) < 0) {
648 if (nongit_ok) {
649 warning("%s", err.buf);
650 strbuf_release(&err);
651 *nongit_ok = -1;
652 return -1;
654 die("%s", err.buf);
657 repository_format_precious_objects = candidate->precious_objects;
658 string_list_clear(&candidate->unknown_extensions, 0);
659 string_list_clear(&candidate->v1_only_extensions, 0);
661 if (candidate->worktree_config) {
663 * pick up core.bare and core.worktree from per-worktree
664 * config if present
666 strbuf_addf(&sb, "%s/config.worktree", gitdir);
667 git_config_from_file(read_worktree_config, sb.buf, candidate);
668 strbuf_release(&sb);
669 has_common = 0;
672 if (!has_common) {
673 if (candidate->is_bare != -1) {
674 is_bare_repository_cfg = candidate->is_bare;
675 if (is_bare_repository_cfg == 1)
676 inside_work_tree = -1;
678 if (candidate->work_tree) {
679 free(git_work_tree_cfg);
680 git_work_tree_cfg = xstrdup(candidate->work_tree);
681 inside_work_tree = -1;
685 return 0;
688 int upgrade_repository_format(int target_version)
690 struct strbuf sb = STRBUF_INIT;
691 struct strbuf err = STRBUF_INIT;
692 struct strbuf repo_version = STRBUF_INIT;
693 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
695 strbuf_git_common_path(&sb, the_repository, "config");
696 read_repository_format(&repo_fmt, sb.buf);
697 strbuf_release(&sb);
699 if (repo_fmt.version >= target_version)
700 return 0;
702 if (verify_repository_format(&repo_fmt, &err) < 0) {
703 error("cannot upgrade repository format from %d to %d: %s",
704 repo_fmt.version, target_version, err.buf);
705 strbuf_release(&err);
706 return -1;
708 if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
709 return error("cannot upgrade repository format: "
710 "unknown extension %s",
711 repo_fmt.unknown_extensions.items[0].string);
713 strbuf_addf(&repo_version, "%d", target_version);
714 git_config_set("core.repositoryformatversion", repo_version.buf);
715 strbuf_release(&repo_version);
716 return 1;
719 static void init_repository_format(struct repository_format *format)
721 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
723 memcpy(format, &fresh, sizeof(fresh));
726 int read_repository_format(struct repository_format *format, const char *path)
728 clear_repository_format(format);
729 git_config_from_file(check_repo_format, path, format);
730 if (format->version == -1)
731 clear_repository_format(format);
732 return format->version;
735 void clear_repository_format(struct repository_format *format)
737 string_list_clear(&format->unknown_extensions, 0);
738 string_list_clear(&format->v1_only_extensions, 0);
739 free(format->work_tree);
740 free(format->partial_clone);
741 init_repository_format(format);
744 int verify_repository_format(const struct repository_format *format,
745 struct strbuf *err)
747 if (GIT_REPO_VERSION_READ < format->version) {
748 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
749 GIT_REPO_VERSION_READ, format->version);
750 return -1;
753 if (format->version >= 1 && format->unknown_extensions.nr) {
754 int i;
756 strbuf_addstr(err, Q_("unknown repository extension found:",
757 "unknown repository extensions found:",
758 format->unknown_extensions.nr));
760 for (i = 0; i < format->unknown_extensions.nr; i++)
761 strbuf_addf(err, "\n\t%s",
762 format->unknown_extensions.items[i].string);
763 return -1;
766 if (format->version == 0 && format->v1_only_extensions.nr) {
767 int i;
769 strbuf_addstr(err,
770 Q_("repo version is 0, but v1-only extension found:",
771 "repo version is 0, but v1-only extensions found:",
772 format->v1_only_extensions.nr));
774 for (i = 0; i < format->v1_only_extensions.nr; i++)
775 strbuf_addf(err, "\n\t%s",
776 format->v1_only_extensions.items[i].string);
777 return -1;
780 return 0;
783 void read_gitfile_error_die(int error_code, const char *path, const char *dir)
785 switch (error_code) {
786 case READ_GITFILE_ERR_STAT_FAILED:
787 case READ_GITFILE_ERR_NOT_A_FILE:
788 /* non-fatal; follow return path */
789 break;
790 case READ_GITFILE_ERR_OPEN_FAILED:
791 die_errno(_("error opening '%s'"), path);
792 case READ_GITFILE_ERR_TOO_LARGE:
793 die(_("too large to be a .git file: '%s'"), path);
794 case READ_GITFILE_ERR_READ_FAILED:
795 die(_("error reading %s"), path);
796 case READ_GITFILE_ERR_INVALID_FORMAT:
797 die(_("invalid gitfile format: %s"), path);
798 case READ_GITFILE_ERR_NO_PATH:
799 die(_("no path in gitfile: %s"), path);
800 case READ_GITFILE_ERR_NOT_A_REPO:
801 die(_("not a git repository: %s"), dir);
802 default:
803 BUG("unknown error code");
808 * Try to read the location of the git directory from the .git file,
809 * return path to git directory if found. The return value comes from
810 * a shared buffer.
812 * On failure, if return_error_code is not NULL, return_error_code
813 * will be set to an error code and NULL will be returned. If
814 * return_error_code is NULL the function will die instead (for most
815 * cases).
817 const char *read_gitfile_gently(const char *path, int *return_error_code)
819 const int max_file_size = 1 << 20; /* 1MB */
820 int error_code = 0;
821 char *buf = NULL;
822 char *dir = NULL;
823 const char *slash;
824 struct stat st;
825 int fd;
826 ssize_t len;
827 static struct strbuf realpath = STRBUF_INIT;
829 if (stat(path, &st)) {
830 /* NEEDSWORK: discern between ENOENT vs other errors */
831 error_code = READ_GITFILE_ERR_STAT_FAILED;
832 goto cleanup_return;
834 if (!S_ISREG(st.st_mode)) {
835 error_code = READ_GITFILE_ERR_NOT_A_FILE;
836 goto cleanup_return;
838 if (st.st_size > max_file_size) {
839 error_code = READ_GITFILE_ERR_TOO_LARGE;
840 goto cleanup_return;
842 fd = open(path, O_RDONLY);
843 if (fd < 0) {
844 error_code = READ_GITFILE_ERR_OPEN_FAILED;
845 goto cleanup_return;
847 buf = xmallocz(st.st_size);
848 len = read_in_full(fd, buf, st.st_size);
849 close(fd);
850 if (len != st.st_size) {
851 error_code = READ_GITFILE_ERR_READ_FAILED;
852 goto cleanup_return;
854 if (!starts_with(buf, "gitdir: ")) {
855 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
856 goto cleanup_return;
858 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
859 len--;
860 if (len < 9) {
861 error_code = READ_GITFILE_ERR_NO_PATH;
862 goto cleanup_return;
864 buf[len] = '\0';
865 dir = buf + 8;
867 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
868 size_t pathlen = slash+1 - path;
869 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
870 (int)(len - 8), buf + 8);
871 free(buf);
872 buf = dir;
874 if (!is_git_directory(dir)) {
875 error_code = READ_GITFILE_ERR_NOT_A_REPO;
876 goto cleanup_return;
879 strbuf_realpath(&realpath, dir, 1);
880 path = realpath.buf;
882 cleanup_return:
883 if (return_error_code)
884 *return_error_code = error_code;
885 else if (error_code)
886 read_gitfile_error_die(error_code, path, dir);
888 free(buf);
889 return error_code ? NULL : path;
892 static const char *setup_explicit_git_dir(const char *gitdirenv,
893 struct strbuf *cwd,
894 struct repository_format *repo_fmt,
895 int *nongit_ok)
897 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
898 const char *worktree;
899 char *gitfile;
900 int offset;
902 if (PATH_MAX - 40 < strlen(gitdirenv))
903 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
905 gitfile = (char*)read_gitfile(gitdirenv);
906 if (gitfile) {
907 gitfile = xstrdup(gitfile);
908 gitdirenv = gitfile;
911 if (!is_git_directory(gitdirenv)) {
912 if (nongit_ok) {
913 *nongit_ok = 1;
914 free(gitfile);
915 return NULL;
917 die(_("not a git repository: '%s'"), gitdirenv);
920 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
921 free(gitfile);
922 return NULL;
925 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
926 if (work_tree_env)
927 set_git_work_tree(work_tree_env);
928 else if (is_bare_repository_cfg > 0) {
929 if (git_work_tree_cfg) {
930 /* #22.2, #30 */
931 warning("core.bare and core.worktree do not make sense");
932 work_tree_config_is_bogus = 1;
935 /* #18, #26 */
936 set_git_dir(gitdirenv, 0);
937 free(gitfile);
938 return NULL;
940 else if (git_work_tree_cfg) { /* #6, #14 */
941 if (is_absolute_path(git_work_tree_cfg))
942 set_git_work_tree(git_work_tree_cfg);
943 else {
944 char *core_worktree;
945 if (chdir(gitdirenv))
946 die_errno(_("cannot chdir to '%s'"), gitdirenv);
947 if (chdir(git_work_tree_cfg))
948 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
949 core_worktree = xgetcwd();
950 if (chdir(cwd->buf))
951 die_errno(_("cannot come back to cwd"));
952 set_git_work_tree(core_worktree);
953 free(core_worktree);
956 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
957 /* #16d */
958 set_git_dir(gitdirenv, 0);
959 free(gitfile);
960 return NULL;
962 else /* #2, #10 */
963 set_git_work_tree(".");
965 /* set_git_work_tree() must have been called by now */
966 worktree = get_git_work_tree();
968 /* both get_git_work_tree() and cwd are already normalized */
969 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
970 set_git_dir(gitdirenv, 0);
971 free(gitfile);
972 return NULL;
975 offset = dir_inside_of(cwd->buf, worktree);
976 if (offset >= 0) { /* cwd inside worktree? */
977 set_git_dir(gitdirenv, 1);
978 if (chdir(worktree))
979 die_errno(_("cannot chdir to '%s'"), worktree);
980 strbuf_addch(cwd, '/');
981 free(gitfile);
982 return cwd->buf + offset;
985 /* cwd outside worktree */
986 set_git_dir(gitdirenv, 0);
987 free(gitfile);
988 return NULL;
991 static const char *setup_discovered_git_dir(const char *gitdir,
992 struct strbuf *cwd, int offset,
993 struct repository_format *repo_fmt,
994 int *nongit_ok)
996 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
997 return NULL;
999 /* --work-tree is set without --git-dir; use discovered one */
1000 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1001 char *to_free = NULL;
1002 const char *ret;
1004 if (offset != cwd->len && !is_absolute_path(gitdir))
1005 gitdir = to_free = real_pathdup(gitdir, 1);
1006 if (chdir(cwd->buf))
1007 die_errno(_("cannot come back to cwd"));
1008 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1009 free(to_free);
1010 return ret;
1013 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
1014 if (is_bare_repository_cfg > 0) {
1015 set_git_dir(gitdir, (offset != cwd->len));
1016 if (chdir(cwd->buf))
1017 die_errno(_("cannot come back to cwd"));
1018 return NULL;
1021 /* #0, #1, #5, #8, #9, #12, #13 */
1022 set_git_work_tree(".");
1023 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
1024 set_git_dir(gitdir, 0);
1025 inside_git_dir = 0;
1026 inside_work_tree = 1;
1027 if (offset >= cwd->len)
1028 return NULL;
1030 /* Make "offset" point past the '/' (already the case for root dirs) */
1031 if (offset != offset_1st_component(cwd->buf))
1032 offset++;
1033 /* Add a '/' at the end */
1034 strbuf_addch(cwd, '/');
1035 return cwd->buf + offset;
1038 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
1039 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
1040 struct repository_format *repo_fmt,
1041 int *nongit_ok)
1043 int root_len;
1045 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1046 return NULL;
1048 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
1050 /* --work-tree is set without --git-dir; use discovered one */
1051 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
1052 static const char *gitdir;
1054 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
1055 if (chdir(cwd->buf))
1056 die_errno(_("cannot come back to cwd"));
1057 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
1060 inside_git_dir = 1;
1061 inside_work_tree = 0;
1062 if (offset != cwd->len) {
1063 if (chdir(cwd->buf))
1064 die_errno(_("cannot come back to cwd"));
1065 root_len = offset_1st_component(cwd->buf);
1066 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
1067 set_git_dir(cwd->buf, 0);
1069 else
1070 set_git_dir(".", 0);
1071 return NULL;
1074 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
1076 struct stat buf;
1077 if (stat(path, &buf)) {
1078 die_errno(_("failed to stat '%*s%s%s'"),
1079 prefix_len,
1080 prefix ? prefix : "",
1081 prefix ? "/" : "", path);
1083 return buf.st_dev;
1087 * A "string_list_each_func_t" function that canonicalizes an entry
1088 * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
1089 * discards it if unusable. The presence of an empty entry in
1090 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
1091 * subsequent entries.
1093 static int canonicalize_ceiling_entry(struct string_list_item *item,
1094 void *cb_data)
1096 int *empty_entry_found = cb_data;
1097 char *ceil = item->string;
1099 if (!*ceil) {
1100 *empty_entry_found = 1;
1101 return 0;
1102 } else if (!is_absolute_path(ceil)) {
1103 return 0;
1104 } else if (*empty_entry_found) {
1105 /* Keep entry but do not canonicalize it */
1106 return 1;
1107 } else {
1108 char *real_path = real_pathdup(ceil, 0);
1109 if (!real_path) {
1110 return 0;
1112 free(item->string);
1113 item->string = real_path;
1114 return 1;
1118 struct safe_directory_data {
1119 const char *path;
1120 int is_safe;
1123 static int safe_directory_cb(const char *key, const char *value, void *d)
1125 struct safe_directory_data *data = d;
1127 if (strcmp(key, "safe.directory"))
1128 return 0;
1130 if (!value || !*value) {
1131 data->is_safe = 0;
1132 } else if (!strcmp(value, "*")) {
1133 data->is_safe = 1;
1134 } else {
1135 const char *interpolated = NULL;
1137 if (!git_config_pathname(&interpolated, key, value) &&
1138 !fspathcmp(data->path, interpolated ? interpolated : value))
1139 data->is_safe = 1;
1141 free((char *)interpolated);
1144 return 0;
1148 * Check if a repository is safe, by verifying the ownership of the
1149 * worktree (if any), the git directory, and the gitfile (if any).
1151 * Exemptions for known-safe repositories can be added via `safe.directory`
1152 * config settings; for non-bare repositories, their worktree needs to be
1153 * added, for bare ones their git directory.
1155 static int ensure_valid_ownership(const char *gitfile,
1156 const char *worktree, const char *gitdir,
1157 struct strbuf *report)
1159 struct safe_directory_data data = {
1160 .path = worktree ? worktree : gitdir
1163 if (!git_env_bool("GIT_TEST_ASSUME_DIFFERENT_OWNER", 0) &&
1164 (!gitfile || is_path_owned_by_current_user(gitfile, report)) &&
1165 (!worktree || is_path_owned_by_current_user(worktree, report)) &&
1166 (!gitdir || is_path_owned_by_current_user(gitdir, report)))
1167 return 1;
1170 * data.path is the "path" that identifies the repository and it is
1171 * constant regardless of what failed above. data.is_safe should be
1172 * initialized to false, and might be changed by the callback.
1174 git_protected_config(safe_directory_cb, &data);
1176 return data.is_safe;
1179 static int allowed_bare_repo_cb(const char *key, const char *value, void *d)
1181 enum allowed_bare_repo *allowed_bare_repo = d;
1183 if (strcasecmp(key, "safe.bareRepository"))
1184 return 0;
1186 if (!strcmp(value, "explicit")) {
1187 *allowed_bare_repo = ALLOWED_BARE_REPO_EXPLICIT;
1188 return 0;
1190 if (!strcmp(value, "all")) {
1191 *allowed_bare_repo = ALLOWED_BARE_REPO_ALL;
1192 return 0;
1194 return -1;
1197 static enum allowed_bare_repo get_allowed_bare_repo(void)
1199 enum allowed_bare_repo result = ALLOWED_BARE_REPO_ALL;
1200 git_protected_config(allowed_bare_repo_cb, &result);
1201 return result;
1204 static const char *allowed_bare_repo_to_string(
1205 enum allowed_bare_repo allowed_bare_repo)
1207 switch (allowed_bare_repo) {
1208 case ALLOWED_BARE_REPO_EXPLICIT:
1209 return "explicit";
1210 case ALLOWED_BARE_REPO_ALL:
1211 return "all";
1212 default:
1213 BUG("invalid allowed_bare_repo %d",
1214 allowed_bare_repo);
1216 return NULL;
1219 enum discovery_result {
1220 GIT_DIR_NONE = 0,
1221 GIT_DIR_EXPLICIT,
1222 GIT_DIR_DISCOVERED,
1223 GIT_DIR_BARE,
1224 /* these are errors */
1225 GIT_DIR_HIT_CEILING = -1,
1226 GIT_DIR_HIT_MOUNT_POINT = -2,
1227 GIT_DIR_INVALID_GITFILE = -3,
1228 GIT_DIR_INVALID_OWNERSHIP = -4,
1229 GIT_DIR_DISALLOWED_BARE = -5,
1233 * We cannot decide in this function whether we are in the work tree or
1234 * not, since the config can only be read _after_ this function was called.
1236 * Also, we avoid changing any global state (such as the current working
1237 * directory) to allow early callers.
1239 * The directory where the search should start needs to be passed in via the
1240 * `dir` parameter; upon return, the `dir` buffer will contain the path of
1241 * the directory where the search ended, and `gitdir` will contain the path of
1242 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
1243 * is relative to `dir` (i.e. *not* necessarily the cwd).
1245 static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
1246 struct strbuf *gitdir,
1247 struct strbuf *report,
1248 int die_on_error)
1250 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
1251 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
1252 const char *gitdirenv;
1253 int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
1254 dev_t current_device = 0;
1255 int one_filesystem = 1;
1258 * If GIT_DIR is set explicitly, we're not going
1259 * to do any discovery, but we still do repository
1260 * validation.
1262 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
1263 if (gitdirenv) {
1264 strbuf_addstr(gitdir, gitdirenv);
1265 return GIT_DIR_EXPLICIT;
1268 if (env_ceiling_dirs) {
1269 int empty_entry_found = 0;
1271 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1272 filter_string_list(&ceiling_dirs, 0,
1273 canonicalize_ceiling_entry, &empty_entry_found);
1274 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
1275 string_list_clear(&ceiling_dirs, 0);
1278 if (ceil_offset < 0)
1279 ceil_offset = min_offset - 2;
1281 if (min_offset && min_offset == dir->len &&
1282 !is_dir_sep(dir->buf[min_offset - 1])) {
1283 strbuf_addch(dir, '/');
1284 min_offset++;
1288 * Test in the following order (relative to the dir):
1289 * - .git (file containing "gitdir: <path>")
1290 * - .git/
1291 * - ./ (bare)
1292 * - ../.git
1293 * - ../.git/
1294 * - ../ (bare)
1295 * - ../../.git
1296 * etc.
1298 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
1299 if (one_filesystem)
1300 current_device = get_device_or_die(dir->buf, NULL, 0);
1301 for (;;) {
1302 int offset = dir->len, error_code = 0;
1303 char *gitdir_path = NULL;
1304 char *gitfile = NULL;
1306 if (offset > min_offset)
1307 strbuf_addch(dir, '/');
1308 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
1309 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
1310 NULL : &error_code);
1311 if (!gitdirenv) {
1312 if (die_on_error ||
1313 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
1314 /* NEEDSWORK: fail if .git is not file nor dir */
1315 if (is_git_directory(dir->buf)) {
1316 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
1317 gitdir_path = xstrdup(dir->buf);
1319 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
1320 return GIT_DIR_INVALID_GITFILE;
1321 } else
1322 gitfile = xstrdup(dir->buf);
1324 * Earlier, we tentatively added DEFAULT_GIT_DIR_ENVIRONMENT
1325 * to check that directory for a repository.
1326 * Now trim that tentative addition away, because we want to
1327 * focus on the real directory we are in.
1329 strbuf_setlen(dir, offset);
1330 if (gitdirenv) {
1331 enum discovery_result ret;
1332 const char *gitdir_candidate =
1333 gitdir_path ? gitdir_path : gitdirenv;
1335 if (ensure_valid_ownership(gitfile, dir->buf,
1336 gitdir_candidate, report)) {
1337 strbuf_addstr(gitdir, gitdirenv);
1338 ret = GIT_DIR_DISCOVERED;
1339 } else
1340 ret = GIT_DIR_INVALID_OWNERSHIP;
1343 * Earlier, during discovery, we might have allocated
1344 * string copies for gitdir_path or gitfile so make
1345 * sure we don't leak by freeing them now, before
1346 * leaving the loop and function.
1348 * Note: gitdirenv will be non-NULL whenever these are
1349 * allocated, therefore we need not take care of releasing
1350 * them outside of this conditional block.
1352 free(gitdir_path);
1353 free(gitfile);
1355 return ret;
1358 if (is_git_directory(dir->buf)) {
1359 trace2_data_string("setup", NULL, "implicit-bare-repository", dir->buf);
1360 if (get_allowed_bare_repo() == ALLOWED_BARE_REPO_EXPLICIT)
1361 return GIT_DIR_DISALLOWED_BARE;
1362 if (!ensure_valid_ownership(NULL, NULL, dir->buf, report))
1363 return GIT_DIR_INVALID_OWNERSHIP;
1364 strbuf_addstr(gitdir, ".");
1365 return GIT_DIR_BARE;
1368 if (offset <= min_offset)
1369 return GIT_DIR_HIT_CEILING;
1371 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
1372 ; /* continue */
1373 if (offset <= ceil_offset)
1374 return GIT_DIR_HIT_CEILING;
1376 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1377 if (one_filesystem &&
1378 current_device != get_device_or_die(dir->buf, NULL, offset))
1379 return GIT_DIR_HIT_MOUNT_POINT;
1383 int discover_git_directory(struct strbuf *commondir,
1384 struct strbuf *gitdir)
1386 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1387 size_t gitdir_offset = gitdir->len, cwd_len;
1388 size_t commondir_offset = commondir->len;
1389 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
1391 if (strbuf_getcwd(&dir))
1392 return -1;
1394 cwd_len = dir.len;
1395 if (setup_git_directory_gently_1(&dir, gitdir, NULL, 0) <= 0) {
1396 strbuf_release(&dir);
1397 return -1;
1401 * The returned gitdir is relative to dir, and if dir does not reflect
1402 * the current working directory, we simply make the gitdir absolute.
1404 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1405 /* Avoid a trailing "/." */
1406 if (!strcmp(".", gitdir->buf + gitdir_offset))
1407 strbuf_setlen(gitdir, gitdir_offset);
1408 else
1409 strbuf_addch(&dir, '/');
1410 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1413 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1415 strbuf_reset(&dir);
1416 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
1417 read_repository_format(&candidate, dir.buf);
1418 strbuf_release(&dir);
1420 if (verify_repository_format(&candidate, &err) < 0) {
1421 warning("ignoring git dir '%s': %s",
1422 gitdir->buf + gitdir_offset, err.buf);
1423 strbuf_release(&err);
1424 strbuf_setlen(commondir, commondir_offset);
1425 strbuf_setlen(gitdir, gitdir_offset);
1426 clear_repository_format(&candidate);
1427 return -1;
1430 the_repository->repository_format_worktree_config =
1431 candidate.worktree_config;
1433 /* take ownership of candidate.partial_clone */
1434 the_repository->repository_format_partial_clone =
1435 candidate.partial_clone;
1436 candidate.partial_clone = NULL;
1438 clear_repository_format(&candidate);
1439 return 0;
1442 const char *setup_git_directory_gently(int *nongit_ok)
1444 static struct strbuf cwd = STRBUF_INIT;
1445 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT, report = STRBUF_INIT;
1446 const char *prefix = NULL;
1447 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1450 * We may have read an incomplete configuration before
1451 * setting-up the git directory. If so, clear the cache so
1452 * that the next queries to the configuration reload complete
1453 * configuration (including the per-repo config file that we
1454 * ignored previously).
1456 git_config_clear();
1459 * Let's assume that we are in a git repository.
1460 * If it turns out later that we are somewhere else, the value will be
1461 * updated accordingly.
1463 if (nongit_ok)
1464 *nongit_ok = 0;
1466 if (strbuf_getcwd(&cwd))
1467 die_errno(_("Unable to read current working directory"));
1468 strbuf_addbuf(&dir, &cwd);
1470 switch (setup_git_directory_gently_1(&dir, &gitdir, &report, 1)) {
1471 case GIT_DIR_EXPLICIT:
1472 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
1473 break;
1474 case GIT_DIR_DISCOVERED:
1475 if (dir.len < cwd.len && chdir(dir.buf))
1476 die(_("cannot change to '%s'"), dir.buf);
1477 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
1478 &repo_fmt, nongit_ok);
1479 break;
1480 case GIT_DIR_BARE:
1481 if (dir.len < cwd.len && chdir(dir.buf))
1482 die(_("cannot change to '%s'"), dir.buf);
1483 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
1484 break;
1485 case GIT_DIR_HIT_CEILING:
1486 if (!nongit_ok)
1487 die(_("not a git repository (or any of the parent directories): %s"),
1488 DEFAULT_GIT_DIR_ENVIRONMENT);
1489 *nongit_ok = 1;
1490 break;
1491 case GIT_DIR_HIT_MOUNT_POINT:
1492 if (!nongit_ok)
1493 die(_("not a git repository (or any parent up to mount point %s)\n"
1494 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1495 dir.buf);
1496 *nongit_ok = 1;
1497 break;
1498 case GIT_DIR_INVALID_OWNERSHIP:
1499 if (!nongit_ok) {
1500 struct strbuf quoted = STRBUF_INIT;
1502 strbuf_complete(&report, '\n');
1503 sq_quote_buf_pretty(&quoted, dir.buf);
1504 die(_("detected dubious ownership in repository at '%s'\n"
1505 "%s"
1506 "To add an exception for this directory, call:\n"
1507 "\n"
1508 "\tgit config --global --add safe.directory %s"),
1509 dir.buf, report.buf, quoted.buf);
1511 *nongit_ok = 1;
1512 break;
1513 case GIT_DIR_DISALLOWED_BARE:
1514 if (!nongit_ok) {
1515 die(_("cannot use bare repository '%s' (safe.bareRepository is '%s')"),
1516 dir.buf,
1517 allowed_bare_repo_to_string(get_allowed_bare_repo()));
1519 *nongit_ok = 1;
1520 break;
1521 case GIT_DIR_NONE:
1523 * As a safeguard against setup_git_directory_gently_1 returning
1524 * this value, fallthrough to BUG. Otherwise it is possible to
1525 * set startup_info->have_repository to 1 when we did nothing to
1526 * find a repository.
1528 default:
1529 BUG("unhandled setup_git_directory_gently_1() result");
1533 * At this point, nongit_ok is stable. If it is non-NULL and points
1534 * to a non-zero value, then this means that we haven't found a
1535 * repository and that the caller expects startup_info to reflect
1536 * this.
1538 * Regardless of the state of nongit_ok, startup_info->prefix and
1539 * the GIT_PREFIX environment variable must always match. For details
1540 * see Documentation/config/alias.txt.
1542 if (nongit_ok && *nongit_ok)
1543 startup_info->have_repository = 0;
1544 else
1545 startup_info->have_repository = 1;
1548 * Not all paths through the setup code will call 'set_git_dir()' (which
1549 * directly sets up the environment) so in order to guarantee that the
1550 * environment is in a consistent state after setup, explicitly setup
1551 * the environment if we have a repository.
1553 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1554 * code paths so we also need to explicitly setup the environment if
1555 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1556 * GIT_DIR values at some point in the future.
1558 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1559 startup_info->have_repository ||
1560 /* GIT_DIR_EXPLICIT */
1561 getenv(GIT_DIR_ENVIRONMENT)) {
1562 if (!the_repository->gitdir) {
1563 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1564 if (!gitdir)
1565 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
1566 setup_git_env(gitdir);
1568 if (startup_info->have_repository) {
1569 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
1570 the_repository->repository_format_worktree_config =
1571 repo_fmt.worktree_config;
1572 /* take ownership of repo_fmt.partial_clone */
1573 the_repository->repository_format_partial_clone =
1574 repo_fmt.partial_clone;
1575 repo_fmt.partial_clone = NULL;
1579 * Since precompose_string_if_needed() needs to look at
1580 * the core.precomposeunicode configuration, this
1581 * has to happen after the above block that finds
1582 * out where the repository is, i.e. a preparation
1583 * for calling git_config_get_bool().
1585 if (prefix) {
1586 prefix = precompose_string_if_needed(prefix);
1587 startup_info->prefix = prefix;
1588 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1589 } else {
1590 startup_info->prefix = NULL;
1591 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1594 setup_original_cwd();
1596 strbuf_release(&dir);
1597 strbuf_release(&gitdir);
1598 strbuf_release(&report);
1599 clear_repository_format(&repo_fmt);
1601 return prefix;
1604 int git_config_perm(const char *var, const char *value)
1606 int i;
1607 char *endptr;
1609 if (!value)
1610 return PERM_GROUP;
1612 if (!strcmp(value, "umask"))
1613 return PERM_UMASK;
1614 if (!strcmp(value, "group"))
1615 return PERM_GROUP;
1616 if (!strcmp(value, "all") ||
1617 !strcmp(value, "world") ||
1618 !strcmp(value, "everybody"))
1619 return PERM_EVERYBODY;
1621 /* Parse octal numbers */
1622 i = strtol(value, &endptr, 8);
1624 /* If not an octal number, maybe true/false? */
1625 if (*endptr != 0)
1626 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1629 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
1630 * a chmod value to restrict to.
1632 switch (i) {
1633 case PERM_UMASK: /* 0 */
1634 return PERM_UMASK;
1635 case OLD_PERM_GROUP: /* 1 */
1636 return PERM_GROUP;
1637 case OLD_PERM_EVERYBODY: /* 2 */
1638 return PERM_EVERYBODY;
1641 /* A filemode value was given: 0xxx */
1643 if ((i & 0600) != 0600)
1644 die(_("problem with core.sharedRepository filemode value "
1645 "(0%.3o).\nThe owner of files must always have "
1646 "read and write permissions."), i);
1649 * Mask filemode value. Others can not get write permission.
1650 * x flags for directories are handled separately.
1652 return -(i & 0666);
1655 void check_repository_format(struct repository_format *fmt)
1657 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
1658 if (!fmt)
1659 fmt = &repo_fmt;
1660 check_repository_format_gently(get_git_dir(), fmt, NULL);
1661 startup_info->have_repository = 1;
1662 repo_set_hash_algo(the_repository, fmt->hash_algo);
1663 the_repository->repository_format_worktree_config =
1664 fmt->worktree_config;
1665 the_repository->repository_format_partial_clone =
1666 xstrdup_or_null(fmt->partial_clone);
1667 clear_repository_format(&repo_fmt);
1671 * Returns the "prefix", a path to the current working directory
1672 * relative to the work tree root, or NULL, if the current working
1673 * directory is not a strict subdirectory of the work tree root. The
1674 * prefix always ends with a '/' character.
1676 const char *setup_git_directory(void)
1678 return setup_git_directory_gently(NULL);
1681 const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
1683 if (is_git_directory(suspect))
1684 return suspect;
1685 return read_gitfile_gently(suspect, return_error_code);
1688 /* if any standard file descriptor is missing open it to /dev/null */
1689 void sanitize_stdfds(void)
1691 int fd = xopen("/dev/null", O_RDWR);
1692 while (fd < 2)
1693 fd = xdup(fd);
1694 if (fd > 2)
1695 close(fd);
1698 int daemonize(void)
1700 #ifdef NO_POSIX_GOODIES
1701 errno = ENOSYS;
1702 return -1;
1703 #else
1704 switch (fork()) {
1705 case 0:
1706 break;
1707 case -1:
1708 die_errno(_("fork failed"));
1709 default:
1710 exit(0);
1712 if (setsid() == -1)
1713 die_errno(_("setsid failed"));
1714 close(0);
1715 close(1);
1716 close(2);
1717 sanitize_stdfds();
1718 return 0;
1719 #endif
1722 #ifdef NO_TRUSTABLE_FILEMODE
1723 #define TEST_FILEMODE 0
1724 #else
1725 #define TEST_FILEMODE 1
1726 #endif
1728 #define GIT_DEFAULT_HASH_ENVIRONMENT "GIT_DEFAULT_HASH"
1730 static void copy_templates_1(struct strbuf *path, struct strbuf *template_path,
1731 DIR *dir)
1733 size_t path_baselen = path->len;
1734 size_t template_baselen = template_path->len;
1735 struct dirent *de;
1737 /* Note: if ".git/hooks" file exists in the repository being
1738 * re-initialized, /etc/core-git/templates/hooks/update would
1739 * cause "git init" to fail here. I think this is sane but
1740 * it means that the set of templates we ship by default, along
1741 * with the way the namespace under .git/ is organized, should
1742 * be really carefully chosen.
1744 safe_create_dir(path->buf, 1);
1745 while ((de = readdir(dir)) != NULL) {
1746 struct stat st_git, st_template;
1747 int exists = 0;
1749 strbuf_setlen(path, path_baselen);
1750 strbuf_setlen(template_path, template_baselen);
1752 if (de->d_name[0] == '.')
1753 continue;
1754 strbuf_addstr(path, de->d_name);
1755 strbuf_addstr(template_path, de->d_name);
1756 if (lstat(path->buf, &st_git)) {
1757 if (errno != ENOENT)
1758 die_errno(_("cannot stat '%s'"), path->buf);
1760 else
1761 exists = 1;
1763 if (lstat(template_path->buf, &st_template))
1764 die_errno(_("cannot stat template '%s'"), template_path->buf);
1766 if (S_ISDIR(st_template.st_mode)) {
1767 DIR *subdir = opendir(template_path->buf);
1768 if (!subdir)
1769 die_errno(_("cannot opendir '%s'"), template_path->buf);
1770 strbuf_addch(path, '/');
1771 strbuf_addch(template_path, '/');
1772 copy_templates_1(path, template_path, subdir);
1773 closedir(subdir);
1775 else if (exists)
1776 continue;
1777 else if (S_ISLNK(st_template.st_mode)) {
1778 struct strbuf lnk = STRBUF_INIT;
1779 if (strbuf_readlink(&lnk, template_path->buf,
1780 st_template.st_size) < 0)
1781 die_errno(_("cannot readlink '%s'"), template_path->buf);
1782 if (symlink(lnk.buf, path->buf))
1783 die_errno(_("cannot symlink '%s' '%s'"),
1784 lnk.buf, path->buf);
1785 strbuf_release(&lnk);
1787 else if (S_ISREG(st_template.st_mode)) {
1788 if (copy_file(path->buf, template_path->buf, st_template.st_mode))
1789 die_errno(_("cannot copy '%s' to '%s'"),
1790 template_path->buf, path->buf);
1792 else
1793 error(_("ignoring template %s"), template_path->buf);
1797 static void copy_templates(const char *template_dir, const char *init_template_dir)
1799 struct strbuf path = STRBUF_INIT;
1800 struct strbuf template_path = STRBUF_INIT;
1801 size_t template_len;
1802 struct repository_format template_format = REPOSITORY_FORMAT_INIT;
1803 struct strbuf err = STRBUF_INIT;
1804 DIR *dir;
1805 char *to_free = NULL;
1807 if (!template_dir)
1808 template_dir = getenv(TEMPLATE_DIR_ENVIRONMENT);
1809 if (!template_dir)
1810 template_dir = init_template_dir;
1811 if (!template_dir)
1812 template_dir = to_free = system_path(DEFAULT_GIT_TEMPLATE_DIR);
1813 if (!template_dir[0]) {
1814 free(to_free);
1815 return;
1818 strbuf_addstr(&template_path, template_dir);
1819 strbuf_complete(&template_path, '/');
1820 template_len = template_path.len;
1822 dir = opendir(template_path.buf);
1823 if (!dir) {
1824 warning(_("templates not found in %s"), template_dir);
1825 goto free_return;
1828 /* Make sure that template is from the correct vintage */
1829 strbuf_addstr(&template_path, "config");
1830 read_repository_format(&template_format, template_path.buf);
1831 strbuf_setlen(&template_path, template_len);
1834 * No mention of version at all is OK, but anything else should be
1835 * verified.
1837 if (template_format.version >= 0 &&
1838 verify_repository_format(&template_format, &err) < 0) {
1839 warning(_("not copying templates from '%s': %s"),
1840 template_dir, err.buf);
1841 strbuf_release(&err);
1842 goto close_free_return;
1845 strbuf_addstr(&path, get_git_common_dir());
1846 strbuf_complete(&path, '/');
1847 copy_templates_1(&path, &template_path, dir);
1848 close_free_return:
1849 closedir(dir);
1850 free_return:
1851 free(to_free);
1852 strbuf_release(&path);
1853 strbuf_release(&template_path);
1854 clear_repository_format(&template_format);
1858 * If the git_dir is not directly inside the working tree, then git will not
1859 * find it by default, and we need to set the worktree explicitly.
1861 static int needs_work_tree_config(const char *git_dir, const char *work_tree)
1863 if (!strcmp(work_tree, "/") && !strcmp(git_dir, "/.git"))
1864 return 0;
1865 if (skip_prefix(git_dir, work_tree, &git_dir) &&
1866 !strcmp(git_dir, "/.git"))
1867 return 0;
1868 return 1;
1871 void initialize_repository_version(int hash_algo, int reinit)
1873 char repo_version_string[10];
1874 int repo_version = GIT_REPO_VERSION;
1876 if (hash_algo != GIT_HASH_SHA1)
1877 repo_version = GIT_REPO_VERSION_READ;
1879 /* This forces creation of new config file */
1880 xsnprintf(repo_version_string, sizeof(repo_version_string),
1881 "%d", repo_version);
1882 git_config_set("core.repositoryformatversion", repo_version_string);
1884 if (hash_algo != GIT_HASH_SHA1)
1885 git_config_set("extensions.objectformat",
1886 hash_algos[hash_algo].name);
1887 else if (reinit)
1888 git_config_set_gently("extensions.objectformat", NULL);
1891 static int create_default_files(const char *template_path,
1892 const char *original_git_dir,
1893 const char *initial_branch,
1894 const struct repository_format *fmt,
1895 int prev_bare_repository,
1896 int init_shared_repository,
1897 int quiet)
1899 struct stat st1;
1900 struct strbuf buf = STRBUF_INIT;
1901 char *path;
1902 char junk[2];
1903 int reinit;
1904 int filemode;
1905 struct strbuf err = STRBUF_INIT;
1906 const char *init_template_dir = NULL;
1907 const char *work_tree = get_git_work_tree();
1910 * First copy the templates -- we might have the default
1911 * config file there, in which case we would want to read
1912 * from it after installing.
1914 * Before reading that config, we also need to clear out any cached
1915 * values (since we've just potentially changed what's available on
1916 * disk).
1918 git_config_get_pathname("init.templatedir", &init_template_dir);
1919 copy_templates(template_path, init_template_dir);
1920 free((char *)init_template_dir);
1921 git_config_clear();
1922 reset_shared_repository();
1923 git_config(git_default_config, NULL);
1926 * We must make sure command-line options continue to override any
1927 * values we might have just re-read from the config.
1929 if (init_shared_repository != -1)
1930 set_shared_repository(init_shared_repository);
1932 * TODO: heed core.bare from config file in templates if no
1933 * command-line override given
1935 is_bare_repository_cfg = prev_bare_repository || !work_tree;
1936 /* TODO (continued):
1938 * Unfortunately, the line above is equivalent to
1939 * is_bare_repository_cfg = !work_tree;
1940 * which ignores the config entirely even if no `--[no-]bare`
1941 * command line option was present.
1943 * To see why, note that before this function, there was this call:
1944 * prev_bare_repository = is_bare_repository()
1945 * expanding the right hand side:
1946 * = is_bare_repository_cfg && !get_git_work_tree()
1947 * = is_bare_repository_cfg && !work_tree
1948 * note that the last simplification above is valid because nothing
1949 * calls repo_init() or set_git_work_tree() between any of the
1950 * relevant calls in the code, and thus the !get_git_work_tree()
1951 * calls will return the same result each time. So, what we are
1952 * interested in computing is the right hand side of the line of
1953 * code just above this comment:
1954 * prev_bare_repository || !work_tree
1955 * = is_bare_repository_cfg && !work_tree || !work_tree
1956 * = !work_tree
1957 * because "A && !B || !B == !B" for all boolean values of A & B.
1961 * We would have created the above under user's umask -- under
1962 * shared-repository settings, we would need to fix them up.
1964 if (get_shared_repository()) {
1965 adjust_shared_perm(get_git_dir());
1969 * We need to create a "refs" dir in any case so that older
1970 * versions of git can tell that this is a repository.
1972 safe_create_dir(git_path("refs"), 1);
1973 adjust_shared_perm(git_path("refs"));
1975 if (refs_init_db(&err))
1976 die("failed to set up refs db: %s", err.buf);
1979 * Point the HEAD symref to the initial branch with if HEAD does
1980 * not yet exist.
1982 path = git_path_buf(&buf, "HEAD");
1983 reinit = (!access(path, R_OK)
1984 || readlink(path, junk, sizeof(junk)-1) != -1);
1985 if (!reinit) {
1986 char *ref;
1988 if (!initial_branch)
1989 initial_branch = git_default_branch_name(quiet);
1991 ref = xstrfmt("refs/heads/%s", initial_branch);
1992 if (check_refname_format(ref, 0) < 0)
1993 die(_("invalid initial branch name: '%s'"),
1994 initial_branch);
1996 if (create_symref("HEAD", ref, NULL) < 0)
1997 exit(1);
1998 free(ref);
2001 initialize_repository_version(fmt->hash_algo, 0);
2003 /* Check filemode trustability */
2004 path = git_path_buf(&buf, "config");
2005 filemode = TEST_FILEMODE;
2006 if (TEST_FILEMODE && !lstat(path, &st1)) {
2007 struct stat st2;
2008 filemode = (!chmod(path, st1.st_mode ^ S_IXUSR) &&
2009 !lstat(path, &st2) &&
2010 st1.st_mode != st2.st_mode &&
2011 !chmod(path, st1.st_mode));
2012 if (filemode && !reinit && (st1.st_mode & S_IXUSR))
2013 filemode = 0;
2015 git_config_set("core.filemode", filemode ? "true" : "false");
2017 if (is_bare_repository())
2018 git_config_set("core.bare", "true");
2019 else {
2020 git_config_set("core.bare", "false");
2021 /* allow template config file to override the default */
2022 if (log_all_ref_updates == LOG_REFS_UNSET)
2023 git_config_set("core.logallrefupdates", "true");
2024 if (needs_work_tree_config(original_git_dir, work_tree))
2025 git_config_set("core.worktree", work_tree);
2028 if (!reinit) {
2029 /* Check if symlink is supported in the work tree */
2030 path = git_path_buf(&buf, "tXXXXXX");
2031 if (!close(xmkstemp(path)) &&
2032 !unlink(path) &&
2033 !symlink("testing", path) &&
2034 !lstat(path, &st1) &&
2035 S_ISLNK(st1.st_mode))
2036 unlink(path); /* good */
2037 else
2038 git_config_set("core.symlinks", "false");
2040 /* Check if the filesystem is case-insensitive */
2041 path = git_path_buf(&buf, "CoNfIg");
2042 if (!access(path, F_OK))
2043 git_config_set("core.ignorecase", "true");
2044 probe_utf8_pathname_composition();
2047 strbuf_release(&buf);
2048 return reinit;
2051 static void create_object_directory(void)
2053 struct strbuf path = STRBUF_INIT;
2054 size_t baselen;
2056 strbuf_addstr(&path, get_object_directory());
2057 baselen = path.len;
2059 safe_create_dir(path.buf, 1);
2061 strbuf_setlen(&path, baselen);
2062 strbuf_addstr(&path, "/pack");
2063 safe_create_dir(path.buf, 1);
2065 strbuf_setlen(&path, baselen);
2066 strbuf_addstr(&path, "/info");
2067 safe_create_dir(path.buf, 1);
2069 strbuf_release(&path);
2072 static void separate_git_dir(const char *git_dir, const char *git_link)
2074 struct stat st;
2076 if (!stat(git_link, &st)) {
2077 const char *src;
2079 if (S_ISREG(st.st_mode))
2080 src = read_gitfile(git_link);
2081 else if (S_ISDIR(st.st_mode))
2082 src = git_link;
2083 else
2084 die(_("unable to handle file type %d"), (int)st.st_mode);
2086 if (rename(src, git_dir))
2087 die_errno(_("unable to move %s to %s"), src, git_dir);
2088 repair_worktrees(NULL, NULL);
2091 write_file(git_link, "gitdir: %s", git_dir);
2094 static void validate_hash_algorithm(struct repository_format *repo_fmt, int hash)
2096 const char *env = getenv(GIT_DEFAULT_HASH_ENVIRONMENT);
2098 * If we already have an initialized repo, don't allow the user to
2099 * specify a different algorithm, as that could cause corruption.
2100 * Otherwise, if the user has specified one on the command line, use it.
2102 if (repo_fmt->version >= 0 && hash != GIT_HASH_UNKNOWN && hash != repo_fmt->hash_algo)
2103 die(_("attempt to reinitialize repository with different hash"));
2104 else if (hash != GIT_HASH_UNKNOWN)
2105 repo_fmt->hash_algo = hash;
2106 else if (env) {
2107 int env_algo = hash_algo_by_name(env);
2108 if (env_algo == GIT_HASH_UNKNOWN)
2109 die(_("unknown hash algorithm '%s'"), env);
2110 repo_fmt->hash_algo = env_algo;
2114 int init_db(const char *git_dir, const char *real_git_dir,
2115 const char *template_dir, int hash, const char *initial_branch,
2116 int init_shared_repository, unsigned int flags)
2118 int reinit;
2119 int exist_ok = flags & INIT_DB_EXIST_OK;
2120 char *original_git_dir = real_pathdup(git_dir, 1);
2121 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
2122 int prev_bare_repository;
2124 if (real_git_dir) {
2125 struct stat st;
2127 if (!exist_ok && !stat(git_dir, &st))
2128 die(_("%s already exists"), git_dir);
2130 if (!exist_ok && !stat(real_git_dir, &st))
2131 die(_("%s already exists"), real_git_dir);
2133 set_git_dir(real_git_dir, 1);
2134 git_dir = get_git_dir();
2135 separate_git_dir(git_dir, original_git_dir);
2137 else {
2138 set_git_dir(git_dir, 1);
2139 git_dir = get_git_dir();
2141 startup_info->have_repository = 1;
2143 /* Ensure `core.hidedotfiles` is processed */
2144 git_config(platform_core_config, NULL);
2146 safe_create_dir(git_dir, 0);
2148 prev_bare_repository = is_bare_repository();
2150 /* Check to see if the repository version is right.
2151 * Note that a newly created repository does not have
2152 * config file, so this will not fail. What we are catching
2153 * is an attempt to reinitialize new repository with an old tool.
2155 check_repository_format(&repo_fmt);
2157 validate_hash_algorithm(&repo_fmt, hash);
2159 reinit = create_default_files(template_dir, original_git_dir,
2160 initial_branch, &repo_fmt,
2161 prev_bare_repository,
2162 init_shared_repository,
2163 flags & INIT_DB_QUIET);
2164 if (reinit && initial_branch)
2165 warning(_("re-init: ignored --initial-branch=%s"),
2166 initial_branch);
2168 create_object_directory();
2170 if (get_shared_repository()) {
2171 char buf[10];
2172 /* We do not spell "group" and such, so that
2173 * the configuration can be read by older version
2174 * of git. Note, we use octal numbers for new share modes,
2175 * and compatibility values for PERM_GROUP and
2176 * PERM_EVERYBODY.
2178 if (get_shared_repository() < 0)
2179 /* force to the mode value */
2180 xsnprintf(buf, sizeof(buf), "0%o", -get_shared_repository());
2181 else if (get_shared_repository() == PERM_GROUP)
2182 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_GROUP);
2183 else if (get_shared_repository() == PERM_EVERYBODY)
2184 xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
2185 else
2186 BUG("invalid value for shared_repository");
2187 git_config_set("core.sharedrepository", buf);
2188 git_config_set("receive.denyNonFastforwards", "true");
2191 if (!(flags & INIT_DB_QUIET)) {
2192 int len = strlen(git_dir);
2194 if (reinit)
2195 printf(get_shared_repository()
2196 ? _("Reinitialized existing shared Git repository in %s%s\n")
2197 : _("Reinitialized existing Git repository in %s%s\n"),
2198 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2199 else
2200 printf(get_shared_repository()
2201 ? _("Initialized empty shared Git repository in %s%s\n")
2202 : _("Initialized empty Git repository in %s%s\n"),
2203 git_dir, len && git_dir[len-1] != '/' ? "/" : "");
2206 free(original_git_dir);
2207 return 0;