Code

setup: rework setup_explicit_git_dir()
[git.git] / setup.c
1 #include "cache.h"
2 #include "dir.h"
4 static int inside_git_dir = -1;
5 static int inside_work_tree = -1;
7 const char *prefix_path(const char *prefix, int len, const char *path)
8 {
9         const char *orig = path;
10         char *sanitized = xmalloc(len + strlen(path) + 1);
11         if (is_absolute_path(orig))
12                 strcpy(sanitized, path);
13         else {
14                 if (len)
15                         memcpy(sanitized, prefix, len);
16                 strcpy(sanitized + len, path);
17         }
18         if (normalize_path_copy(sanitized, sanitized))
19                 goto error_out;
20         if (is_absolute_path(orig)) {
21                 size_t root_len, len, total;
22                 const char *work_tree = get_git_work_tree();
23                 if (!work_tree)
24                         goto error_out;
25                 len = strlen(work_tree);
26                 root_len = offset_1st_component(work_tree);
27                 total = strlen(sanitized) + 1;
28                 if (strncmp(sanitized, work_tree, len) ||
29                     (len > root_len && sanitized[len] != '\0' && sanitized[len] != '/')) {
30                 error_out:
31                         die("'%s' is outside repository", orig);
32                 }
33                 if (sanitized[len] == '/')
34                         len++;
35                 memmove(sanitized, sanitized + len, total - len);
36         }
37         return sanitized;
38 }
40 /*
41  * Unlike prefix_path, this should be used if the named file does
42  * not have to interact with index entry; i.e. name of a random file
43  * on the filesystem.
44  */
45 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
46 {
47         static char path[PATH_MAX];
48 #ifndef WIN32
49         if (!pfx || !*pfx || is_absolute_path(arg))
50                 return arg;
51         memcpy(path, pfx, pfx_len);
52         strcpy(path + pfx_len, arg);
53 #else
54         char *p;
55         /* don't add prefix to absolute paths, but still replace '\' by '/' */
56         if (is_absolute_path(arg))
57                 pfx_len = 0;
58         else
59                 memcpy(path, pfx, pfx_len);
60         strcpy(path + pfx_len, arg);
61         for (p = path + pfx_len; *p; p++)
62                 if (*p == '\\')
63                         *p = '/';
64 #endif
65         return path;
66 }
68 int check_filename(const char *prefix, const char *arg)
69 {
70         const char *name;
71         struct stat st;
73         name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
74         if (!lstat(name, &st))
75                 return 1; /* file exists */
76         if (errno == ENOENT || errno == ENOTDIR)
77                 return 0; /* file does not exist */
78         die_errno("failed to stat '%s'", arg);
79 }
81 static void NORETURN die_verify_filename(const char *prefix, const char *arg)
82 {
83         unsigned char sha1[20];
84         unsigned mode;
85         /* try a detailed diagnostic ... */
86         get_sha1_with_mode_1(arg, sha1, &mode, 0, prefix);
87         /* ... or fall back the most general message. */
88         die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
89             "Use '--' to separate paths from revisions", arg);
91 }
93 /*
94  * Verify a filename that we got as an argument for a pathspec
95  * entry. Note that a filename that begins with "-" never verifies
96  * as true, because even if such a filename were to exist, we want
97  * it to be preceded by the "--" marker (or we want the user to
98  * use a format like "./-filename")
99  */
100 void verify_filename(const char *prefix, const char *arg)
102         if (*arg == '-')
103                 die("bad flag '%s' used after filename", arg);
104         if (check_filename(prefix, arg))
105                 return;
106         die_verify_filename(prefix, arg);
109 /*
110  * Opposite of the above: the command line did not have -- marker
111  * and we parsed the arg as a refname.  It should not be interpretable
112  * as a filename.
113  */
114 void verify_non_filename(const char *prefix, const char *arg)
116         if (!is_inside_work_tree() || is_inside_git_dir())
117                 return;
118         if (*arg == '-')
119                 return; /* flag */
120         if (!check_filename(prefix, arg))
121                 return;
122         die("ambiguous argument '%s': both revision and filename\n"
123             "Use '--' to separate filenames from revisions", arg);
126 const char **get_pathspec(const char *prefix, const char **pathspec)
128         const char *entry = *pathspec;
129         const char **src, **dst;
130         int prefixlen;
132         if (!prefix && !entry)
133                 return NULL;
135         if (!entry) {
136                 static const char *spec[2];
137                 spec[0] = prefix;
138                 spec[1] = NULL;
139                 return spec;
140         }
142         /* Otherwise we have to re-write the entries.. */
143         src = pathspec;
144         dst = pathspec;
145         prefixlen = prefix ? strlen(prefix) : 0;
146         while (*src) {
147                 const char *p = prefix_path(prefix, prefixlen, *src);
148                 *(dst++) = p;
149                 src++;
150         }
151         *dst = NULL;
152         if (!*pathspec)
153                 return NULL;
154         return pathspec;
157 /*
158  * Test if it looks like we're at a git directory.
159  * We want to see:
160  *
161  *  - either an objects/ directory _or_ the proper
162  *    GIT_OBJECT_DIRECTORY environment variable
163  *  - a refs/ directory
164  *  - either a HEAD symlink or a HEAD file that is formatted as
165  *    a proper "ref:", or a regular file HEAD that has a properly
166  *    formatted sha1 object name.
167  */
168 static int is_git_directory(const char *suspect)
170         char path[PATH_MAX];
171         size_t len = strlen(suspect);
173         if (PATH_MAX <= len + strlen("/objects"))
174                 die("Too long path: %.*s", 60, suspect);
175         strcpy(path, suspect);
176         if (getenv(DB_ENVIRONMENT)) {
177                 if (access(getenv(DB_ENVIRONMENT), X_OK))
178                         return 0;
179         }
180         else {
181                 strcpy(path + len, "/objects");
182                 if (access(path, X_OK))
183                         return 0;
184         }
186         strcpy(path + len, "/refs");
187         if (access(path, X_OK))
188                 return 0;
190         strcpy(path + len, "/HEAD");
191         if (validate_headref(path))
192                 return 0;
194         return 1;
197 int is_inside_git_dir(void)
199         if (inside_git_dir < 0)
200                 inside_git_dir = is_inside_dir(get_git_dir());
201         return inside_git_dir;
204 int is_inside_work_tree(void)
206         if (inside_work_tree < 0)
207                 inside_work_tree = is_inside_dir(get_git_work_tree());
208         return inside_work_tree;
211 void setup_work_tree(void)
213         const char *work_tree, *git_dir;
214         static int initialized = 0;
216         if (initialized)
217                 return;
218         work_tree = get_git_work_tree();
219         git_dir = get_git_dir();
220         if (!is_absolute_path(git_dir))
221                 git_dir = make_absolute_path(git_dir);
222         if (!work_tree || chdir(work_tree))
223                 die("This operation must be run in a work tree");
224         set_git_dir(make_relative_path(git_dir, work_tree));
225         initialized = 1;
228 static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
230         char repo_config[PATH_MAX+1];
232         /*
233          * git_config() can't be used here because it calls git_pathdup()
234          * to get $GIT_CONFIG/config. That call will make setup_git_env()
235          * set git_dir to ".git".
236          *
237          * We are in gitdir setup, no git dir has been found useable yet.
238          * Use a gentler version of git_config() to check if this repo
239          * is a good one.
240          */
241         snprintf(repo_config, PATH_MAX, "%s/config", gitdir);
242         git_config_early(check_repository_format_version, NULL, repo_config);
243         if (GIT_REPO_VERSION < repository_format_version) {
244                 if (!nongit_ok)
245                         die ("Expected git repo version <= %d, found %d",
246                              GIT_REPO_VERSION, repository_format_version);
247                 warning("Expected git repo version <= %d, found %d",
248                         GIT_REPO_VERSION, repository_format_version);
249                 warning("Please upgrade Git");
250                 *nongit_ok = -1;
251                 return -1;
252         }
253         return 0;
256 /*
257  * Try to read the location of the git directory from the .git file,
258  * return path to git directory if found.
259  */
260 const char *read_gitfile_gently(const char *path)
262         char *buf;
263         char *dir;
264         const char *slash;
265         struct stat st;
266         int fd;
267         size_t len;
269         if (stat(path, &st))
270                 return NULL;
271         if (!S_ISREG(st.st_mode))
272                 return NULL;
273         fd = open(path, O_RDONLY);
274         if (fd < 0)
275                 die_errno("Error opening '%s'", path);
276         buf = xmalloc(st.st_size + 1);
277         len = read_in_full(fd, buf, st.st_size);
278         close(fd);
279         if (len != st.st_size)
280                 die("Error reading %s", path);
281         buf[len] = '\0';
282         if (prefixcmp(buf, "gitdir: "))
283                 die("Invalid gitfile format: %s", path);
284         while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
285                 len--;
286         if (len < 9)
287                 die("No path in gitfile: %s", path);
288         buf[len] = '\0';
289         dir = buf + 8;
291         if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
292                 size_t pathlen = slash+1 - path;
293                 size_t dirlen = pathlen + len - 8;
294                 dir = xmalloc(dirlen + 1);
295                 strncpy(dir, path, pathlen);
296                 strncpy(dir + pathlen, buf + 8, len - 8);
297                 dir[dirlen] = '\0';
298                 free(buf);
299                 buf = dir;
300         }
302         if (!is_git_directory(dir))
303                 die("Not a git repository: %s", dir);
304         path = make_absolute_path(dir);
306         free(buf);
307         return path;
310 static const char *setup_explicit_git_dir(const char *gitdirenv,
311                                           char *cwd, int len,
312                                           int *nongit_ok)
314         const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
315         const char *worktree;
316         char *gitfile;
318         if (PATH_MAX - 40 < strlen(gitdirenv))
319                 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
321         gitfile = (char*)read_gitfile_gently(gitdirenv);
322         if (gitfile) {
323                 gitfile = xstrdup(gitfile);
324                 gitdirenv = gitfile;
325         }
327         if (!is_git_directory(gitdirenv)) {
328                 if (nongit_ok) {
329                         *nongit_ok = 1;
330                         free(gitfile);
331                         return NULL;
332                 }
333                 die("Not a git repository: '%s'", gitdirenv);
334         }
336         if (check_repository_format_gently(gitdirenv, nongit_ok)) {
337                 free(gitfile);
338                 return NULL;
339         }
341         /* #3, #7, #11, #15, #19, #23, #27, #31 (see t1510) */
342         if (work_tree_env)
343                 set_git_work_tree(work_tree_env);
344         else if (is_bare_repository_cfg > 0) {
345                 if (git_work_tree_cfg) /* #22.2, #30 */
346                         die("core.bare and core.worktree do not make sense");
348                 /* #18, #26 */
349                 set_git_dir(gitdirenv);
350                 free(gitfile);
351                 return NULL;
352         }
353         else if (git_work_tree_cfg) { /* #6, #14 */
354                 if (is_absolute_path(git_work_tree_cfg))
355                         set_git_work_tree(git_work_tree_cfg);
356                 else {
357                         char core_worktree[PATH_MAX];
358                         if (chdir(gitdirenv))
359                                 die_errno("Could not chdir to '%s'", gitdirenv);
360                         if (chdir(git_work_tree_cfg))
361                                 die_errno("Could not chdir to '%s'", git_work_tree_cfg);
362                         if (!getcwd(core_worktree, PATH_MAX))
363                                 die_errno("Could not get directory '%s'", git_work_tree_cfg);
364                         if (chdir(cwd))
365                                 die_errno("Could not come back to cwd");
366                         set_git_work_tree(core_worktree);
367                 }
368         }
369         else /* #2, #10 */
370                 set_git_work_tree(".");
372         /* set_git_work_tree() must have been called by now */
373         worktree = get_git_work_tree();
375         /* both get_git_work_tree() and cwd are already normalized */
376         if (!strcmp(cwd, worktree)) { /* cwd == worktree */
377                 set_git_dir(gitdirenv);
378                 free(gitfile);
379                 return NULL;
380         }
382         if (!prefixcmp(cwd, worktree) &&
383             cwd[strlen(worktree)] == '/') { /* cwd inside worktree */
384                 set_git_dir(make_absolute_path(gitdirenv));
385                 if (chdir(worktree))
386                         die_errno("Could not chdir to '%s'", worktree);
387                 cwd[len++] = '/';
388                 cwd[len] = '\0';
389                 free(gitfile);
390                 return cwd + strlen(worktree) + 1;
391         }
393         /* cwd outside worktree */
394         set_git_dir(gitdirenv);
395         free(gitfile);
396         return NULL;
399 static const char *setup_discovered_git_dir(const char *gitdir,
400                                             char *cwd, int offset, int len,
401                                             int *nongit_ok)
403         if (check_repository_format_gently(gitdir, nongit_ok))
404                 return NULL;
406         /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
407         if (is_bare_repository_cfg > 0) {
408                 set_git_dir(offset == len ? gitdir : make_absolute_path(gitdir));
409                 if (chdir(cwd))
410                         die_errno("Could not come back to cwd");
411                 return NULL;
412         }
414         /* #0, #1, #5, #8, #9, #12, #13 */
415         set_git_work_tree(".");
416         if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
417                 set_git_dir(gitdir);
418         inside_git_dir = 0;
419         inside_work_tree = 1;
420         if (offset == len)
421                 return NULL;
423         /* Make "offset" point to past the '/', and add a '/' at the end */
424         offset++;
425         cwd[len++] = '/';
426         cwd[len] = 0;
427         return cwd + offset;
430 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
431 static const char *setup_bare_git_dir(char *cwd, int offset, int len, int *nongit_ok)
433         int root_len;
435         if (check_repository_format_gently(".", nongit_ok))
436                 return NULL;
438         inside_git_dir = 1;
439         inside_work_tree = 0;
440         if (offset != len) {
441                 if (chdir(cwd))
442                         die_errno("Cannot come back to cwd");
443                 root_len = offset_1st_component(cwd);
444                 cwd[offset > root_len ? offset : root_len] = '\0';
445                 set_git_dir(cwd);
446         }
447         else
448                 set_git_dir(".");
449         return NULL;
452 static const char *setup_nongit(const char *cwd, int *nongit_ok)
454         if (!nongit_ok)
455                 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
456         if (chdir(cwd))
457                 die_errno("Cannot come back to cwd");
458         *nongit_ok = 1;
459         return NULL;
462 static dev_t get_device_or_die(const char *path, const char *prefix)
464         struct stat buf;
465         if (stat(path, &buf))
466                 die_errno("failed to stat '%s%s%s'",
467                                 prefix ? prefix : "",
468                                 prefix ? "/" : "", path);
469         return buf.st_dev;
472 /*
473  * We cannot decide in this function whether we are in the work tree or
474  * not, since the config can only be read _after_ this function was called.
475  */
476 static const char *setup_git_directory_gently_1(int *nongit_ok)
478         const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
479         static char cwd[PATH_MAX+1];
480         const char *gitdirenv, *ret;
481         char *gitfile;
482         int len, offset, ceil_offset;
483         dev_t current_device = 0;
484         int one_filesystem = 1;
486         /*
487          * Let's assume that we are in a git repository.
488          * If it turns out later that we are somewhere else, the value will be
489          * updated accordingly.
490          */
491         if (nongit_ok)
492                 *nongit_ok = 0;
494         if (!getcwd(cwd, sizeof(cwd)-1))
495                 die_errno("Unable to read current working directory");
496         offset = len = strlen(cwd);
498         /*
499          * If GIT_DIR is set explicitly, we're not going
500          * to do any discovery, but we still do repository
501          * validation.
502          */
503         gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
504         if (gitdirenv)
505                 return setup_explicit_git_dir(gitdirenv, cwd, len, nongit_ok);
507         ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
508         if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
509                 ceil_offset = 1;
511         /*
512          * Test in the following order (relative to the cwd):
513          * - .git (file containing "gitdir: <path>")
514          * - .git/
515          * - ./ (bare)
516          * - ../.git
517          * - ../.git/
518          * - ../ (bare)
519          * - ../../.git/
520          *   etc.
521          */
522         one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
523         if (one_filesystem)
524                 current_device = get_device_or_die(".", NULL);
525         for (;;) {
526                 gitfile = (char*)read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
527                 if (gitfile)
528                         gitdirenv = gitfile = xstrdup(gitfile);
529                 else {
530                         if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
531                                 gitdirenv = DEFAULT_GIT_DIR_ENVIRONMENT;
532                 }
534                 if (gitdirenv) {
535                         ret = setup_discovered_git_dir(gitdirenv,
536                                                        cwd, offset, len,
537                                                        nongit_ok);
538                         free(gitfile);
539                         return ret;
540                 }
541                 free(gitfile);
543                 if (is_git_directory("."))
544                         return setup_bare_git_dir(cwd, offset, len, nongit_ok);
546                 while (--offset > ceil_offset && cwd[offset] != '/');
547                 if (offset <= ceil_offset)
548                         return setup_nongit(cwd, nongit_ok);
549                 if (one_filesystem) {
550                         dev_t parent_device = get_device_or_die("..", cwd);
551                         if (parent_device != current_device) {
552                                 if (nongit_ok) {
553                                         if (chdir(cwd))
554                                                 die_errno("Cannot come back to cwd");
555                                         *nongit_ok = 1;
556                                         return NULL;
557                                 }
558                                 cwd[offset] = '\0';
559                                 die("Not a git repository (or any parent up to mount parent %s)\n"
560                                 "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd);
561                         }
562                 }
563                 if (chdir("..")) {
564                         cwd[offset] = '\0';
565                         die_errno("Cannot change to '%s/..'", cwd);
566                 }
567         }
570 const char *setup_git_directory_gently(int *nongit_ok)
572         const char *prefix;
574         prefix = setup_git_directory_gently_1(nongit_ok);
575         if (startup_info)
576                 startup_info->have_repository = !nongit_ok || !*nongit_ok;
577         return prefix;
580 int git_config_perm(const char *var, const char *value)
582         int i;
583         char *endptr;
585         if (value == NULL)
586                 return PERM_GROUP;
588         if (!strcmp(value, "umask"))
589                 return PERM_UMASK;
590         if (!strcmp(value, "group"))
591                 return PERM_GROUP;
592         if (!strcmp(value, "all") ||
593             !strcmp(value, "world") ||
594             !strcmp(value, "everybody"))
595                 return PERM_EVERYBODY;
597         /* Parse octal numbers */
598         i = strtol(value, &endptr, 8);
600         /* If not an octal number, maybe true/false? */
601         if (*endptr != 0)
602                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
604         /*
605          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
606          * a chmod value to restrict to.
607          */
608         switch (i) {
609         case PERM_UMASK:               /* 0 */
610                 return PERM_UMASK;
611         case OLD_PERM_GROUP:           /* 1 */
612                 return PERM_GROUP;
613         case OLD_PERM_EVERYBODY:       /* 2 */
614                 return PERM_EVERYBODY;
615         }
617         /* A filemode value was given: 0xxx */
619         if ((i & 0600) != 0600)
620                 die("Problem with core.sharedRepository filemode value "
621                     "(0%.3o).\nThe owner of files must always have "
622                     "read and write permissions.", i);
624         /*
625          * Mask filemode value. Others can not get write permission.
626          * x flags for directories are handled separately.
627          */
628         return -(i & 0666);
631 int check_repository_format_version(const char *var, const char *value, void *cb)
633         if (strcmp(var, "core.repositoryformatversion") == 0)
634                 repository_format_version = git_config_int(var, value);
635         else if (strcmp(var, "core.sharedrepository") == 0)
636                 shared_repository = git_config_perm(var, value);
637         else if (strcmp(var, "core.bare") == 0) {
638                 is_bare_repository_cfg = git_config_bool(var, value);
639                 if (is_bare_repository_cfg == 1)
640                         inside_work_tree = -1;
641         } else if (strcmp(var, "core.worktree") == 0) {
642                 if (!value)
643                         return config_error_nonbool(var);
644                 free(git_work_tree_cfg);
645                 git_work_tree_cfg = xstrdup(value);
646                 inside_work_tree = -1;
647         }
648         return 0;
651 int check_repository_format(void)
653         return check_repository_format_gently(get_git_dir(), NULL);
656 /*
657  * Returns the "prefix", a path to the current working directory
658  * relative to the work tree root, or NULL, if the current working
659  * directory is not a strict subdirectory of the work tree root. The
660  * prefix always ends with a '/' character.
661  */
662 const char *setup_git_directory(void)
664         return setup_git_directory_gently(NULL);