setup: suppress implicit "." work-tree for bare repos
[git] / setup.c
1 #include "cache.h"
2 #include "dir.h"
3 #include "string-list.h"
4
5 static int inside_git_dir = -1;
6 static int inside_work_tree = -1;
7
8 static char *prefix_path_gently(const char *prefix, int len, const char *path)
9 {
10         const char *orig = path;
11         char *sanitized;
12         if (is_absolute_path(orig)) {
13                 const char *temp = real_path(path);
14                 sanitized = xmalloc(len + strlen(temp) + 1);
15                 strcpy(sanitized, temp);
16         } else {
17                 sanitized = xmalloc(len + strlen(path) + 1);
18                 if (len)
19                         memcpy(sanitized, prefix, len);
20                 strcpy(sanitized + len, path);
21         }
22         if (normalize_path_copy(sanitized, sanitized))
23                 goto error_out;
24         if (is_absolute_path(orig)) {
25                 size_t root_len, len, total;
26                 const char *work_tree = get_git_work_tree();
27                 if (!work_tree)
28                         goto error_out;
29                 len = strlen(work_tree);
30                 root_len = offset_1st_component(work_tree);
31                 total = strlen(sanitized) + 1;
32                 if (strncmp(sanitized, work_tree, len) ||
33                     (len > root_len && sanitized[len] != '\0' && sanitized[len] != '/')) {
34                 error_out:
35                         free(sanitized);
36                         return NULL;
37                 }
38                 if (sanitized[len] == '/')
39                         len++;
40                 memmove(sanitized, sanitized + len, total - len);
41         }
42         return sanitized;
43 }
44
45 char *prefix_path(const char *prefix, int len, const char *path)
46 {
47         char *r = prefix_path_gently(prefix, len, path);
48         if (!r)
49                 die("'%s' is outside repository", path);
50         return r;
51 }
52
53 int path_inside_repo(const char *prefix, const char *path)
54 {
55         int len = prefix ? strlen(prefix) : 0;
56         char *r = prefix_path_gently(prefix, len, path);
57         if (r) {
58                 free(r);
59                 return 1;
60         }
61         return 0;
62 }
63
64 int check_filename(const char *prefix, const char *arg)
65 {
66         const char *name;
67         struct stat st;
68
69         name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
70         if (!lstat(name, &st))
71                 return 1; /* file exists */
72         if (errno == ENOENT || errno == ENOTDIR)
73                 return 0; /* file does not exist */
74         die_errno("failed to stat '%s'", arg);
75 }
76
77 static void NORETURN die_verify_filename(const char *prefix,
78                                          const char *arg,
79                                          int diagnose_misspelt_rev)
80 {
81         if (!diagnose_misspelt_rev)
82                 die("%s: no such path in the working tree.\n"
83                     "Use 'git <command> -- <path>...' to specify paths that do not exist locally.",
84                     arg);
85         /*
86          * Saying "'(icase)foo' does not exist in the index" when the
87          * user gave us ":(icase)foo" is just stupid.  A magic pathspec
88          * begins with a colon and is followed by a non-alnum; do not
89          * let maybe_die_on_misspelt_object_name() even trigger.
90          */
91         if (!(arg[0] == ':' && !isalnum(arg[1])))
92                 maybe_die_on_misspelt_object_name(arg, prefix);
93
94         /* ... or fall back the most general message. */
95         die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
96             "Use '--' to separate paths from revisions, like this:\n"
97             "'git <command> [<revision>...] -- [<file>...]'", arg);
98
99 }
100
101 /*
102  * Verify a filename that we got as an argument for a pathspec
103  * entry. Note that a filename that begins with "-" never verifies
104  * as true, because even if such a filename were to exist, we want
105  * it to be preceded by the "--" marker (or we want the user to
106  * use a format like "./-filename")
107  *
108  * The "diagnose_misspelt_rev" is used to provide a user-friendly
109  * diagnosis when dying upon finding that "name" is not a pathname.
110  * If set to 1, the diagnosis will try to diagnose "name" as an
111  * invalid object name (e.g. HEAD:foo). If set to 0, the diagnosis
112  * will only complain about an inexisting file.
113  *
114  * This function is typically called to check that a "file or rev"
115  * argument is unambiguous. In this case, the caller will want
116  * diagnose_misspelt_rev == 1 when verifying the first non-rev
117  * argument (which could have been a revision), and
118  * diagnose_misspelt_rev == 0 for the next ones (because we already
119  * saw a filename, there's not ambiguity anymore).
120  */
121 void verify_filename(const char *prefix,
122                      const char *arg,
123                      int diagnose_misspelt_rev)
124 {
125         if (*arg == '-')
126                 die("bad flag '%s' used after filename", arg);
127         if (check_filename(prefix, arg))
128                 return;
129         die_verify_filename(prefix, arg, diagnose_misspelt_rev);
130 }
131
132 /*
133  * Opposite of the above: the command line did not have -- marker
134  * and we parsed the arg as a refname.  It should not be interpretable
135  * as a filename.
136  */
137 void verify_non_filename(const char *prefix, const char *arg)
138 {
139         if (!is_inside_work_tree() || is_inside_git_dir())
140                 return;
141         if (*arg == '-')
142                 return; /* flag */
143         if (!check_filename(prefix, arg))
144                 return;
145         die("ambiguous argument '%s': both revision and filename\n"
146             "Use '--' to separate paths from revisions, like this:\n"
147             "'git <command> [<revision>...] -- [<file>...]'", arg);
148 }
149
150 /*
151  * Magic pathspec
152  *
153  * NEEDSWORK: These need to be moved to dir.h or even to a new
154  * pathspec.h when we restructure get_pathspec() users to use the
155  * "struct pathspec" interface.
156  *
157  * Possible future magic semantics include stuff like:
158  *
159  *      { PATHSPEC_NOGLOB, '!', "noglob" },
160  *      { PATHSPEC_ICASE, '\0', "icase" },
161  *      { PATHSPEC_RECURSIVE, '*', "recursive" },
162  *      { PATHSPEC_REGEXP, '\0', "regexp" },
163  *
164  */
165 #define PATHSPEC_FROMTOP    (1<<0)
166
167 static struct pathspec_magic {
168         unsigned bit;
169         char mnemonic; /* this cannot be ':'! */
170         const char *name;
171 } pathspec_magic[] = {
172         { PATHSPEC_FROMTOP, '/', "top" },
173 };
174
175 /*
176  * Take an element of a pathspec and check for magic signatures.
177  * Append the result to the prefix.
178  *
179  * For now, we only parse the syntax and throw out anything other than
180  * "top" magic.
181  *
182  * NEEDSWORK: This needs to be rewritten when we start migrating
183  * get_pathspec() users to use the "struct pathspec" interface.  For
184  * example, a pathspec element may be marked as case-insensitive, but
185  * the prefix part must always match literally, and a single stupid
186  * string cannot express such a case.
187  */
188 static const char *prefix_pathspec(const char *prefix, int prefixlen, const char *elt)
189 {
190         unsigned magic = 0;
191         const char *copyfrom = elt;
192         int i;
193
194         if (elt[0] != ':') {
195                 ; /* nothing to do */
196         } else if (elt[1] == '(') {
197                 /* longhand */
198                 const char *nextat;
199                 for (copyfrom = elt + 2;
200                      *copyfrom && *copyfrom != ')';
201                      copyfrom = nextat) {
202                         size_t len = strcspn(copyfrom, ",)");
203                         if (copyfrom[len] == ')')
204                                 nextat = copyfrom + len;
205                         else
206                                 nextat = copyfrom + len + 1;
207                         if (!len)
208                                 continue;
209                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
210                                 if (strlen(pathspec_magic[i].name) == len &&
211                                     !strncmp(pathspec_magic[i].name, copyfrom, len)) {
212                                         magic |= pathspec_magic[i].bit;
213                                         break;
214                                 }
215                         if (ARRAY_SIZE(pathspec_magic) <= i)
216                                 die("Invalid pathspec magic '%.*s' in '%s'",
217                                     (int) len, copyfrom, elt);
218                 }
219                 if (*copyfrom == ')')
220                         copyfrom++;
221         } else {
222                 /* shorthand */
223                 for (copyfrom = elt + 1;
224                      *copyfrom && *copyfrom != ':';
225                      copyfrom++) {
226                         char ch = *copyfrom;
227
228                         if (!is_pathspec_magic(ch))
229                                 break;
230                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
231                                 if (pathspec_magic[i].mnemonic == ch) {
232                                         magic |= pathspec_magic[i].bit;
233                                         break;
234                                 }
235                         if (ARRAY_SIZE(pathspec_magic) <= i)
236                                 die("Unimplemented pathspec magic '%c' in '%s'",
237                                     ch, elt);
238                 }
239                 if (*copyfrom == ':')
240                         copyfrom++;
241         }
242
243         if (magic & PATHSPEC_FROMTOP)
244                 return xstrdup(copyfrom);
245         else
246                 return prefix_path(prefix, prefixlen, copyfrom);
247 }
248
249 const char **get_pathspec(const char *prefix, const char **pathspec)
250 {
251         const char *entry = *pathspec;
252         const char **src, **dst;
253         int prefixlen;
254
255         if (!prefix && !entry)
256                 return NULL;
257
258         if (!entry) {
259                 static const char *spec[2];
260                 spec[0] = prefix;
261                 spec[1] = NULL;
262                 return spec;
263         }
264
265         /* Otherwise we have to re-write the entries.. */
266         src = pathspec;
267         dst = pathspec;
268         prefixlen = prefix ? strlen(prefix) : 0;
269         while (*src) {
270                 *(dst++) = prefix_pathspec(prefix, prefixlen, *src);
271                 src++;
272         }
273         *dst = NULL;
274         if (!*pathspec)
275                 return NULL;
276         return pathspec;
277 }
278
279 /*
280  * Test if it looks like we're at a git directory.
281  * We want to see:
282  *
283  *  - either an objects/ directory _or_ the proper
284  *    GIT_OBJECT_DIRECTORY environment variable
285  *  - a refs/ directory
286  *  - either a HEAD symlink or a HEAD file that is formatted as
287  *    a proper "ref:", or a regular file HEAD that has a properly
288  *    formatted sha1 object name.
289  */
290 int is_git_directory(const char *suspect)
291 {
292         char path[PATH_MAX];
293         size_t len = strlen(suspect);
294
295         if (PATH_MAX <= len + strlen("/objects"))
296                 die("Too long path: %.*s", 60, suspect);
297         strcpy(path, suspect);
298         if (getenv(DB_ENVIRONMENT)) {
299                 if (access(getenv(DB_ENVIRONMENT), X_OK))
300                         return 0;
301         }
302         else {
303                 strcpy(path + len, "/objects");
304                 if (access(path, X_OK))
305                         return 0;
306         }
307
308         strcpy(path + len, "/refs");
309         if (access(path, X_OK))
310                 return 0;
311
312         strcpy(path + len, "/HEAD");
313         if (validate_headref(path))
314                 return 0;
315
316         return 1;
317 }
318
319 int is_inside_git_dir(void)
320 {
321         if (inside_git_dir < 0)
322                 inside_git_dir = is_inside_dir(get_git_dir());
323         return inside_git_dir;
324 }
325
326 int is_inside_work_tree(void)
327 {
328         if (inside_work_tree < 0)
329                 inside_work_tree = is_inside_dir(get_git_work_tree());
330         return inside_work_tree;
331 }
332
333 void setup_work_tree(void)
334 {
335         const char *work_tree, *git_dir;
336         static int initialized = 0;
337
338         if (initialized)
339                 return;
340         work_tree = get_git_work_tree();
341         git_dir = get_git_dir();
342         if (!is_absolute_path(git_dir))
343                 git_dir = real_path(get_git_dir());
344         if (!work_tree || chdir(work_tree))
345                 die("This operation must be run in a work tree");
346
347         /*
348          * Make sure subsequent git processes find correct worktree
349          * if $GIT_WORK_TREE is set relative
350          */
351         if (getenv(GIT_WORK_TREE_ENVIRONMENT))
352                 setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
353
354         set_git_dir(relative_path(git_dir, work_tree));
355         initialized = 1;
356 }
357
358 static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
359 {
360         char repo_config[PATH_MAX+1];
361
362         /*
363          * git_config() can't be used here because it calls git_pathdup()
364          * to get $GIT_CONFIG/config. That call will make setup_git_env()
365          * set git_dir to ".git".
366          *
367          * We are in gitdir setup, no git dir has been found useable yet.
368          * Use a gentler version of git_config() to check if this repo
369          * is a good one.
370          */
371         snprintf(repo_config, PATH_MAX, "%s/config", gitdir);
372         git_config_early(check_repository_format_version, NULL, repo_config);
373         if (GIT_REPO_VERSION < repository_format_version) {
374                 if (!nongit_ok)
375                         die ("Expected git repo version <= %d, found %d",
376                              GIT_REPO_VERSION, repository_format_version);
377                 warning("Expected git repo version <= %d, found %d",
378                         GIT_REPO_VERSION, repository_format_version);
379                 warning("Please upgrade Git");
380                 *nongit_ok = -1;
381                 return -1;
382         }
383         return 0;
384 }
385
386 /*
387  * Try to read the location of the git directory from the .git file,
388  * return path to git directory if found.
389  */
390 const char *read_gitfile(const char *path)
391 {
392         char *buf;
393         char *dir;
394         const char *slash;
395         struct stat st;
396         int fd;
397         ssize_t len;
398
399         if (stat(path, &st))
400                 return NULL;
401         if (!S_ISREG(st.st_mode))
402                 return NULL;
403         fd = open(path, O_RDONLY);
404         if (fd < 0)
405                 die_errno("Error opening '%s'", path);
406         buf = xmalloc(st.st_size + 1);
407         len = read_in_full(fd, buf, st.st_size);
408         close(fd);
409         if (len != st.st_size)
410                 die("Error reading %s", path);
411         buf[len] = '\0';
412         if (prefixcmp(buf, "gitdir: "))
413                 die("Invalid gitfile format: %s", path);
414         while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
415                 len--;
416         if (len < 9)
417                 die("No path in gitfile: %s", path);
418         buf[len] = '\0';
419         dir = buf + 8;
420
421         if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
422                 size_t pathlen = slash+1 - path;
423                 size_t dirlen = pathlen + len - 8;
424                 dir = xmalloc(dirlen + 1);
425                 strncpy(dir, path, pathlen);
426                 strncpy(dir + pathlen, buf + 8, len - 8);
427                 dir[dirlen] = '\0';
428                 free(buf);
429                 buf = dir;
430         }
431
432         if (!is_git_directory(dir))
433                 die("Not a git repository: %s", dir);
434         path = real_path(dir);
435
436         free(buf);
437         return path;
438 }
439
440 static const char *setup_explicit_git_dir(const char *gitdirenv,
441                                           char *cwd, int len,
442                                           int *nongit_ok)
443 {
444         const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
445         const char *worktree;
446         char *gitfile;
447         int offset;
448
449         if (PATH_MAX - 40 < strlen(gitdirenv))
450                 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
451
452         gitfile = (char*)read_gitfile(gitdirenv);
453         if (gitfile) {
454                 gitfile = xstrdup(gitfile);
455                 gitdirenv = gitfile;
456         }
457
458         if (!is_git_directory(gitdirenv)) {
459                 if (nongit_ok) {
460                         *nongit_ok = 1;
461                         free(gitfile);
462                         return NULL;
463                 }
464                 die("Not a git repository: '%s'", gitdirenv);
465         }
466
467         if (check_repository_format_gently(gitdirenv, nongit_ok)) {
468                 free(gitfile);
469                 return NULL;
470         }
471
472         /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
473         if (work_tree_env)
474                 set_git_work_tree(work_tree_env);
475         else if (is_bare_repository_cfg > 0) {
476                 if (git_work_tree_cfg) /* #22.2, #30 */
477                         die("core.bare and core.worktree do not make sense");
478
479                 /* #18, #26 */
480                 set_git_dir(gitdirenv);
481                 free(gitfile);
482                 return NULL;
483         }
484         else if (git_work_tree_cfg) { /* #6, #14 */
485                 if (is_absolute_path(git_work_tree_cfg))
486                         set_git_work_tree(git_work_tree_cfg);
487                 else {
488                         char core_worktree[PATH_MAX];
489                         if (chdir(gitdirenv))
490                                 die_errno("Could not chdir to '%s'", gitdirenv);
491                         if (chdir(git_work_tree_cfg))
492                                 die_errno("Could not chdir to '%s'", git_work_tree_cfg);
493                         if (!getcwd(core_worktree, PATH_MAX))
494                                 die_errno("Could not get directory '%s'", git_work_tree_cfg);
495                         if (chdir(cwd))
496                                 die_errno("Could not come back to cwd");
497                         set_git_work_tree(core_worktree);
498                 }
499         }
500         else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
501                 /* #16d */
502                 set_git_dir(gitdirenv);
503                 free(gitfile);
504                 return NULL;
505         }
506         else /* #2, #10 */
507                 set_git_work_tree(".");
508
509         /* set_git_work_tree() must have been called by now */
510         worktree = get_git_work_tree();
511
512         /* both get_git_work_tree() and cwd are already normalized */
513         if (!strcmp(cwd, worktree)) { /* cwd == worktree */
514                 set_git_dir(gitdirenv);
515                 free(gitfile);
516                 return NULL;
517         }
518
519         offset = dir_inside_of(cwd, worktree);
520         if (offset >= 0) {      /* cwd inside worktree? */
521                 set_git_dir(real_path(gitdirenv));
522                 if (chdir(worktree))
523                         die_errno("Could not chdir to '%s'", worktree);
524                 cwd[len++] = '/';
525                 cwd[len] = '\0';
526                 free(gitfile);
527                 return cwd + offset;
528         }
529
530         /* cwd outside worktree */
531         set_git_dir(gitdirenv);
532         free(gitfile);
533         return NULL;
534 }
535
536 static const char *setup_discovered_git_dir(const char *gitdir,
537                                             char *cwd, int offset, int len,
538                                             int *nongit_ok)
539 {
540         if (check_repository_format_gently(gitdir, nongit_ok))
541                 return NULL;
542
543         /* --work-tree is set without --git-dir; use discovered one */
544         if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
545                 if (offset != len && !is_absolute_path(gitdir))
546                         gitdir = xstrdup(real_path(gitdir));
547                 if (chdir(cwd))
548                         die_errno("Could not come back to cwd");
549                 return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
550         }
551
552         /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
553         if (is_bare_repository_cfg > 0) {
554                 set_git_dir(offset == len ? gitdir : real_path(gitdir));
555                 if (chdir(cwd))
556                         die_errno("Could not come back to cwd");
557                 return NULL;
558         }
559
560         /* #0, #1, #5, #8, #9, #12, #13 */
561         set_git_work_tree(".");
562         if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
563                 set_git_dir(gitdir);
564         inside_git_dir = 0;
565         inside_work_tree = 1;
566         if (offset == len)
567                 return NULL;
568
569         /* Make "offset" point to past the '/', and add a '/' at the end */
570         offset++;
571         cwd[len++] = '/';
572         cwd[len] = 0;
573         return cwd + offset;
574 }
575
576 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
577 static const char *setup_bare_git_dir(char *cwd, int offset, int len, int *nongit_ok)
578 {
579         int root_len;
580
581         if (check_repository_format_gently(".", nongit_ok))
582                 return NULL;
583
584         setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
585
586         /* --work-tree is set without --git-dir; use discovered one */
587         if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
588                 const char *gitdir;
589
590                 gitdir = offset == len ? "." : xmemdupz(cwd, offset);
591                 if (chdir(cwd))
592                         die_errno("Could not come back to cwd");
593                 return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
594         }
595
596         inside_git_dir = 1;
597         inside_work_tree = 0;
598         if (offset != len) {
599                 if (chdir(cwd))
600                         die_errno("Cannot come back to cwd");
601                 root_len = offset_1st_component(cwd);
602                 cwd[offset > root_len ? offset : root_len] = '\0';
603                 set_git_dir(cwd);
604         }
605         else
606                 set_git_dir(".");
607         return NULL;
608 }
609
610 static const char *setup_nongit(const char *cwd, int *nongit_ok)
611 {
612         if (!nongit_ok)
613                 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
614         if (chdir(cwd))
615                 die_errno("Cannot come back to cwd");
616         *nongit_ok = 1;
617         return NULL;
618 }
619
620 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
621 {
622         struct stat buf;
623         if (stat(path, &buf)) {
624                 die_errno("failed to stat '%*s%s%s'",
625                                 prefix_len,
626                                 prefix ? prefix : "",
627                                 prefix ? "/" : "", path);
628         }
629         return buf.st_dev;
630 }
631
632 /*
633  * A "string_list_each_func_t" function that canonicalizes an entry
634  * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
635  * discards it if unusable.  The presence of an empty entry in
636  * GIT_CEILING_DIRECTORIES turns off canonicalization for all
637  * subsequent entries.
638  */
639 static int canonicalize_ceiling_entry(struct string_list_item *item,
640                                       void *cb_data)
641 {
642         int *empty_entry_found = cb_data;
643         char *ceil = item->string;
644
645         if (!*ceil) {
646                 *empty_entry_found = 1;
647                 return 0;
648         } else if (!is_absolute_path(ceil)) {
649                 return 0;
650         } else if (*empty_entry_found) {
651                 /* Keep entry but do not canonicalize it */
652                 return 1;
653         } else {
654                 const char *real_path = real_path_if_valid(ceil);
655                 if (!real_path)
656                         return 0;
657                 free(item->string);
658                 item->string = xstrdup(real_path);
659                 return 1;
660         }
661 }
662
663 /*
664  * We cannot decide in this function whether we are in the work tree or
665  * not, since the config can only be read _after_ this function was called.
666  */
667 static const char *setup_git_directory_gently_1(int *nongit_ok)
668 {
669         const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
670         struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
671         static char cwd[PATH_MAX+1];
672         const char *gitdirenv, *ret;
673         char *gitfile;
674         int len, offset, offset_parent, ceil_offset = -1;
675         dev_t current_device = 0;
676         int one_filesystem = 1;
677
678         /*
679          * Let's assume that we are in a git repository.
680          * If it turns out later that we are somewhere else, the value will be
681          * updated accordingly.
682          */
683         if (nongit_ok)
684                 *nongit_ok = 0;
685
686         if (!getcwd(cwd, sizeof(cwd)-1))
687                 die_errno("Unable to read current working directory");
688         offset = len = strlen(cwd);
689
690         /*
691          * If GIT_DIR is set explicitly, we're not going
692          * to do any discovery, but we still do repository
693          * validation.
694          */
695         gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
696         if (gitdirenv)
697                 return setup_explicit_git_dir(gitdirenv, cwd, len, nongit_ok);
698
699         if (env_ceiling_dirs) {
700                 int empty_entry_found = 0;
701
702                 string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
703                 filter_string_list(&ceiling_dirs, 0,
704                                    canonicalize_ceiling_entry, &empty_entry_found);
705                 ceil_offset = longest_ancestor_length(cwd, &ceiling_dirs);
706                 string_list_clear(&ceiling_dirs, 0);
707         }
708
709         if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
710                 ceil_offset = 1;
711
712         /*
713          * Test in the following order (relative to the cwd):
714          * - .git (file containing "gitdir: <path>")
715          * - .git/
716          * - ./ (bare)
717          * - ../.git
718          * - ../.git/
719          * - ../ (bare)
720          * - ../../.git/
721          *   etc.
722          */
723         one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
724         if (one_filesystem)
725                 current_device = get_device_or_die(".", NULL, 0);
726         for (;;) {
727                 gitfile = (char*)read_gitfile(DEFAULT_GIT_DIR_ENVIRONMENT);
728                 if (gitfile)
729                         gitdirenv = gitfile = xstrdup(gitfile);
730                 else {
731                         if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
732                                 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
733                 }
734
735                 if (gitdirenv) {
736                         ret = setup_discovered_git_dir(gitdirenv,
737                                                        cwd, offset, len,
738                                                        nongit_ok);
739                         free(gitfile);
740                         return ret;
741                 }
742                 free(gitfile);
743
744                 if (is_git_directory("."))
745                         return setup_bare_git_dir(cwd, offset, len, nongit_ok);
746
747                 offset_parent = offset;
748                 while (--offset_parent > ceil_offset && cwd[offset_parent] != '/');
749                 if (offset_parent <= ceil_offset)
750                         return setup_nongit(cwd, nongit_ok);
751                 if (one_filesystem) {
752                         dev_t parent_device = get_device_or_die("..", cwd, offset);
753                         if (parent_device != current_device) {
754                                 if (nongit_ok) {
755                                         if (chdir(cwd))
756                                                 die_errno("Cannot come back to cwd");
757                                         *nongit_ok = 1;
758                                         return NULL;
759                                 }
760                                 cwd[offset] = '\0';
761                                 die("Not a git repository (or any parent up to mount point %s)\n"
762                                 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd);
763                         }
764                 }
765                 if (chdir("..")) {
766                         cwd[offset] = '\0';
767                         die_errno("Cannot change to '%s/..'", cwd);
768                 }
769                 offset = offset_parent;
770         }
771 }
772
773 const char *setup_git_directory_gently(int *nongit_ok)
774 {
775         const char *prefix;
776
777         prefix = setup_git_directory_gently_1(nongit_ok);
778         if (prefix)
779                 setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
780         else
781                 setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
782
783         if (startup_info) {
784                 startup_info->have_repository = !nongit_ok || !*nongit_ok;
785                 startup_info->prefix = prefix;
786         }
787         return prefix;
788 }
789
790 int git_config_perm(const char *var, const char *value)
791 {
792         int i;
793         char *endptr;
794
795         if (value == NULL)
796                 return PERM_GROUP;
797
798         if (!strcmp(value, "umask"))
799                 return PERM_UMASK;
800         if (!strcmp(value, "group"))
801                 return PERM_GROUP;
802         if (!strcmp(value, "all") ||
803             !strcmp(value, "world") ||
804             !strcmp(value, "everybody"))
805                 return PERM_EVERYBODY;
806
807         /* Parse octal numbers */
808         i = strtol(value, &endptr, 8);
809
810         /* If not an octal number, maybe true/false? */
811         if (*endptr != 0)
812                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
813
814         /*
815          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
816          * a chmod value to restrict to.
817          */
818         switch (i) {
819         case PERM_UMASK:               /* 0 */
820                 return PERM_UMASK;
821         case OLD_PERM_GROUP:           /* 1 */
822                 return PERM_GROUP;
823         case OLD_PERM_EVERYBODY:       /* 2 */
824                 return PERM_EVERYBODY;
825         }
826
827         /* A filemode value was given: 0xxx */
828
829         if ((i & 0600) != 0600)
830                 die("Problem with core.sharedRepository filemode value "
831                     "(0%.3o).\nThe owner of files must always have "
832                     "read and write permissions.", i);
833
834         /*
835          * Mask filemode value. Others can not get write permission.
836          * x flags for directories are handled separately.
837          */
838         return -(i & 0666);
839 }
840
841 int check_repository_format_version(const char *var, const char *value, void *cb)
842 {
843         if (strcmp(var, "core.repositoryformatversion") == 0)
844                 repository_format_version = git_config_int(var, value);
845         else if (strcmp(var, "core.sharedrepository") == 0)
846                 shared_repository = git_config_perm(var, value);
847         else if (strcmp(var, "core.bare") == 0) {
848                 is_bare_repository_cfg = git_config_bool(var, value);
849                 if (is_bare_repository_cfg == 1)
850                         inside_work_tree = -1;
851         } else if (strcmp(var, "core.worktree") == 0) {
852                 if (!value)
853                         return config_error_nonbool(var);
854                 free(git_work_tree_cfg);
855                 git_work_tree_cfg = xstrdup(value);
856                 inside_work_tree = -1;
857         }
858         return 0;
859 }
860
861 int check_repository_format(void)
862 {
863         return check_repository_format_gently(get_git_dir(), NULL);
864 }
865
866 /*
867  * Returns the "prefix", a path to the current working directory
868  * relative to the work tree root, or NULL, if the current working
869  * directory is not a strict subdirectory of the work tree root. The
870  * prefix always ends with a '/' character.
871  */
872 const char *setup_git_directory(void)
873 {
874         return setup_git_directory_gently(NULL);
875 }
876
877 const char *resolve_gitdir(const char *suspect)
878 {
879         if (is_git_directory(suspect))
880                 return suspect;
881         return read_gitfile(suspect);
882 }