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