]> git.ipfire.org Git - thirdparty/git.git/blame - setup.c
config: drop git_config_early
[thirdparty/git.git] / setup.c
CommitLineData
d288a700 1#include "cache.h"
e90fdc39 2#include "dir.h"
31171d9e 3#include "string-list.h"
e90fdc39
JS
4
5static int inside_git_dir = -1;
6static int inside_work_tree = -1;
fada7674 7static int work_tree_config_is_bogus;
00a09d57 8static struct string_list unknown_extensions = STRING_LIST_INIT_DUP;
d288a700 9
ddc2a628
MEW
10/*
11 * The input parameter must contain an absolute path, and it must already be
12 * normalized.
13 *
14 * Find the part of an absolute path that lies inside the work tree by
15 * dereferencing symlinks outside the work tree, for example:
16 * /dir1/repo/dir2/file (work tree is /dir1/repo) -> dir2/file
17 * /dir/file (work tree is /) -> dir/file
18 * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
19 * /dir/repolink/file (repolink points to /dir/repo) -> file
20 * /dir/repo (exactly equal to work tree) -> (empty string)
21 */
22static int abspath_part_inside_repo(char *path)
23{
24 size_t len;
25 size_t wtlen;
26 char *path0;
27 int off;
28 const char *work_tree = get_git_work_tree();
29
30 if (!work_tree)
31 return -1;
32 wtlen = strlen(work_tree);
33 len = strlen(path);
6127ff63 34 off = offset_1st_component(path);
ddc2a628
MEW
35
36 /* check if work tree is already the prefix */
37 if (wtlen <= len && !strncmp(path, work_tree, wtlen)) {
38 if (path[wtlen] == '/') {
39 memmove(path, path + wtlen + 1, len - wtlen);
40 return 0;
41 } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
42 /* work tree is the root, or the whole path */
43 memmove(path, path + wtlen, len - wtlen + 1);
44 return 0;
45 }
46 /* work tree might match beginning of a symlink to work tree */
47 off = wtlen;
48 }
49 path0 = path;
6127ff63 50 path += off;
ddc2a628
MEW
51
52 /* check each '/'-terminated level */
53 while (*path) {
54 path++;
55 if (*path == '/') {
56 *path = '\0';
57 if (strcmp(real_path(path0), work_tree) == 0) {
58 memmove(path0, path + 1, len - (path - path0));
59 return 0;
60 }
61 *path = '/';
62 }
63 }
64
65 /* check whole path */
66 if (strcmp(real_path(path0), work_tree) == 0) {
67 *path0 = '\0';
68 return 0;
69 }
70
71 return -1;
72}
73
645a29c4
NTND
74/*
75 * Normalize "path", prepending the "prefix" for relative paths. If
76 * remaining_prefix is not NULL, return the actual prefix still
77 * remains in the path. For example, prefix = sub1/sub2/ and path is
78 *
79 * foo -> sub1/sub2/foo (full prefix)
80 * ../foo -> sub1/foo (remaining prefix is sub1/)
81 * ../../bar -> bar (no remaining prefix)
82 * ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
83 * `pwd`/../bar -> sub1/bar (no remaining prefix)
84 */
85char *prefix_path_gently(const char *prefix, int len,
86 int *remaining_prefix, const char *path)
d089ebaa
JH
87{
88 const char *orig = path;
18e051a3
CMAB
89 char *sanitized;
90 if (is_absolute_path(orig)) {
3733e694 91 sanitized = xmallocz(strlen(path));
645a29c4
NTND
92 if (remaining_prefix)
93 *remaining_prefix = 0;
655ee9ea
MEW
94 if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
95 free(sanitized);
96 return NULL;
97 }
98 if (abspath_part_inside_repo(sanitized)) {
99 free(sanitized);
100 return NULL;
101 }
18e051a3 102 } else {
75faa45a 103 sanitized = xstrfmt("%.*s%s", len, prefix, path);
645a29c4
NTND
104 if (remaining_prefix)
105 *remaining_prefix = len;
655ee9ea 106 if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
546e0fd9
JK
107 free(sanitized);
108 return NULL;
d089ebaa 109 }
d089ebaa
JH
110 }
111 return sanitized;
f332726e
LT
112}
113
546e0fd9
JK
114char *prefix_path(const char *prefix, int len, const char *path)
115{
645a29c4 116 char *r = prefix_path_gently(prefix, len, NULL, path);
546e0fd9
JK
117 if (!r)
118 die("'%s' is outside repository", path);
119 return r;
120}
121
122int path_inside_repo(const char *prefix, const char *path)
123{
124 int len = prefix ? strlen(prefix) : 0;
645a29c4 125 char *r = prefix_path_gently(prefix, len, NULL, path);
546e0fd9
JK
126 if (r) {
127 free(r);
128 return 1;
129 }
130 return 0;
131}
132
c6e8c800
JH
133int check_filename(const char *prefix, const char *arg)
134{
135 const char *name;
136 struct stat st;
137
59556548 138 if (starts_with(arg, ":/")) {
4db86e8b
NTND
139 if (arg[2] == '\0') /* ":/" is root dir, always exists */
140 return 1;
141 name = arg + 2;
df714f81 142 } else if (prefix)
4db86e8b
NTND
143 name = prefix_filename(prefix, strlen(prefix), arg);
144 else
145 name = arg;
c6e8c800
JH
146 if (!lstat(name, &st))
147 return 1; /* file exists */
148 if (errno == ENOENT || errno == ENOTDIR)
149 return 0; /* file does not exist */
150 die_errno("failed to stat '%s'", arg);
151}
152
023e37c3
MM
153static void NORETURN die_verify_filename(const char *prefix,
154 const char *arg,
155 int diagnose_misspelt_rev)
009fee47 156{
023e37c3
MM
157 if (!diagnose_misspelt_rev)
158 die("%s: no such path in the working tree.\n"
4d4b5739 159 "Use 'git <command> -- <path>...' to specify paths that do not exist locally.",
023e37c3 160 arg);
0e539dca
JH
161 /*
162 * Saying "'(icase)foo' does not exist in the index" when the
163 * user gave us ":(icase)foo" is just stupid. A magic pathspec
164 * begins with a colon and is followed by a non-alnum; do not
8c135ea2 165 * let maybe_die_on_misspelt_object_name() even trigger.
0e539dca
JH
166 */
167 if (!(arg[0] == ':' && !isalnum(arg[1])))
8c135ea2 168 maybe_die_on_misspelt_object_name(arg, prefix);
0e539dca 169
009fee47
MM
170 /* ... or fall back the most general message. */
171 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
4d4b5739
MM
172 "Use '--' to separate paths from revisions, like this:\n"
173 "'git <command> [<revision>...] -- [<file>...]'", arg);
009fee47
MM
174
175}
176
e23d0b4a
LT
177/*
178 * Verify a filename that we got as an argument for a pathspec
179 * entry. Note that a filename that begins with "-" never verifies
180 * as true, because even if such a filename were to exist, we want
181 * it to be preceded by the "--" marker (or we want the user to
182 * use a format like "./-filename")
023e37c3
MM
183 *
184 * The "diagnose_misspelt_rev" is used to provide a user-friendly
185 * diagnosis when dying upon finding that "name" is not a pathname.
186 * If set to 1, the diagnosis will try to diagnose "name" as an
187 * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
188 * will only complain about an inexisting file.
189 *
190 * This function is typically called to check that a "file or rev"
191 * argument is unambiguous. In this case, the caller will want
192 * diagnose_misspelt_rev == 1 when verifying the first non-rev
193 * argument (which could have been a revision), and
194 * diagnose_misspelt_rev == 0 for the next ones (because we already
195 * saw a filename, there's not ambiguity anymore).
e23d0b4a 196 */
023e37c3
MM
197void verify_filename(const char *prefix,
198 const char *arg,
199 int diagnose_misspelt_rev)
e23d0b4a 200{
e23d0b4a
LT
201 if (*arg == '-')
202 die("bad flag '%s' used after filename", arg);
df714f81 203 if (check_filename(prefix, arg) || !no_wildcard(arg))
e23d0b4a 204 return;
023e37c3 205 die_verify_filename(prefix, arg, diagnose_misspelt_rev);
e23d0b4a
LT
206}
207
ea92f41f
JH
208/*
209 * Opposite of the above: the command line did not have -- marker
210 * and we parsed the arg as a refname. It should not be interpretable
211 * as a filename.
212 */
213void verify_non_filename(const char *prefix, const char *arg)
214{
7ae3df8c 215 if (!is_inside_work_tree() || is_inside_git_dir())
68025633 216 return;
ea92f41f
JH
217 if (*arg == '-')
218 return; /* flag */
c6e8c800
JH
219 if (!check_filename(prefix, arg))
220 return;
221 die("ambiguous argument '%s': both revision and filename\n"
4d4b5739
MM
222 "Use '--' to separate paths from revisions, like this:\n"
223 "'git <command> [<revision>...] -- [<file>...]'", arg);
ea92f41f
JH
224}
225
31e26ebc 226int get_common_dir(struct strbuf *sb, const char *gitdir)
11f9dd71
MK
227{
228 const char *git_env_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
229 if (git_env_common_dir) {
230 strbuf_addstr(sb, git_env_common_dir);
231 return 1;
232 } else {
233 return get_common_dir_noenv(sb, gitdir);
234 }
235}
236
237int get_common_dir_noenv(struct strbuf *sb, const char *gitdir)
4dc4e145
NTND
238{
239 struct strbuf data = STRBUF_INIT;
240 struct strbuf path = STRBUF_INIT;
31e26ebc 241 int ret = 0;
11f9dd71 242
4dc4e145
NTND
243 strbuf_addf(&path, "%s/commondir", gitdir);
244 if (file_exists(path.buf)) {
245 if (strbuf_read_file(&data, path.buf, 0) <= 0)
246 die_errno(_("failed to read %s"), path.buf);
247 while (data.len && (data.buf[data.len - 1] == '\n' ||
248 data.buf[data.len - 1] == '\r'))
249 data.len--;
250 data.buf[data.len] = '\0';
251 strbuf_reset(&path);
252 if (!is_absolute_path(data.buf))
253 strbuf_addf(&path, "%s/", gitdir);
254 strbuf_addbuf(&path, &data);
255 strbuf_addstr(sb, real_path(path.buf));
31e26ebc 256 ret = 1;
4dc4e145
NTND
257 } else
258 strbuf_addstr(sb, gitdir);
259 strbuf_release(&data);
260 strbuf_release(&path);
31e26ebc 261 return ret;
4dc4e145 262}
d288a700 263
5f5608bc 264/*
ad1a382f 265 * Test if it looks like we're at a git directory.
5e7bfe25 266 * We want to see:
5f5608bc 267 *
790296fd 268 * - either an objects/ directory _or_ the proper
5f5608bc 269 * GIT_OBJECT_DIRECTORY environment variable
ad1a382f 270 * - a refs/ directory
8098a178 271 * - either a HEAD symlink or a HEAD file that is formatted as
c847f537
JH
272 * a proper "ref:", or a regular file HEAD that has a properly
273 * formatted sha1 object name.
5f5608bc 274 */
b3256eb8 275int is_git_directory(const char *suspect)
5f5608bc 276{
1d186b6f
NTND
277 struct strbuf path = STRBUF_INIT;
278 int ret = 0;
279 size_t len;
ad1a382f 280
4dc4e145
NTND
281 /* Check worktree-related signatures */
282 strbuf_addf(&path, "%s/HEAD", suspect);
283 if (validate_headref(path.buf))
284 goto done;
285
286 strbuf_reset(&path);
287 get_common_dir(&path, suspect);
1d186b6f 288 len = path.len;
4dc4e145
NTND
289
290 /* Check non-worktree-related signatures */
ad1a382f
SP
291 if (getenv(DB_ENVIRONMENT)) {
292 if (access(getenv(DB_ENVIRONMENT), X_OK))
1d186b6f 293 goto done;
ad1a382f
SP
294 }
295 else {
4dc4e145 296 strbuf_setlen(&path, len);
1d186b6f
NTND
297 strbuf_addstr(&path, "/objects");
298 if (access(path.buf, X_OK))
299 goto done;
ad1a382f
SP
300 }
301
1d186b6f
NTND
302 strbuf_setlen(&path, len);
303 strbuf_addstr(&path, "/refs");
304 if (access(path.buf, X_OK))
305 goto done;
ad1a382f 306
1d186b6f
NTND
307 ret = 1;
308done:
309 strbuf_release(&path);
310 return ret;
5f5608bc
LT
311}
312
ffd036b1
JK
313int is_nonbare_repository_dir(struct strbuf *path)
314{
315 int ret = 0;
316 int gitfile_error;
317 size_t orig_path_len = path->len;
318 assert(orig_path_len != 0);
319 strbuf_complete(path, '/');
320 strbuf_addstr(path, ".git");
321 if (read_gitfile_gently(path->buf, &gitfile_error) || is_git_directory(path->buf))
322 ret = 1;
323 if (gitfile_error == READ_GITFILE_ERR_OPEN_FAILED ||
324 gitfile_error == READ_GITFILE_ERR_READ_FAILED)
325 ret = 1;
326 strbuf_setlen(path, orig_path_len);
327 return ret;
328}
329
68025633
JS
330int is_inside_git_dir(void)
331{
e90fdc39
JS
332 if (inside_git_dir < 0)
333 inside_git_dir = is_inside_dir(get_git_dir());
334 return inside_git_dir;
892c41b9
ML
335}
336
892c41b9
ML
337int is_inside_work_tree(void)
338{
e90fdc39
JS
339 if (inside_work_tree < 0)
340 inside_work_tree = is_inside_dir(get_git_work_tree());
341 return inside_work_tree;
892c41b9
ML
342}
343
f3fa1838
JH
344void setup_work_tree(void)
345{
354e6534
JS
346 const char *work_tree, *git_dir;
347 static int initialized = 0;
348
349 if (initialized)
350 return;
fada7674
JK
351
352 if (work_tree_config_is_bogus)
353 die("unable to set up work tree using invalid config");
354
354e6534
JS
355 work_tree = get_git_work_tree();
356 git_dir = get_git_dir();
59f0f2f3 357 if (!is_absolute_path(git_dir))
e2a57aac 358 git_dir = real_path(get_git_dir());
59f0f2f3
MH
359 if (!work_tree || chdir(work_tree))
360 die("This operation must be run in a work tree");
0ed74813
NTND
361
362 /*
363 * Make sure subsequent git processes find correct worktree
364 * if $GIT_WORK_TREE is set relative
365 */
366 if (getenv(GIT_WORK_TREE_ENVIRONMENT))
367 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
368
41894ae3 369 set_git_dir(remove_leading_path(git_dir, work_tree));
354e6534 370 initialized = 1;
59f0f2f3
MH
371}
372
31e26ebc
NTND
373static int check_repo_format(const char *var, const char *value, void *cb)
374{
00a09d57
JK
375 const char *ext;
376
31e26ebc
NTND
377 if (strcmp(var, "core.repositoryformatversion") == 0)
378 repository_format_version = git_config_int(var, value);
00a09d57
JK
379 else if (skip_prefix(var, "extensions.", &ext)) {
380 /*
381 * record any known extensions here; otherwise,
382 * we fall through to recording it as unknown, and
383 * check_repository_format will complain
384 */
385 if (!strcmp(ext, "noop"))
386 ;
067fbd41
JK
387 else if (!strcmp(ext, "preciousobjects"))
388 repository_format_precious_objects = git_config_bool(var, value);
00a09d57
JK
389 else
390 string_list_append(&unknown_extensions, ext);
391 }
31e26ebc
NTND
392 return 0;
393}
394
337e51ce 395static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
9459aa77 396{
7d0fb0da
NTND
397 struct strbuf sb = STRBUF_INIT;
398 const char *repo_config;
31e26ebc 399 config_fn_t fn;
7d0fb0da 400 int ret = 0;
337e51ce 401
00a09d57
JK
402 string_list_clear(&unknown_extensions, 0);
403
31e26ebc
NTND
404 if (get_common_dir(&sb, gitdir))
405 fn = check_repo_format;
406 else
407 fn = check_repository_format_version;
e61a509a
NTND
408 strbuf_addstr(&sb, "/config");
409 repo_config = sb.buf;
410
337e51ce 411 /*
21627f9b
JK
412 * Ignore return value; for historical reasons, we must treat a missing
413 * config file as a noop (git-init relies on this).
337e51ce 414 */
21627f9b 415 git_config_from_file(fn, repo_config, NULL);
00a09d57 416 if (GIT_REPO_VERSION_READ < repository_format_version) {
9459aa77
NTND
417 if (!nongit_ok)
418 die ("Expected git repo version <= %d, found %d",
00a09d57 419 GIT_REPO_VERSION_READ, repository_format_version);
9459aa77 420 warning("Expected git repo version <= %d, found %d",
00a09d57 421 GIT_REPO_VERSION_READ, repository_format_version);
9459aa77
NTND
422 warning("Please upgrade Git");
423 *nongit_ok = -1;
7d0fb0da 424 ret = -1;
9459aa77 425 }
00a09d57
JK
426
427 if (repository_format_version >= 1 && unknown_extensions.nr) {
428 int i;
429
430 if (!nongit_ok)
431 die("unknown repository extension: %s",
432 unknown_extensions.items[0].string);
433
434 for (i = 0; i < unknown_extensions.nr; i++)
435 warning("unknown repository extension: %s",
436 unknown_extensions.items[i].string);
437 *nongit_ok = -1;
438 ret = -1;
439 }
440
7d0fb0da
NTND
441 strbuf_release(&sb);
442 return ret;
9459aa77
NTND
443}
444
b44ebb19
LH
445/*
446 * Try to read the location of the git directory from the .git file,
447 * return path to git directory if found.
a93bedad
EE
448 *
449 * On failure, if return_error_code is not NULL, return_error_code
450 * will be set to an error code and NULL will be returned. If
451 * return_error_code is NULL the function will die instead (for most
452 * cases).
b44ebb19 453 */
a93bedad 454const char *read_gitfile_gently(const char *path, int *return_error_code)
b44ebb19 455{
921bdd96 456 const int max_file_size = 1 << 20; /* 1MB */
a93bedad
EE
457 int error_code = 0;
458 char *buf = NULL;
459 char *dir = NULL;
40c813e0 460 const char *slash;
b44ebb19
LH
461 struct stat st;
462 int fd;
b1905aea 463 ssize_t len;
b44ebb19 464
a93bedad
EE
465 if (stat(path, &st)) {
466 error_code = READ_GITFILE_ERR_STAT_FAILED;
467 goto cleanup_return;
468 }
469 if (!S_ISREG(st.st_mode)) {
470 error_code = READ_GITFILE_ERR_NOT_A_FILE;
471 goto cleanup_return;
472 }
921bdd96
EE
473 if (st.st_size > max_file_size) {
474 error_code = READ_GITFILE_ERR_TOO_LARGE;
475 goto cleanup_return;
476 }
b44ebb19 477 fd = open(path, O_RDONLY);
a93bedad
EE
478 if (fd < 0) {
479 error_code = READ_GITFILE_ERR_OPEN_FAILED;
480 goto cleanup_return;
481 }
3733e694 482 buf = xmallocz(st.st_size);
b44ebb19
LH
483 len = read_in_full(fd, buf, st.st_size);
484 close(fd);
a93bedad
EE
485 if (len != st.st_size) {
486 error_code = READ_GITFILE_ERR_READ_FAILED;
487 goto cleanup_return;
488 }
a93bedad
EE
489 if (!starts_with(buf, "gitdir: ")) {
490 error_code = READ_GITFILE_ERR_INVALID_FORMAT;
491 goto cleanup_return;
492 }
b44ebb19
LH
493 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
494 len--;
a93bedad
EE
495 if (len < 9) {
496 error_code = READ_GITFILE_ERR_NO_PATH;
497 goto cleanup_return;
498 }
b44ebb19 499 buf[len] = '\0';
40c813e0
BK
500 dir = buf + 8;
501
502 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
503 size_t pathlen = slash+1 - path;
75faa45a
JK
504 dir = xstrfmt("%.*s%.*s", (int)pathlen, path,
505 (int)(len - 8), buf + 8);
40c813e0
BK
506 free(buf);
507 buf = dir;
508 }
a93bedad
EE
509 if (!is_git_directory(dir)) {
510 error_code = READ_GITFILE_ERR_NOT_A_REPO;
511 goto cleanup_return;
512 }
e2a57aac 513 path = real_path(dir);
40c813e0 514
a93bedad 515cleanup_return:
a93bedad
EE
516 if (return_error_code)
517 *return_error_code = error_code;
38ae8784 518 else if (error_code) {
a93bedad
EE
519 switch (error_code) {
520 case READ_GITFILE_ERR_STAT_FAILED:
521 case READ_GITFILE_ERR_NOT_A_FILE:
38ae8784
JK
522 /* non-fatal; follow return path */
523 break;
a93bedad
EE
524 case READ_GITFILE_ERR_OPEN_FAILED:
525 die_errno("Error opening '%s'", path);
921bdd96
EE
526 case READ_GITFILE_ERR_TOO_LARGE:
527 die("Too large to be a .git file: '%s'", path);
a93bedad
EE
528 case READ_GITFILE_ERR_READ_FAILED:
529 die("Error reading %s", path);
530 case READ_GITFILE_ERR_INVALID_FORMAT:
531 die("Invalid gitfile format: %s", path);
532 case READ_GITFILE_ERR_NO_PATH:
533 die("No path in gitfile: %s", path);
534 case READ_GITFILE_ERR_NOT_A_REPO:
535 die("Not a git repository: %s", dir);
536 default:
537 assert(0);
538 }
539 }
540
b44ebb19 541 free(buf);
38ae8784 542 return error_code ? NULL : path;
b44ebb19
LH
543}
544
e4e30347 545static const char *setup_explicit_git_dir(const char *gitdirenv,
7333ed17 546 struct strbuf *cwd,
b3f66fd3 547 int *nongit_ok)
e4e30347 548{
b3f66fd3
NTND
549 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
550 const char *worktree;
551 char *gitfile;
9b125da4 552 int offset;
e4e30347
JN
553
554 if (PATH_MAX - 40 < strlen(gitdirenv))
555 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
b3f66fd3 556
13d6ec91 557 gitfile = (char*)read_gitfile(gitdirenv);
b3f66fd3
NTND
558 if (gitfile) {
559 gitfile = xstrdup(gitfile);
560 gitdirenv = gitfile;
561 }
562
e4e30347
JN
563 if (!is_git_directory(gitdirenv)) {
564 if (nongit_ok) {
565 *nongit_ok = 1;
b3f66fd3 566 free(gitfile);
e4e30347
JN
567 return NULL;
568 }
569 die("Not a git repository: '%s'", gitdirenv);
570 }
b3f66fd3
NTND
571
572 if (check_repository_format_gently(gitdirenv, nongit_ok)) {
573 free(gitfile);
574 return NULL;
e4e30347 575 }
b3f66fd3
NTND
576
577 /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
578 if (work_tree_env)
579 set_git_work_tree(work_tree_env);
580 else if (is_bare_repository_cfg > 0) {
fada7674
JK
581 if (git_work_tree_cfg) {
582 /* #22.2, #30 */
583 warning("core.bare and core.worktree do not make sense");
584 work_tree_config_is_bogus = 1;
585 }
b3f66fd3
NTND
586
587 /* #18, #26 */
588 set_git_dir(gitdirenv);
589 free(gitfile);
e4e30347 590 return NULL;
b3f66fd3
NTND
591 }
592 else if (git_work_tree_cfg) { /* #6, #14 */
593 if (is_absolute_path(git_work_tree_cfg))
594 set_git_work_tree(git_work_tree_cfg);
595 else {
56b9f6e7 596 char *core_worktree;
b3f66fd3
NTND
597 if (chdir(gitdirenv))
598 die_errno("Could not chdir to '%s'", gitdirenv);
599 if (chdir(git_work_tree_cfg))
600 die_errno("Could not chdir to '%s'", git_work_tree_cfg);
56b9f6e7 601 core_worktree = xgetcwd();
7333ed17 602 if (chdir(cwd->buf))
b3f66fd3
NTND
603 die_errno("Could not come back to cwd");
604 set_git_work_tree(core_worktree);
56b9f6e7 605 free(core_worktree);
b3f66fd3
NTND
606 }
607 }
2cd83d10
JK
608 else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
609 /* #16d */
610 set_git_dir(gitdirenv);
611 free(gitfile);
612 return NULL;
613 }
b3f66fd3
NTND
614 else /* #2, #10 */
615 set_git_work_tree(".");
616
617 /* set_git_work_tree() must have been called by now */
618 worktree = get_git_work_tree();
619
620 /* both get_git_work_tree() and cwd are already normalized */
7333ed17 621 if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
b3f66fd3
NTND
622 set_git_dir(gitdirenv);
623 free(gitfile);
e4e30347 624 return NULL;
b3f66fd3 625 }
e4e30347 626
7333ed17 627 offset = dir_inside_of(cwd->buf, worktree);
9b125da4 628 if (offset >= 0) { /* cwd inside worktree? */
e2a57aac 629 set_git_dir(real_path(gitdirenv));
b3f66fd3
NTND
630 if (chdir(worktree))
631 die_errno("Could not chdir to '%s'", worktree);
7333ed17 632 strbuf_addch(cwd, '/');
b3f66fd3 633 free(gitfile);
7333ed17 634 return cwd->buf + offset;
93a00542 635 }
b3f66fd3
NTND
636
637 /* cwd outside worktree */
638 set_git_dir(gitdirenv);
639 free(gitfile);
640 return NULL;
93a00542
JN
641}
642
9951d3b3 643static const char *setup_discovered_git_dir(const char *gitdir,
7333ed17 644 struct strbuf *cwd, int offset,
9951d3b3 645 int *nongit_ok)
98937bef 646{
9951d3b3
NTND
647 if (check_repository_format_gently(gitdir, nongit_ok))
648 return NULL;
98937bef 649
4868b2ea
JN
650 /* --work-tree is set without --git-dir; use discovered one */
651 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
7333ed17 652 if (offset != cwd->len && !is_absolute_path(gitdir))
e2a57aac 653 gitdir = xstrdup(real_path(gitdir));
7333ed17 654 if (chdir(cwd->buf))
4868b2ea 655 die_errno("Could not come back to cwd");
7333ed17 656 return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
4868b2ea
JN
657 }
658
9951d3b3
NTND
659 /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
660 if (is_bare_repository_cfg > 0) {
7333ed17
RS
661 set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
662 if (chdir(cwd->buf))
9951d3b3 663 die_errno("Could not come back to cwd");
98937bef 664 return NULL;
9951d3b3 665 }
98937bef 666
9951d3b3
NTND
667 /* #0, #1, #5, #8, #9, #12, #13 */
668 set_git_work_tree(".");
669 if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
670 set_git_dir(gitdir);
98937bef 671 inside_git_dir = 0;
9951d3b3 672 inside_work_tree = 1;
7333ed17 673 if (offset == cwd->len)
98937bef
NTND
674 return NULL;
675
676 /* Make "offset" point to past the '/', and add a '/' at the end */
677 offset++;
7333ed17
RS
678 strbuf_addch(cwd, '/');
679 return cwd->buf + offset;
98937bef
NTND
680}
681
1cd8031b 682/* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
7333ed17
RS
683static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
684 int *nongit_ok)
68698da5
JN
685{
686 int root_len;
687
1cd8031b
NTND
688 if (check_repository_format_gently(".", nongit_ok))
689 return NULL;
690
2cd83d10
JK
691 setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
692
4868b2ea
JN
693 /* --work-tree is set without --git-dir; use discovered one */
694 if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
695 const char *gitdir;
696
7333ed17
RS
697 gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
698 if (chdir(cwd->buf))
4868b2ea 699 die_errno("Could not come back to cwd");
7333ed17 700 return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
4868b2ea
JN
701 }
702
68698da5 703 inside_git_dir = 1;
1cd8031b 704 inside_work_tree = 0;
7333ed17
RS
705 if (offset != cwd->len) {
706 if (chdir(cwd->buf))
8fc0ae80 707 die_errno("Cannot come back to cwd");
7333ed17
RS
708 root_len = offset_1st_component(cwd->buf);
709 strbuf_setlen(cwd, offset > root_len ? offset : root_len);
710 set_git_dir(cwd->buf);
337e51ce 711 }
1cd8031b 712 else
68698da5 713 set_git_dir(".");
68698da5
JN
714 return NULL;
715}
716
f161edeb
JN
717static const char *setup_nongit(const char *cwd, int *nongit_ok)
718{
719 if (!nongit_ok)
720 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
721 if (chdir(cwd))
722 die_errno("Cannot come back to cwd");
723 *nongit_ok = 1;
724 return NULL;
725}
726
2565b43b 727static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
60c98d1e
JN
728{
729 struct stat buf;
2565b43b
CB
730 if (stat(path, &buf)) {
731 die_errno("failed to stat '%*s%s%s'",
732 prefix_len,
60c98d1e
JN
733 prefix ? prefix : "",
734 prefix ? "/" : "", path);
2565b43b 735 }
60c98d1e
JN
736 return buf.st_dev;
737}
738
9e2326c7 739/*
1b77d83c
MH
740 * A "string_list_each_func_t" function that canonicalizes an entry
741 * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
7ec30aaa
MH
742 * discards it if unusable. The presence of an empty entry in
743 * GIT_CEILING_DIRECTORIES turns off canonicalization for all
744 * subsequent entries.
9e2326c7 745 */
1b77d83c 746static int canonicalize_ceiling_entry(struct string_list_item *item,
7ec30aaa 747 void *cb_data)
9e2326c7 748{
7ec30aaa 749 int *empty_entry_found = cb_data;
1b77d83c 750 char *ceil = item->string;
9e2326c7 751
7ec30aaa
MH
752 if (!*ceil) {
753 *empty_entry_found = 1;
9e2326c7 754 return 0;
7ec30aaa 755 } else if (!is_absolute_path(ceil)) {
9e2326c7 756 return 0;
7ec30aaa
MH
757 } else if (*empty_entry_found) {
758 /* Keep entry but do not canonicalize it */
759 return 1;
760 } else {
761 const char *real_path = real_path_if_valid(ceil);
762 if (!real_path)
763 return 0;
764 free(item->string);
765 item->string = xstrdup(real_path);
766 return 1;
767 }
9e2326c7
MH
768}
769
e90fdc39
JS
770/*
771 * We cannot decide in this function whether we are in the work tree or
772 * not, since the config can only be read _after_ this function was called.
773 */
a60645f9 774static const char *setup_git_directory_gently_1(int *nongit_ok)
d288a700 775{
0454dd93 776 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
31171d9e 777 struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
7333ed17 778 static struct strbuf cwd = STRBUF_INIT;
9951d3b3
NTND
779 const char *gitdirenv, *ret;
780 char *gitfile;
7333ed17 781 int offset, offset_parent, ceil_offset = -1;
c7d1d1b1
RH
782 dev_t current_device = 0;
783 int one_filesystem = 1;
d288a700 784
3c8687a7
TA
785 /*
786 * We may have read an incomplete configuration before
787 * setting-up the git directory. If so, clear the cache so
788 * that the next queries to the configuration reload complete
789 * configuration (including the per-repo config file that we
790 * ignored previously).
791 */
792 git_config_clear();
793
af05d679
SG
794 /*
795 * Let's assume that we are in a git repository.
796 * If it turns out later that we are somewhere else, the value will be
797 * updated accordingly.
798 */
799 if (nongit_ok)
800 *nongit_ok = 0;
801
7333ed17 802 if (strbuf_getcwd(&cwd))
b3f66fd3 803 die_errno("Unable to read current working directory");
7333ed17 804 offset = cwd.len;
b3f66fd3 805
e90fdc39
JS
806 /*
807 * If GIT_DIR is set explicitly, we're not going
808 * to do any discovery, but we still do repository
809 * validation.
810 */
ad1a382f 811 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
e4e30347 812 if (gitdirenv)
7333ed17 813 return setup_explicit_git_dir(gitdirenv, &cwd, nongit_ok);
d288a700 814
31171d9e 815 if (env_ceiling_dirs) {
7ec30aaa
MH
816 int empty_entry_found = 0;
817
31171d9e 818 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
1b77d83c 819 filter_string_list(&ceiling_dirs, 0,
7ec30aaa 820 canonicalize_ceiling_entry, &empty_entry_found);
7333ed17 821 ceil_offset = longest_ancestor_length(cwd.buf, &ceiling_dirs);
31171d9e
MH
822 string_list_clear(&ceiling_dirs, 0);
823 }
824
7333ed17 825 if (ceil_offset < 0 && has_dos_drive_prefix(cwd.buf))
17d778e7 826 ceil_offset = 1;
d288a700 827
892c41b9 828 /*
e90fdc39 829 * Test in the following order (relative to the cwd):
b44ebb19 830 * - .git (file containing "gitdir: <path>")
e90fdc39
JS
831 * - .git/
832 * - ./ (bare)
b44ebb19 833 * - ../.git
e90fdc39
JS
834 * - ../.git/
835 * - ../ (bare)
836 * - ../../.git/
837 * etc.
892c41b9 838 */
cf87463e 839 one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
60c98d1e 840 if (one_filesystem)
2565b43b 841 current_device = get_device_or_die(".", NULL, 0);
e90fdc39 842 for (;;) {
13d6ec91 843 gitfile = (char*)read_gitfile(DEFAULT_GIT_DIR_ENVIRONMENT);
9951d3b3
NTND
844 if (gitfile)
845 gitdirenv = gitfile = xstrdup(gitfile);
846 else {
847 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
848 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
849 }
850
851 if (gitdirenv) {
852 ret = setup_discovered_git_dir(gitdirenv,
7333ed17 853 &cwd, offset,
9951d3b3
NTND
854 nongit_ok);
855 free(gitfile);
856 return ret;
857 }
858 free(gitfile);
859
68698da5 860 if (is_git_directory("."))
7333ed17 861 return setup_bare_git_dir(&cwd, offset, nongit_ok);
1cd8031b 862
2565b43b 863 offset_parent = offset;
7333ed17 864 while (--offset_parent > ceil_offset && cwd.buf[offset_parent] != '/');
2565b43b 865 if (offset_parent <= ceil_offset)
7333ed17 866 return setup_nongit(cwd.buf, nongit_ok);
8030e442 867 if (one_filesystem) {
7333ed17
RS
868 dev_t parent_device = get_device_or_die("..", cwd.buf,
869 offset);
60c98d1e 870 if (parent_device != current_device) {
8030e442 871 if (nongit_ok) {
7333ed17 872 if (chdir(cwd.buf))
8030e442
LD
873 die_errno("Cannot come back to cwd");
874 *nongit_ok = 1;
875 return NULL;
876 }
7333ed17 877 strbuf_setlen(&cwd, offset);
2565b43b 878 die("Not a git repository (or any parent up to mount point %s)\n"
7333ed17
RS
879 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).",
880 cwd.buf);
8030e442
LD
881 }
882 }
502ffe34 883 if (chdir("..")) {
7333ed17
RS
884 strbuf_setlen(&cwd, offset);
885 die_errno("Cannot change to '%s/..'", cwd.buf);
502ffe34 886 }
2565b43b 887 offset = offset_parent;
892c41b9 888 }
d288a700 889}
5e7bfe25 890
a60645f9
NTND
891const char *setup_git_directory_gently(int *nongit_ok)
892{
893 const char *prefix;
894
895 prefix = setup_git_directory_gently_1(nongit_ok);
1f5d271f 896 if (prefix)
a6f7f9a3 897 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
1f5d271f 898 else
a6f7f9a3 899 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
1f5d271f 900
f07d6a1a 901 if (startup_info) {
a60645f9 902 startup_info->have_repository = !nongit_ok || !*nongit_ok;
f07d6a1a
NTND
903 startup_info->prefix = prefix;
904 }
a60645f9
NTND
905 return prefix;
906}
907
94df2506
JH
908int git_config_perm(const char *var, const char *value)
909{
06cbe855
HO
910 int i;
911 char *endptr;
912
913 if (value == NULL)
914 return PERM_GROUP;
915
916 if (!strcmp(value, "umask"))
917 return PERM_UMASK;
918 if (!strcmp(value, "group"))
919 return PERM_GROUP;
920 if (!strcmp(value, "all") ||
921 !strcmp(value, "world") ||
922 !strcmp(value, "everybody"))
923 return PERM_EVERYBODY;
924
925 /* Parse octal numbers */
926 i = strtol(value, &endptr, 8);
927
928 /* If not an octal number, maybe true/false? */
929 if (*endptr != 0)
930 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
931
932 /*
933 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
5a688fe4 934 * a chmod value to restrict to.
06cbe855
HO
935 */
936 switch (i) {
937 case PERM_UMASK: /* 0 */
938 return PERM_UMASK;
939 case OLD_PERM_GROUP: /* 1 */
940 return PERM_GROUP;
941 case OLD_PERM_EVERYBODY: /* 2 */
942 return PERM_EVERYBODY;
94df2506 943 }
06cbe855
HO
944
945 /* A filemode value was given: 0xxx */
946
947 if ((i & 0600) != 0600)
948 die("Problem with core.sharedRepository filemode value "
949 "(0%.3o).\nThe owner of files must always have "
950 "read and write permissions.", i);
951
952 /*
953 * Mask filemode value. Others can not get write permission.
954 * x flags for directories are handled separately.
955 */
5a688fe4 956 return -(i & 0666);
94df2506
JH
957}
958
ef90d6d4 959int check_repository_format_version(const char *var, const char *value, void *cb)
ab9cb76f 960{
31e26ebc
NTND
961 int ret = check_repo_format(var, value, cb);
962 if (ret)
963 return ret;
964 if (strcmp(var, "core.bare") == 0) {
e90fdc39
JS
965 is_bare_repository_cfg = git_config_bool(var, value);
966 if (is_bare_repository_cfg == 1)
967 inside_work_tree = -1;
968 } else if (strcmp(var, "core.worktree") == 0) {
180483c5
JH
969 if (!value)
970 return config_error_nonbool(var);
8e0f7003 971 free(git_work_tree_cfg);
e90fdc39
JS
972 git_work_tree_cfg = xstrdup(value);
973 inside_work_tree = -1;
974 }
299726d5 975 return 0;
ab9cb76f
JH
976}
977
4b0d1eeb 978void check_repository_format(void)
ab9cb76f 979{
4b0d1eeb 980 check_repository_format_gently(get_git_dir(), NULL);
ab9cb76f
JH
981}
982
e1e5ec86
CB
983/*
984 * Returns the "prefix", a path to the current working directory
985 * relative to the work tree root, or NULL, if the current working
986 * directory is not a strict subdirectory of the work tree root. The
987 * prefix always ends with a '/' character.
988 */
5e7bfe25
JH
989const char *setup_git_directory(void)
990{
b3f66fd3 991 return setup_git_directory_gently(NULL);
5e7bfe25 992}
abc06822
FG
993
994const char *resolve_gitdir(const char *suspect)
995{
996 if (is_git_directory(suspect))
997 return suspect;
efc5fb6a 998 return read_gitfile(suspect);
abc06822 999}
1d999ddd
TR
1000
1001/* if any standard file descriptor is missing open it to /dev/null */
1002void sanitize_stdfds(void)
1003{
1004 int fd = open("/dev/null", O_RDWR, 0);
1005 while (fd != -1 && fd < 2)
1006 fd = dup(fd);
1007 if (fd == -1)
1008 die_errno("open /dev/null or dup failed");
1009 if (fd > 2)
1010 close(fd);
1011}
de0957ce
NTND
1012
1013int daemonize(void)
1014{
1015#ifdef NO_POSIX_GOODIES
1016 errno = ENOSYS;
1017 return -1;
1018#else
1019 switch (fork()) {
1020 case 0:
1021 break;
1022 case -1:
1023 die_errno("fork failed");
1024 default:
1025 exit(0);
1026 }
1027 if (setsid() == -1)
1028 die_errno("setsid failed");
1029 close(0);
1030 close(1);
1031 close(2);
1032 sanitize_stdfds();
1033 return 0;
1034#endif
1035}