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