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