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