]> git.ipfire.org Git - thirdparty/git.git/blame - setup.c
Merge branch 'mh/pack-protocol-doc-fix'
[thirdparty/git.git] / setup.c
CommitLineData
d288a700 1#include "cache.h"
c14c234f 2#include "repository.h"
b2141fc1 3#include "config.h"
e90fdc39 4#include "dir.h"
31171d9e 5#include "string-list.h"
8500e0de 6#include "chdir-notify.h"
e90fdc39
JS
7
8static int inside_git_dir = -1;
9static int inside_work_tree = -1;
fada7674 10static int work_tree_config_is_bogus;
d288a700 11
46c3cd44
JK
12static struct startup_info the_startup_info;
13struct startup_info *startup_info = &the_startup_info;
14
ddc2a628
MEW
15/*
16 * The input parameter must contain an absolute path, and it must already be
17 * normalized.
18 *
19 * Find the part of an absolute path that lies inside the work tree by
20 * dereferencing symlinks outside the work tree, for example:
21 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
22 * /dir/file (work tree is /) -> dir/file
23 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
24 * /dir/repolink/file (repolink points to /dir/repo) -> file
25 * /dir/repo (exactly equal to work tree) -> (empty string)
26 */
27static int abspath_part_inside_repo(char *path)
28{
29 size_t len;
30 size_t wtlen;
31 char *path0;
32 int off;
33 const char *work_tree = get_git_work_tree();
34
35 if (!work_tree)
36 return -1;
37 wtlen = strlen(work_tree);
38 len = strlen(path);
6127ff63 39 off = offset_1st_component(path);
ddc2a628
MEW
40
41 /* check if work tree is already the prefix */
d8727b36 42 if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
ddc2a628
MEW
43 if (path[wtlen] == '/') {
44 memmove(path, path + wtlen + 1, len - wtlen);
45 return 0;
46 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
47 /* work tree is the root, or the whole path */
48 memmove(path, path + wtlen, len - wtlen + 1);
49 return 0;
50 }
51 /* work tree might match beginning of a symlink to work tree */
52 off = wtlen;
53 }
54 path0 = path;
6127ff63 55 path += off;
ddc2a628
MEW
56
57 /* check each '/'-terminated level */
58 while (*path) {
59 path++;
60 if (*path == '/') {
61 *path = '\0';
d8727b36 62 if (fspathcmp(real_path(path0), work_tree) == 0) {
ddc2a628
MEW
63 memmove(path0, path + 1, len - (path - path0));
64 return 0;
65 }
66 *path = '/';
67 }
68 }
69
70 /* check whole path */
d8727b36 71 if (fspathcmp(real_path(path0), work_tree) == 0) {
ddc2a628
MEW
72 *path0 = '\0';
73 return 0;
74 }
75
76 return -1;
77}
78
645a29c4
NTND
79/*
80 * Normalize "path", prepending the "prefix" for relative paths. If
81 * remaining_prefix is not NULL, return the actual prefix still
82 * remains in the path. For example, prefix = sub1/sub2/ and path is
83 *
84 * foo -> sub1/sub2/foo (full prefix)
85 * ../foo -> sub1/foo (remaining prefix is sub1/)
86 * ../../bar -> bar (no remaining prefix)
87 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
88 * `pwd`/../bar -> sub1/bar (no remaining prefix)
89 */
90char *prefix_path_gently(const char *prefix, int len,
91 int *remaining_prefix, const char *path)
d089ebaa
JH
92{
93 const char *orig = path;
18e051a3
CMAB
94 char *sanitized;
95 if (is_absolute_path(orig)) {
3733e694 96 sanitized = xmallocz(strlen(path));
645a29c4
NTND
97 if (remaining_prefix)
98 *remaining_prefix = 0;
655ee9ea
MEW
99 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
100 free(sanitized);
101 return NULL;
102 }
103 if (abspath_part_inside_repo(sanitized)) {
104 free(sanitized);
105 return NULL;
106 }
18e051a3 107 } else {
24041d6b 108 sanitized = xstrfmt("%.*s%s", len, len ? prefix : "", path);
645a29c4
NTND
109 if (remaining_prefix)
110 *remaining_prefix = len;
655ee9ea 111 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
546e0fd9
JK
112 free(sanitized);
113 return NULL;
d089ebaa 114 }
d089ebaa
JH
115 }
116 return sanitized;
f332726e
LT
117}
118
546e0fd9
JK
119char *prefix_path(const char *prefix, int len, const char *path)
120{
645a29c4 121 char *r = prefix_path_gently(prefix, len, NULL, path);
546e0fd9 122 if (!r)
fc045fe7 123 die(_("'%s' is outside repository"), path);
546e0fd9
JK
124 return r;
125}
126
127int path_inside_repo(const char *prefix, const char *path)
128{
129 int len = prefix ? strlen(prefix) : 0;
645a29c4 130 char *r = prefix_path_gently(prefix, len, NULL, path);
546e0fd9
JK
131 if (r) {
132 free(r);
133 return 1;
134 }
135 return 0;
136}
137
c6e8c800
JH
138int check_filename(const char *prefix, const char *arg)
139{
e4da43b1 140 char *to_free = NULL;
c6e8c800
JH
141 struct stat st;
142
d51c6ee0
JK
143 if (skip_prefix(arg, ":/", &arg)) {
144 if (!*arg) /* ":/" is root dir, always exists */
4db86e8b 145 return 1;
a08cbcda 146 prefix = NULL;
42471bce
JK
147 } else if (skip_prefix(arg, ":!", &arg) ||
148 skip_prefix(arg, ":^", &arg)) {
149 if (!*arg) /* excluding everything is silly, but allowed */
150 return 1;
a08cbcda
JK
151 }
152
153 if (prefix)
154 arg = to_free = prefix_filename(prefix, arg);
155
156 if (!lstat(arg, &st)) {
e4da43b1 157 free(to_free);
c6e8c800 158 return 1; /* file exists */
e4da43b1 159 }
93dd544f 160 if (is_missing_file_error(errno)) {
e4da43b1 161 free(to_free);
c6e8c800 162 return 0; /* file does not exist */
e4da43b1 163 }
fc045fe7 164 die_errno(_("failed to stat '%s'"), arg);
c6e8c800
JH
165}
166
023e37c3
MM
167static void NORETURN die_verify_filename(const char *prefix,
168 const char *arg,
169 int diagnose_misspelt_rev)
009fee47 170{
023e37c3 171 if (!diagnose_misspelt_rev)
ab33a76e
VA
172 die(_("%s: no such path in the working tree.\n"
173 "Use 'git <command> -- <path>...' to specify paths that do not exist locally."),
023e37c3 174 arg);
0e539dca
JH
175 /*
176 * Saying "'(icase)foo' does not exist in the index" when the
177 * user gave us ":(icase)foo" is just stupid. A magic pathspec
178 * begins with a colon and is followed by a non-alnum; do not
8c135ea2 179 * let maybe_die_on_misspelt_object_name() even trigger.
0e539dca
JH
180 */
181 if (!(arg[0] == ':' && !isalnum(arg[1])))
8c135ea2 182 maybe_die_on_misspelt_object_name(arg, prefix);
0e539dca 183
009fee47 184 /* ... or fall back the most general message. */
ab33a76e
VA
185 die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
186 "Use '--' to separate paths from revisions, like this:\n"
187 "'git <command> [<revision>...] -- [<file>...]'"), arg);
009fee47
MM
188
189}
190
c99eddd8
JK
191/*
192 * Check for arguments that don't resolve as actual files,
193 * but which look sufficiently like pathspecs that we'll consider
194 * them such for the purposes of rev/pathspec DWIM parsing.
195 */
196static int looks_like_pathspec(const char *arg)
197{
198 /* anything with a wildcard character */
199 if (!no_wildcard(arg))
200 return 1;
201
202 /* long-form pathspec magic */
203 if (starts_with(arg, ":("))
204 return 1;
205
206 return 0;
207}
208
e23d0b4a
LT
209/*
210 * Verify a filename that we got as an argument for a pathspec
211 * entry. Note that a filename that begins with "-" never verifies
212 * as true, because even if such a filename were to exist, we want
213 * it to be preceded by the "--" marker (or we want the user to
214 * use a format like "./-filename")
023e37c3
MM
215 *
216 * The "diagnose_misspelt_rev" is used to provide a user-friendly
217 * diagnosis when dying upon finding that "name" is not a pathname.
218 * If set to 1, the diagnosis will try to diagnose "name" as an
219 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
220 * will only complain about an inexisting file.
221 *
222 * This function is typically called to check that a "file or rev"
223 * argument is unambiguous. In this case, the caller will want
224 * diagnose_misspelt_rev == 1 when verifying the first non-rev
225 * argument (which could have been a revision), and
226 * diagnose_misspelt_rev == 0 for the next ones (because we already
227 * saw a filename, there's not ambiguity anymore).
e23d0b4a 228 */
023e37c3
MM
229void verify_filename(const char *prefix,
230 const char *arg,
231 int diagnose_misspelt_rev)
e23d0b4a 232{
e23d0b4a 233 if (*arg == '-')
fc045fe7 234 die(_("option '%s' must come before non-option arguments"), arg);
2cb47ab6 235 if (looks_like_pathspec(arg) || check_filename(prefix, arg))
e23d0b4a 236 return;
023e37c3 237 die_verify_filename(prefix, arg, diagnose_misspelt_rev);
e23d0b4a
LT
238}
239
ea92f41f
JH
240/*
241 * Opposite of the above: the command line did not have -- marker
242 * and we parsed the arg as a refname. It should not be interpretable
243 * as a filename.
244 */
245void verify_non_filename(const char *prefix, const char *arg)
246{
7ae3df8c 247 if (!is_inside_work_tree() || is_inside_git_dir())
68025633 248 return;
ea92f41f
JH
249 if (*arg == '-')
250 return; /* flag */
c6e8c800
JH
251 if (!check_filename(prefix, arg))
252 return;
ab33a76e
VA
253 die(_("ambiguous argument '%s': both revision and filename\n"
254 "Use '--' to separate paths from revisions, like this:\n"
255 "'git <command> [<revision>...] -- [<file>...]'"), arg);
ea92f41f
JH
256}
257
31e26ebc 258int get_common_dir(struct strbuf *sb, const char *gitdir)
11f9dd71
MK
259{
260 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
261 if (git_env_common_dir) {
262 strbuf_addstr(sb, git_env_common_dir);
263 return 1;
264 } else {
265 return get_common_dir_noenv(sb, gitdir);
266 }
267}
268
269int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
4dc4e145
NTND
270{
271 struct strbuf data = STRBUF_INIT;
272 struct strbuf path = STRBUF_INIT;
31e26ebc 273 int ret = 0;
11f9dd71 274
4dc4e145
NTND
275 strbuf_addf(&path, "%s/commondir", gitdir);
276 if (file_exists(path.buf)) {
277 if (strbuf_read_file(&data, path.buf, 0) <= 0)
278 die_errno(_("failed to read %s"), path.buf);
279 while (data.len && (data.buf[data.len - 1] == '\n' ||
280 data.buf[data.len - 1] == '\r'))
281 data.len--;
282 data.buf[data.len] = '\0';
283 strbuf_reset(&path);
284 if (!is_absolute_path(data.buf))
285 strbuf_addf(&path, "%s/", gitdir);
286 strbuf_addbuf(&path, &data);
33ad9ddd 287 strbuf_add_real_path(sb, path.buf);
31e26ebc 288 ret = 1;
4ac9006f 289 } else {
4dc4e145 290 strbuf_addstr(sb, gitdir);
4ac9006f
BW
291 }
292
4dc4e145
NTND
293 strbuf_release(&data);
294 strbuf_release(&path);
31e26ebc 295 return ret;
4dc4e145 296}
d288a700 297
5f5608bc 298/*
ad1a382f 299 * Test if it looks like we're at a git directory.
5e7bfe25 300 * We want to see:
5f5608bc 301 *
790296fd 302 * - either an objects/ directory _or_ the proper
5f5608bc 303 * GIT_OBJECT_DIRECTORY environment variable
ad1a382f 304 * - a refs/ directory
8098a178 305 * - either a HEAD symlink or a HEAD file that is formatted as
c847f537
JH
306 * a proper "ref:", or a regular file HEAD that has a properly
307 * formatted sha1 object name.
5f5608bc 308 */
b3256eb8 309int is_git_directory(const char *suspect)
5f5608bc 310{
1d186b6f
NTND
311 struct strbuf path = STRBUF_INIT;
312 int ret = 0;
313 size_t len;
ad1a382f 314
4dc4e145 315 /* Check worktree-related signatures */
fa4d8c78
JK
316 strbuf_addstr(&path, suspect);
317 strbuf_complete(&path, '/');
318 strbuf_addstr(&path, "HEAD");
4dc4e145
NTND
319 if (validate_headref(path.buf))
320 goto done;
321
322 strbuf_reset(&path);
323 get_common_dir(&path, suspect);
1d186b6f 324 len = path.len;
4dc4e145
NTND
325
326 /* Check non-worktree-related signatures */
ad1a382f
SP
327 if (getenv(DB_ENVIRONMENT)) {
328 if (access(getenv(DB_ENVIRONMENT), X_OK))
1d186b6f 329 goto done;
ad1a382f
SP
330 }
331 else {
4dc4e145 332 strbuf_setlen(&path, len);
1d186b6f
NTND
333 strbuf_addstr(&path, "/objects");
334 if (access(path.buf, X_OK))
335 goto done;
ad1a382f
SP
336 }
337
1d186b6f
NTND
338 strbuf_setlen(&path, len);
339 strbuf_addstr(&path, "/refs");
340 if (access(path.buf, X_OK))
341 goto done;
ad1a382f 342
1d186b6f
NTND
343 ret = 1;
344done:
345 strbuf_release(&path);
346 return ret;
5f5608bc
LT
347}
348
ffd036b1
JK
349int is_nonbare_repository_dir(struct strbuf *path)
350{
351 int ret = 0;
352 int gitfile_error;
353 size_t orig_path_len = path->len;
354 assert(orig_path_len != 0);
355 strbuf_complete(path, '/');
356 strbuf_addstr(path, ".git");
357 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
358 ret = 1;
359 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
360 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
361 ret = 1;
362 strbuf_setlen(path, orig_path_len);
363 return ret;
364}
365
68025633
JS
366int is_inside_git_dir(void)
367{
e90fdc39
JS
368 if (inside_git_dir < 0)
369 inside_git_dir = is_inside_dir(get_git_dir());
370 return inside_git_dir;
892c41b9
ML
371}
372
892c41b9
ML
373int is_inside_work_tree(void)
374{
e90fdc39
JS
375 if (inside_work_tree < 0)
376 inside_work_tree = is_inside_dir(get_git_work_tree());
377 return inside_work_tree;
892c41b9
ML
378}
379
f3fa1838
JH
380void setup_work_tree(void)
381{
8500e0de 382 const char *work_tree;
354e6534
JS
383 static int initialized = 0;
384
385 if (initialized)
386 return;
fada7674
JK
387
388 if (work_tree_config_is_bogus)
fc045fe7 389 die(_("unable to set up work tree using invalid config"));
fada7674 390
354e6534 391 work_tree = get_git_work_tree();
8500e0de 392 if (!work_tree || chdir_notify(work_tree))
fc045fe7 393 die(_("this operation must be run in a work tree"));
0ed74813
NTND
394
395 /*
396 * Make sure subsequent git processes find correct worktree
397 * if $GIT_WORK_TREE is set relative
398 */
399 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
400 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
401
354e6534 402 initialized = 1;
59f0f2f3
MH
403}
404
58b284a2
NTND
405static int read_worktree_config(const char *var, const char *value, void *vdata)
406{
407 struct repository_format *data = vdata;
408
409 if (strcmp(var, "core.bare") == 0) {
410 data->is_bare = git_config_bool(var, value);
411 } else if (strcmp(var, "core.worktree") == 0) {
412 if (!value)
413 return config_error_nonbool(var);
13019979 414 free(data->work_tree);
58b284a2
NTND
415 data->work_tree = xstrdup(value);
416 }
417 return 0;
418}
419
2cc7c2c7 420static int check_repo_format(const char *var, const char *value, void *vdata)
31e26ebc 421{
2cc7c2c7 422 struct repository_format *data = vdata;
00a09d57
JK
423 const char *ext;
424
31e26ebc 425 if (strcmp(var, "core.repositoryformatversion") == 0)
2cc7c2c7 426 data->version = git_config_int(var, value);
00a09d57
JK
427 else if (skip_prefix(var, "extensions.", &ext)) {
428 /*
429 * record any known extensions here; otherwise,
430 * we fall through to recording it as unknown, and
431 * check_repository_format will complain
432 */
433 if (!strcmp(ext, "noop"))
434 ;
067fbd41 435 else if (!strcmp(ext, "preciousobjects"))
2cc7c2c7 436 data->precious_objects = git_config_bool(var, value);
75b97fec
JT
437 else if (!strcmp(ext, "partialclone")) {
438 if (!value)
439 return config_error_nonbool(var);
440 data->partial_clone = xstrdup(value);
58b284a2
NTND
441 } else if (!strcmp(ext, "worktreeconfig"))
442 data->worktree_config = git_config_bool(var, value);
443 else
2cc7c2c7 444 string_list_append(&data->unknown_extensions, ext);
00a09d57 445 }
58b284a2
NTND
446
447 return read_worktree_config(var, value, vdata);
31e26ebc
NTND
448}
449
abade65b 450static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
9459aa77 451{
7d0fb0da 452 struct strbuf sb = STRBUF_INIT;
2cc7c2c7 453 struct strbuf err = STRBUF_INIT;
652f18ee 454 int has_common;
00a09d57 455
652f18ee 456 has_common = get_common_dir(&sb, gitdir);
e61a509a 457 strbuf_addstr(&sb, "/config");
abade65b 458 read_repository_format(candidate, sb.buf);
2cc7c2c7 459 strbuf_release(&sb);
e61a509a 460
337e51ce 461 /*
2cc7c2c7
JK
462 * For historical use of check_repository_format() in git-init,
463 * we treat a missing config as a silent "ok", even when nongit_ok
464 * is unset.
337e51ce 465 */
abade65b 466 if (candidate->version < 0)
2cc7c2c7
JK
467 return 0;
468
abade65b 469 if (verify_repository_format(candidate, &err) < 0) {
2cc7c2c7
JK
470 if (nongit_ok) {
471 warning("%s", err.buf);
472 strbuf_release(&err);
473 *nongit_ok = -1;
474 return -1;
475 }
476 die("%s", err.buf);
477 }
478
abade65b 479 repository_format_precious_objects = candidate->precious_objects;
e8805af1 480 repository_format_partial_clone = xstrdup_or_null(candidate->partial_clone);
58b284a2 481 repository_format_worktree_config = candidate->worktree_config;
abade65b 482 string_list_clear(&candidate->unknown_extensions, 0);
58b284a2
NTND
483
484 if (repository_format_worktree_config) {
485 /*
486 * pick up core.bare and core.worktree from per-worktree
487 * config if present
488 */
489 strbuf_addf(&sb, "%s/config.worktree", gitdir);
490 git_config_from_file(read_worktree_config, sb.buf, candidate);
491 strbuf_release(&sb);
492 has_common = 0;
493 }
494
652f18ee 495 if (!has_common) {
abade65b 496 if (candidate->is_bare != -1) {
497 is_bare_repository_cfg = candidate->is_bare;
652f18ee
JK
498 if (is_bare_repository_cfg == 1)
499 inside_work_tree = -1;
500 }
abade65b 501 if (candidate->work_tree) {
652f18ee 502 free(git_work_tree_cfg);
e8805af1 503 git_work_tree_cfg = xstrdup(candidate->work_tree);
2cc7c2c7 504 inside_work_tree = -1;
652f18ee 505 }
2cc7c2c7
JK
506 }
507
508 return 0;
509}
510
e8805af1
511static void init_repository_format(struct repository_format *format)
512{
513 const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
514
515 memcpy(format, &fresh, sizeof(fresh));
516}
517
652f18ee 518int read_repository_format(struct repository_format *format, const char *path)
2cc7c2c7 519{
e8805af1 520 clear_repository_format(format);
652f18ee 521 git_config_from_file(check_repo_format, path, format);
e8805af1
522 if (format->version == -1)
523 clear_repository_format(format);
2cc7c2c7
JK
524 return format->version;
525}
526
e8805af1
527void clear_repository_format(struct repository_format *format)
528{
529 string_list_clear(&format->unknown_extensions, 0);
530 free(format->work_tree);
531 free(format->partial_clone);
532 init_repository_format(format);
533}
534
2cc7c2c7
JK
535int verify_repository_format(const struct repository_format *format,
536 struct strbuf *err)
537{
538 if (GIT_REPO_VERSION_READ < format->version) {
274db840 539 strbuf_addf(err, _("Expected git repo version <= %d, found %d"),
2cc7c2c7
JK
540 GIT_REPO_VERSION_READ, format->version);
541 return -1;
542 }
543
544 if (format->version >= 1 && format->unknown_extensions.nr) {
00a09d57
JK
545 int i;
546
274db840 547 strbuf_addstr(err, _("unknown repository extensions found:"));
00a09d57 548
2cc7c2c7
JK
549 for (i = 0; i < format->unknown_extensions.nr; i++)
550 strbuf_addf(err, "\n\t%s",
551 format->unknown_extensions.items[i].string);
552 return -1;
00a09d57
JK
553 }
554
2cc7c2c7 555 return 0;
9459aa77
NTND
556}
557
5f29433f
SB
558void read_gitfile_error_die(int error_code, const char *path, const char *dir)
559{
560 switch (error_code) {
561 case READ_GITFILE_ERR_STAT_FAILED:
562 case READ_GITFILE_ERR_NOT_A_FILE:
563 /* non-fatal; follow return path */
564 break;
565 case READ_GITFILE_ERR_OPEN_FAILED:
fc045fe7 566 die_errno(_("error opening '%s'"), path);
5f29433f 567 case READ_GITFILE_ERR_TOO_LARGE:
fc045fe7 568 die(_("too large to be a .git file: '%s'"), path);
5f29433f 569 case READ_GITFILE_ERR_READ_FAILED:
fc045fe7 570 die(_("error reading %s"), path);
5f29433f 571 case READ_GITFILE_ERR_INVALID_FORMAT:
fc045fe7 572 die(_("invalid gitfile format: %s"), path);
5f29433f 573 case READ_GITFILE_ERR_NO_PATH:
fc045fe7 574 die(_("no path in gitfile: %s"), path);
5f29433f 575 case READ_GITFILE_ERR_NOT_A_REPO:
fc045fe7 576 die(_("not a git repository: %s"), dir);
5f29433f 577 default:
033abf97 578 BUG("unknown error code");
5f29433f
SB
579 }
580}
581
b44ebb19
LH
582/*
583 * Try to read the location of the git directory from the .git file,
ea1d8756
HWN
584 * return path to git directory if found. The return value comes from
585 * a shared buffer.
a93bedad
EE
586 *
587 * On failure, if return_error_code is not NULL, return_error_code
588 * will be set to an error code and NULL will be returned. If
589 * return_error_code is NULL the function will die instead (for most
590 * cases).
b44ebb19 591 */
a93bedad 592const char *read_gitfile_gently(const char *path, int *return_error_code)
b44ebb19 593{
921bdd96 594 const int max_file_size = 1 << 20; /* 1MB */
a93bedad
EE
595 int error_code = 0;
596 char *buf = NULL;
597 char *dir = NULL;
40c813e0 598 const char *slash;
b44ebb19
LH
599 struct stat st;
600 int fd;
b1905aea 601 ssize_t len;
b44ebb19 602
a93bedad 603 if (stat(path, &st)) {
5c4003ca 604 /* NEEDSWORK: discern between ENOENT vs other errors */
a93bedad
EE
605 error_code = READ_GITFILE_ERR_STAT_FAILED;
606 goto cleanup_return;
607 }
608 if (!S_ISREG(st.st_mode)) {
609 error_code = READ_GITFILE_ERR_NOT_A_FILE;
610 goto cleanup_return;
611 }
921bdd96
EE
612 if (st.st_size > max_file_size) {
613 error_code = READ_GITFILE_ERR_TOO_LARGE;
614 goto cleanup_return;
615 }
b44ebb19 616 fd = open(path, O_RDONLY);
a93bedad
EE
617 if (fd < 0) {
618 error_code = READ_GITFILE_ERR_OPEN_FAILED;
619 goto cleanup_return;
620 }
3733e694 621 buf = xmallocz(st.st_size);
b44ebb19
LH
622 len = read_in_full(fd, buf, st.st_size);
623 close(fd);
a93bedad
EE
624 if (len != st.st_size) {
625 error_code = READ_GITFILE_ERR_READ_FAILED;
626 goto cleanup_return;
627 }
a93bedad
EE
628 if (!starts_with(buf, "gitdir: ")) {
629 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
630 goto cleanup_return;
631 }
b44ebb19
LH
632 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
633 len--;
a93bedad
EE
634 if (len < 9) {
635 error_code = READ_GITFILE_ERR_NO_PATH;
636 goto cleanup_return;
637 }
b44ebb19 638 buf[len] = '\0';
40c813e0
BK
639 dir = buf + 8;
640
641 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
642 size_t pathlen = slash+1 - path;
75faa45a
JK
643 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
644 (int)(len - 8), buf + 8);
40c813e0
BK
645 free(buf);
646 buf = dir;
647 }
a93bedad
EE
648 if (!is_git_directory(dir)) {
649 error_code = READ_GITFILE_ERR_NOT_A_REPO;
650 goto cleanup_return;
651 }
e2a57aac 652 path = real_path(dir);
40c813e0 653
a93bedad 654cleanup_return:
a93bedad
EE
655 if (return_error_code)
656 *return_error_code = error_code;
5f29433f
SB
657 else if (error_code)
658 read_gitfile_error_die(error_code, path, dir);
a93bedad 659
b44ebb19 660 free(buf);
38ae8784 661 return error_code ? NULL : path;
b44ebb19
LH
662}
663
e4e30347 664static const char *setup_explicit_git_dir(const char *gitdirenv,
7333ed17 665 struct strbuf *cwd,
abade65b 666 struct repository_format *repo_fmt,
b3f66fd3 667 int *nongit_ok)
e4e30347 668{
b3f66fd3
NTND
669 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
670 const char *worktree;
671 char *gitfile;
9b125da4 672 int offset;
e4e30347
JN
673
674 if (PATH_MAX - 40 < strlen(gitdirenv))
fc045fe7 675 die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
b3f66fd3 676
13d6ec91 677 gitfile = (char*)read_gitfile(gitdirenv);
b3f66fd3
NTND
678 if (gitfile) {
679 gitfile = xstrdup(gitfile);
680 gitdirenv = gitfile;
681 }
682
e4e30347
JN
683 if (!is_git_directory(gitdirenv)) {
684 if (nongit_ok) {
685 *nongit_ok = 1;
b3f66fd3 686 free(gitfile);
e4e30347
JN
687 return NULL;
688 }
fc045fe7 689 die(_("not a git repository: '%s'"), gitdirenv);
e4e30347 690 }
b3f66fd3 691
abade65b 692 if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
b3f66fd3
NTND
693 free(gitfile);
694 return NULL;
e4e30347 695 }
b3f66fd3
NTND
696
697 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
698 if (work_tree_env)
699 set_git_work_tree(work_tree_env);
700 else if (is_bare_repository_cfg > 0) {
fada7674
JK
701 if (git_work_tree_cfg) {
702 /* #22.2, #30 */
703 warning("core.bare and core.worktree do not make sense");
704 work_tree_config_is_bogus = 1;
705 }
b3f66fd3
NTND
706
707 /* #18, #26 */
708 set_git_dir(gitdirenv);
709 free(gitfile);
e4e30347 710 return NULL;
b3f66fd3
NTND
711 }
712 else if (git_work_tree_cfg) { /* #6, #14 */
713 if (is_absolute_path(git_work_tree_cfg))
714 set_git_work_tree(git_work_tree_cfg);
715 else {
56b9f6e7 716 char *core_worktree;
b3f66fd3 717 if (chdir(gitdirenv))
fc045fe7 718 die_errno(_("cannot chdir to '%s'"), gitdirenv);
b3f66fd3 719 if (chdir(git_work_tree_cfg))
fc045fe7 720 die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
56b9f6e7 721 core_worktree = xgetcwd();
7333ed17 722 if (chdir(cwd->buf))
fc045fe7 723 die_errno(_("cannot come back to cwd"));
b3f66fd3 724 set_git_work_tree(core_worktree);
56b9f6e7 725 free(core_worktree);
b3f66fd3
NTND
726 }
727 }
2cd83d10
JK
728 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
729 /* #16d */
730 set_git_dir(gitdirenv);
731 free(gitfile);
732 return NULL;
733 }
b3f66fd3
NTND
734 else /* #2, #10 */
735 set_git_work_tree(".");
736
737 /* set_git_work_tree() must have been called by now */
738 worktree = get_git_work_tree();
739
740 /* both get_git_work_tree() and cwd are already normalized */
7333ed17 741 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
b3f66fd3
NTND
742 set_git_dir(gitdirenv);
743 free(gitfile);
e4e30347 744 return NULL;
b3f66fd3 745 }
e4e30347 746
7333ed17 747 offset = dir_inside_of(cwd->buf, worktree);
9b125da4 748 if (offset >= 0) { /* cwd inside worktree? */
e2a57aac 749 set_git_dir(real_path(gitdirenv));
b3f66fd3 750 if (chdir(worktree))
fc045fe7 751 die_errno(_("cannot chdir to '%s'"), worktree);
7333ed17 752 strbuf_addch(cwd, '/');
b3f66fd3 753 free(gitfile);
7333ed17 754 return cwd->buf + offset;
93a00542 755 }
b3f66fd3
NTND
756
757 /* cwd outside worktree */
758 set_git_dir(gitdirenv);
759 free(gitfile);
760 return NULL;
93a00542
JN
761}
762
9951d3b3 763static const char *setup_discovered_git_dir(const char *gitdir,
7333ed17 764 struct strbuf *cwd, int offset,
abade65b 765 struct repository_format *repo_fmt,
9951d3b3 766 int *nongit_ok)
98937bef 767{
abade65b 768 if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
9951d3b3 769 return NULL;
98937bef 770
4868b2ea
JN
771 /* --work-tree is set without --git-dir; use discovered one */
772 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
2d4dcf21
JS
773 char *to_free = NULL;
774 const char *ret;
775
7333ed17 776 if (offset != cwd->len && !is_absolute_path(gitdir))
2d4dcf21 777 gitdir = to_free = real_pathdup(gitdir, 1);
7333ed17 778 if (chdir(cwd->buf))
fc045fe7 779 die_errno(_("cannot come back to cwd"));
abade65b 780 ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
2d4dcf21
JS
781 free(to_free);
782 return ret;
4868b2ea
JN
783 }
784
9951d3b3
NTND
785 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
786 if (is_bare_repository_cfg > 0) {
7333ed17
RS
787 set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
788 if (chdir(cwd->buf))
fc045fe7 789 die_errno(_("cannot come back to cwd"));
98937bef 790 return NULL;
9951d3b3 791 }
98937bef 792
9951d3b3
NTND
793 /* #0, #1, #5, #8, #9, #12, #13 */
794 set_git_work_tree(".");
795 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
796 set_git_dir(gitdir);
98937bef 797 inside_git_dir = 0;
9951d3b3 798 inside_work_tree = 1;
7333ed17 799 if (offset == cwd->len)
98937bef
NTND
800 return NULL;
801
df380d58
JS
802 /* Make "offset" point past the '/' (already the case for root dirs) */
803 if (offset != offset_1st_component(cwd->buf))
804 offset++;
805 /* Add a '/' at the end */
7333ed17
RS
806 strbuf_addch(cwd, '/');
807 return cwd->buf + offset;
98937bef
NTND
808}
809
1cd8031b 810/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
7333ed17 811static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
abade65b 812 struct repository_format *repo_fmt,
7333ed17 813 int *nongit_ok)
68698da5
JN
814{
815 int root_len;
816
abade65b 817 if (check_repository_format_gently(".", repo_fmt, nongit_ok))
1cd8031b
NTND
818 return NULL;
819
2cd83d10
JK
820 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
821
4868b2ea
JN
822 /* --work-tree is set without --git-dir; use discovered one */
823 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
da6f8475 824 static const char *gitdir;
4868b2ea 825
7333ed17
RS
826 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
827 if (chdir(cwd->buf))
fc045fe7 828 die_errno(_("cannot come back to cwd"));
abade65b 829 return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
4868b2ea
JN
830 }
831
68698da5 832 inside_git_dir = 1;
1cd8031b 833 inside_work_tree = 0;
7333ed17
RS
834 if (offset != cwd->len) {
835 if (chdir(cwd->buf))
fc045fe7 836 die_errno(_("cannot come back to cwd"));
7333ed17
RS
837 root_len = offset_1st_component(cwd->buf);
838 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
839 set_git_dir(cwd->buf);
337e51ce 840 }
1cd8031b 841 else
68698da5 842 set_git_dir(".");
68698da5
JN
843 return NULL;
844}
845
2565b43b 846static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
60c98d1e
JN
847{
848 struct stat buf;
2565b43b 849 if (stat(path, &buf)) {
fc045fe7 850 die_errno(_("failed to stat '%*s%s%s'"),
2565b43b 851 prefix_len,
60c98d1e
JN
852 prefix ? prefix : "",
853 prefix ? "/" : "", path);
2565b43b 854 }
60c98d1e
JN
855 return buf.st_dev;
856}
857
9e2326c7 858/*
1b77d83c
MH
859 * A "string_list_each_func_t" function that canonicalizes an entry
860 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
7ec30aaa
MH
861 * discards it if unusable. The presence of an empty entry in
862 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
863 * subsequent entries.
9e2326c7 864 */
1b77d83c 865static int canonicalize_ceiling_entry(struct string_list_item *item,
7ec30aaa 866 void *cb_data)
9e2326c7 867{
7ec30aaa 868 int *empty_entry_found = cb_data;
1b77d83c 869 char *ceil = item->string;
9e2326c7 870
7ec30aaa
MH
871 if (!*ceil) {
872 *empty_entry_found = 1;
9e2326c7 873 return 0;
7ec30aaa 874 } else if (!is_absolute_path(ceil)) {
9e2326c7 875 return 0;
7ec30aaa
MH
876 } else if (*empty_entry_found) {
877 /* Keep entry but do not canonicalize it */
878 return 1;
879 } else {
ce83eadd 880 char *real_path = real_pathdup(ceil, 0);
4ac9006f 881 if (!real_path) {
7ec30aaa 882 return 0;
4ac9006f 883 }
7ec30aaa 884 free(item->string);
4ac9006f 885 item->string = real_path;
7ec30aaa
MH
886 return 1;
887 }
9e2326c7
MH
888}
889
ce9b8aab
JS
890enum discovery_result {
891 GIT_DIR_NONE = 0,
892 GIT_DIR_EXPLICIT,
893 GIT_DIR_DISCOVERED,
894 GIT_DIR_BARE,
895 /* these are errors */
896 GIT_DIR_HIT_CEILING = -1,
01017dce
JS
897 GIT_DIR_HIT_MOUNT_POINT = -2,
898 GIT_DIR_INVALID_GITFILE = -3
ce9b8aab
JS
899};
900
e90fdc39
JS
901/*
902 * We cannot decide in this function whether we are in the work tree or
903 * not, since the config can only be read _after_ this function was called.
ce9b8aab
JS
904 *
905 * Also, we avoid changing any global state (such as the current working
906 * directory) to allow early callers.
907 *
908 * The directory where the search should start needs to be passed in via the
909 * `dir` parameter; upon return, the `dir` buffer will contain the path of
910 * the directory where the search ended, and `gitdir` will contain the path of
911 * the discovered .git/ directory, if any. If `gitdir` is not absolute, it
912 * is relative to `dir` (i.e. *not* necessarily the cwd).
e90fdc39 913 */
ce9b8aab 914static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
01017dce
JS
915 struct strbuf *gitdir,
916 int die_on_error)
d288a700 917{
0454dd93 918 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
31171d9e 919 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
ce9b8aab
JS
920 const char *gitdirenv;
921 int ceil_offset = -1, min_offset = has_dos_drive_prefix(dir->buf) ? 3 : 1;
c7d1d1b1
RH
922 dev_t current_device = 0;
923 int one_filesystem = 1;
d288a700 924
e90fdc39
JS
925 /*
926 * If GIT_DIR is set explicitly, we're not going
927 * to do any discovery, but we still do repository
928 * validation.
929 */
ad1a382f 930 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
ce9b8aab
JS
931 if (gitdirenv) {
932 strbuf_addstr(gitdir, gitdirenv);
933 return GIT_DIR_EXPLICIT;
934 }
d288a700 935
31171d9e 936 if (env_ceiling_dirs) {
7ec30aaa
MH
937 int empty_entry_found = 0;
938
31171d9e 939 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1b77d83c 940 filter_string_list(&ceiling_dirs, 0,
7ec30aaa 941 canonicalize_ceiling_entry, &empty_entry_found);
ce9b8aab 942 ceil_offset = longest_ancestor_length(dir->buf, &ceiling_dirs);
31171d9e
MH
943 string_list_clear(&ceiling_dirs, 0);
944 }
945
ce9b8aab
JS
946 if (ceil_offset < 0)
947 ceil_offset = min_offset - 2;
d288a700 948
892c41b9 949 /*
ce9b8aab 950 * Test in the following order (relative to the dir):
b44ebb19 951 * - .git (file containing "gitdir: <path>")
e90fdc39
JS
952 * - .git/
953 * - ./ (bare)
b44ebb19 954 * - ../.git
e90fdc39
JS
955 * - ../.git/
956 * - ../ (bare)
176b2d32 957 * - ../../.git
e90fdc39 958 * etc.
892c41b9 959 */
cf87463e 960 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
60c98d1e 961 if (one_filesystem)
ce9b8aab 962 current_device = get_device_or_die(dir->buf, NULL, 0);
e90fdc39 963 for (;;) {
01017dce 964 int offset = dir->len, error_code = 0;
ce9b8aab
JS
965
966 if (offset > min_offset)
967 strbuf_addch(dir, '/');
968 strbuf_addstr(dir, DEFAULT_GIT_DIR_ENVIRONMENT);
01017dce
JS
969 gitdirenv = read_gitfile_gently(dir->buf, die_on_error ?
970 NULL : &error_code);
971 if (!gitdirenv) {
972 if (die_on_error ||
973 error_code == READ_GITFILE_ERR_NOT_A_FILE) {
5c4003ca 974 /* NEEDSWORK: fail if .git is not file nor dir */
01017dce
JS
975 if (is_git_directory(dir->buf))
976 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
977 } else if (error_code != READ_GITFILE_ERR_STAT_FAILED)
978 return GIT_DIR_INVALID_GITFILE;
9951d3b3 979 }
ce9b8aab 980 strbuf_setlen(dir, offset);
9951d3b3 981 if (gitdirenv) {
ce9b8aab
JS
982 strbuf_addstr(gitdir, gitdirenv);
983 return GIT_DIR_DISCOVERED;
9951d3b3 984 }
9951d3b3 985
ce9b8aab
JS
986 if (is_git_directory(dir->buf)) {
987 strbuf_addstr(gitdir, ".");
988 return GIT_DIR_BARE;
502ffe34 989 }
9951d3b3 990
ce9b8aab
JS
991 if (offset <= min_offset)
992 return GIT_DIR_HIT_CEILING;
1cd8031b 993
ce9b8aab 994 while (--offset > ceil_offset && !is_dir_sep(dir->buf[offset]))
6c1e6544 995 ; /* continue */
ce9b8aab
JS
996 if (offset <= ceil_offset)
997 return GIT_DIR_HIT_CEILING;
998
999 strbuf_setlen(dir, offset > min_offset ? offset : min_offset);
1000 if (one_filesystem &&
1001 current_device != get_device_or_die(dir->buf, NULL, offset))
1002 return GIT_DIR_HIT_MOUNT_POINT;
892c41b9 1003 }
d288a700 1004}
5e7bfe25 1005
d3fb71b3
BW
1006int discover_git_directory(struct strbuf *commondir,
1007 struct strbuf *gitdir)
16ac8b8d
JS
1008{
1009 struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
1010 size_t gitdir_offset = gitdir->len, cwd_len;
d3fb71b3 1011 size_t commondir_offset = commondir->len;
e8805af1 1012 struct repository_format candidate = REPOSITORY_FORMAT_INIT;
16ac8b8d
JS
1013
1014 if (strbuf_getcwd(&dir))
d3fb71b3 1015 return -1;
16ac8b8d
JS
1016
1017 cwd_len = dir.len;
01017dce 1018 if (setup_git_directory_gently_1(&dir, gitdir, 0) <= 0) {
16ac8b8d 1019 strbuf_release(&dir);
d3fb71b3 1020 return -1;
16ac8b8d
JS
1021 }
1022
1023 /*
1024 * The returned gitdir is relative to dir, and if dir does not reflect
1025 * the current working directory, we simply make the gitdir absolute.
1026 */
1027 if (dir.len < cwd_len && !is_absolute_path(gitdir->buf + gitdir_offset)) {
1028 /* Avoid a trailing "/." */
1029 if (!strcmp(".", gitdir->buf + gitdir_offset))
1030 strbuf_setlen(gitdir, gitdir_offset);
1031 else
1032 strbuf_addch(&dir, '/');
1033 strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
1034 }
1035
d3fb71b3
BW
1036 get_common_dir(commondir, gitdir->buf + gitdir_offset);
1037
16ac8b8d 1038 strbuf_reset(&dir);
d3fb71b3 1039 strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
16ac8b8d
JS
1040 read_repository_format(&candidate, dir.buf);
1041 strbuf_release(&dir);
1042
1043 if (verify_repository_format(&candidate, &err) < 0) {
1044 warning("ignoring git dir '%s': %s",
1045 gitdir->buf + gitdir_offset, err.buf);
1046 strbuf_release(&err);
d3fb71b3 1047 strbuf_setlen(commondir, commondir_offset);
69743f9b 1048 strbuf_setlen(gitdir, gitdir_offset);
e8805af1 1049 clear_repository_format(&candidate);
d3fb71b3 1050 return -1;
16ac8b8d
JS
1051 }
1052
e8805af1 1053 clear_repository_format(&candidate);
d3fb71b3 1054 return 0;
16ac8b8d
JS
1055}
1056
a60645f9
NTND
1057const char *setup_git_directory_gently(int *nongit_ok)
1058{
ce9b8aab
JS
1059 static struct strbuf cwd = STRBUF_INIT;
1060 struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;
07098b81 1061 const char *prefix = NULL;
e8805af1 1062 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
a60645f9 1063
ce9b8aab
JS
1064 /*
1065 * We may have read an incomplete configuration before
1066 * setting-up the git directory. If so, clear the cache so
1067 * that the next queries to the configuration reload complete
1068 * configuration (including the per-repo config file that we
1069 * ignored previously).
1070 */
1071 git_config_clear();
1072
1073 /*
1074 * Let's assume that we are in a git repository.
1075 * If it turns out later that we are somewhere else, the value will be
1076 * updated accordingly.
1077 */
1078 if (nongit_ok)
1079 *nongit_ok = 0;
1080
1081 if (strbuf_getcwd(&cwd))
1082 die_errno(_("Unable to read current working directory"));
1083 strbuf_addbuf(&dir, &cwd);
1084
01017dce 1085 switch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {
ce9b8aab 1086 case GIT_DIR_EXPLICIT:
abade65b 1087 prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
ce9b8aab
JS
1088 break;
1089 case GIT_DIR_DISCOVERED:
1090 if (dir.len < cwd.len && chdir(dir.buf))
fc045fe7 1091 die(_("cannot change to '%s'"), dir.buf);
ce9b8aab 1092 prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
abade65b 1093 &repo_fmt, nongit_ok);
ce9b8aab
JS
1094 break;
1095 case GIT_DIR_BARE:
1096 if (dir.len < cwd.len && chdir(dir.buf))
fc045fe7 1097 die(_("cannot change to '%s'"), dir.buf);
abade65b 1098 prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
ce9b8aab
JS
1099 break;
1100 case GIT_DIR_HIT_CEILING:
07098b81
ED
1101 if (!nongit_ok)
1102 die(_("not a git repository (or any of the parent directories): %s"),
1103 DEFAULT_GIT_DIR_ENVIRONMENT);
1104 *nongit_ok = 1;
ce9b8aab
JS
1105 break;
1106 case GIT_DIR_HIT_MOUNT_POINT:
07098b81
ED
1107 if (!nongit_ok)
1108 die(_("not a git repository (or any parent up to mount point %s)\n"
1109 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
1110 dir.buf);
1111 *nongit_ok = 1;
1112 break;
1113 case GIT_DIR_NONE:
1114 /*
1115 * As a safeguard against setup_git_directory_gently_1 returning
1116 * this value, fallthrough to BUG. Otherwise it is possible to
1117 * set startup_info->have_repository to 1 when we did nothing to
1118 * find a repository.
1119 */
ce9b8aab 1120 default:
033abf97 1121 BUG("unhandled setup_git_directory_1() result");
ce9b8aab
JS
1122 }
1123
07098b81
ED
1124 /*
1125 * At this point, nongit_ok is stable. If it is non-NULL and points
1126 * to a non-zero value, then this means that we haven't found a
1127 * repository and that the caller expects startup_info to reflect
1128 * this.
1129 *
1130 * Regardless of the state of nongit_ok, startup_info->prefix and
1131 * the GIT_PREFIX environment variable must always match. For details
1132 * see Documentation/config/alias.txt.
1133 */
1134 if (nongit_ok && *nongit_ok) {
1135 startup_info->have_repository = 0;
1136 startup_info->prefix = NULL;
a6f7f9a3 1137 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
07098b81
ED
1138 } else {
1139 startup_info->have_repository = 1;
1140 startup_info->prefix = prefix;
1141 if (prefix)
1142 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1143 else
1144 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1145 }
46c3cd44 1146
73f192c9
BW
1147 /*
1148 * Not all paths through the setup code will call 'set_git_dir()' (which
1149 * directly sets up the environment) so in order to guarantee that the
1150 * environment is in a consistent state after setup, explicitly setup
1151 * the environment if we have a repository.
1152 *
1153 * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
1154 * code paths so we also need to explicitly setup the environment if
1155 * the user has set GIT_DIR. It may be beneficial to disallow bogus
1156 * GIT_DIR values at some point in the future.
1157 */
07098b81
ED
1158 if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
1159 startup_info->have_repository ||
1160 /* GIT_DIR_EXPLICIT */
1161 getenv(GIT_DIR_ENVIRONMENT)) {
c14c234f
BW
1162 if (!the_repository->gitdir) {
1163 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
1164 if (!gitdir)
1165 gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
357a03eb 1166 setup_git_env(gitdir);
c14c234f 1167 }
78a67668 1168 if (startup_info->have_repository)
1169 repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
c14c234f 1170 }
73f192c9 1171
ce9b8aab
JS
1172 strbuf_release(&dir);
1173 strbuf_release(&gitdir);
e8805af1 1174 clear_repository_format(&repo_fmt);
ce9b8aab 1175
a60645f9
NTND
1176 return prefix;
1177}
1178
94df2506
JH
1179int git_config_perm(const char *var, const char *value)
1180{
06cbe855
HO
1181 int i;
1182 char *endptr;
1183
1184 if (value == NULL)
1185 return PERM_GROUP;
1186
1187 if (!strcmp(value, "umask"))
1188 return PERM_UMASK;
1189 if (!strcmp(value, "group"))
1190 return PERM_GROUP;
1191 if (!strcmp(value, "all") ||
1192 !strcmp(value, "world") ||
1193 !strcmp(value, "everybody"))
1194 return PERM_EVERYBODY;
1195
1196 /* Parse octal numbers */
1197 i = strtol(value, &endptr, 8);
1198
1199 /* If not an octal number, maybe true/false? */
1200 if (*endptr != 0)
1201 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
1202
1203 /*
1204 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
5a688fe4 1205 * a chmod value to restrict to.
06cbe855
HO
1206 */
1207 switch (i) {
1208 case PERM_UMASK: /* 0 */
1209 return PERM_UMASK;
1210 case OLD_PERM_GROUP: /* 1 */
1211 return PERM_GROUP;
1212 case OLD_PERM_EVERYBODY: /* 2 */
1213 return PERM_EVERYBODY;
94df2506 1214 }
06cbe855
HO
1215
1216 /* A filemode value was given: 0xxx */
1217
1218 if ((i & 0600) != 0600)
fc045fe7 1219 die(_("problem with core.sharedRepository filemode value "
06cbe855 1220 "(0%.3o).\nThe owner of files must always have "
2ff30e67 1221 "read and write permissions."), i);
06cbe855
HO
1222
1223 /*
1224 * Mask filemode value. Others can not get write permission.
1225 * x flags for directories are handled separately.
1226 */
5a688fe4 1227 return -(i & 0666);
94df2506
JH
1228}
1229
4b0d1eeb 1230void check_repository_format(void)
ab9cb76f 1231{
e8805af1 1232 struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
abade65b 1233 check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);
f1c126bd 1234 startup_info->have_repository = 1;
e8805af1 1235 clear_repository_format(&repo_fmt);
ab9cb76f
JH
1236}
1237
e1e5ec86
CB
1238/*
1239 * Returns the "prefix", a path to the current working directory
1240 * relative to the work tree root, or NULL, if the current working
1241 * directory is not a strict subdirectory of the work tree root. The
1242 * prefix always ends with a '/' character.
1243 */
5e7bfe25
JH
1244const char *setup_git_directory(void)
1245{
b3f66fd3 1246 return setup_git_directory_gently(NULL);
5e7bfe25 1247}
abc06822 1248
40d96325 1249const char *resolve_gitdir_gently(const char *suspect, int *return_error_code)
abc06822
FG
1250{
1251 if (is_git_directory(suspect))
1252 return suspect;
40d96325 1253 return read_gitfile_gently(suspect, return_error_code);
abc06822 1254}
1d999ddd
TR
1255
1256/* if any standard file descriptor is missing open it to /dev/null */
1257void sanitize_stdfds(void)
1258{
1259 int fd = open("/dev/null", O_RDWR, 0);
1260 while (fd != -1 && fd < 2)
1261 fd = dup(fd);
1262 if (fd == -1)
fc045fe7 1263 die_errno(_("open /dev/null or dup failed"));
1d999ddd
TR
1264 if (fd > 2)
1265 close(fd);
1266}
de0957ce
NTND
1267
1268int daemonize(void)
1269{
1270#ifdef NO_POSIX_GOODIES
1271 errno = ENOSYS;
1272 return -1;
1273#else
1274 switch (fork()) {
1275 case 0:
1276 break;
1277 case -1:
fc045fe7 1278 die_errno(_("fork failed"));
de0957ce
NTND
1279 default:
1280 exit(0);
1281 }
1282 if (setsid() == -1)
fc045fe7 1283 die_errno(_("setsid failed"));
de0957ce
NTND
1284 close(0);
1285 close(1);
1286 close(2);
1287 sanitize_stdfds();
1288 return 0;
1289#endif
1290}