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