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