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