Code

Fix "config_error_nonbool" used with value instead of key
[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 static int sanitary_path_copy(char *dst, const char *src)
8 {
9         char *dst0 = dst;
11         if (*src == '/') {
12                 *dst++ = '/';
13                 while (*src == '/')
14                         src++;
15         }
17         for (;;) {
18                 char c = *src;
20                 /*
21                  * A path component that begins with . could be
22                  * special:
23                  * (1) "." and ends   -- ignore and terminate.
24                  * (2) "./"           -- ignore them, eat slash and continue.
25                  * (3) ".." and ends  -- strip one and terminate.
26                  * (4) "../"          -- strip one, eat slash and continue.
27                  */
28                 if (c == '.') {
29                         switch (src[1]) {
30                         case '\0':
31                                 /* (1) */
32                                 src++;
33                                 break;
34                         case '/':
35                                 /* (2) */
36                                 src += 2;
37                                 while (*src == '/')
38                                         src++;
39                                 continue;
40                         case '.':
41                                 switch (src[2]) {
42                                 case '\0':
43                                         /* (3) */
44                                         src += 2;
45                                         goto up_one;
46                                 case '/':
47                                         /* (4) */
48                                         src += 3;
49                                         while (*src == '/')
50                                                 src++;
51                                         goto up_one;
52                                 }
53                         }
54                 }
56                 /* copy up to the next '/', and eat all '/' */
57                 while ((c = *src++) != '\0' && c != '/')
58                         *dst++ = c;
59                 if (c == '/') {
60                         *dst++ = c;
61                         while (c == '/')
62                                 c = *src++;
63                         src--;
64                 } else if (!c)
65                         break;
66                 continue;
68         up_one:
69                 /*
70                  * dst0..dst is prefix portion, and dst[-1] is '/';
71                  * go up one level.
72                  */
73                 dst -= 2; /* go past trailing '/' if any */
74                 if (dst < dst0)
75                         return -1;
76                 while (1) {
77                         if (dst <= dst0)
78                                 break;
79                         c = *dst--;
80                         if (c == '/') {
81                                 dst += 2;
82                                 break;
83                         }
84                 }
85         }
86         *dst = '\0';
87         return 0;
88 }
90 const char *prefix_path(const char *prefix, int len, const char *path)
91 {
92         const char *orig = path;
93         char *sanitized = xmalloc(len + strlen(path) + 1);
94         if (is_absolute_path(orig))
95                 strcpy(sanitized, path);
96         else {
97                 if (len)
98                         memcpy(sanitized, prefix, len);
99                 strcpy(sanitized + len, path);
100         }
101         if (sanitary_path_copy(sanitized, sanitized))
102                 goto error_out;
103         if (is_absolute_path(orig)) {
104                 const char *work_tree = get_git_work_tree();
105                 size_t len = strlen(work_tree);
106                 size_t total = strlen(sanitized) + 1;
107                 if (strncmp(sanitized, work_tree, len) ||
108                     (sanitized[len] != '\0' && sanitized[len] != '/')) {
109                 error_out:
110                         error("'%s' is outside repository", orig);
111                         free(sanitized);
112                         return NULL;
113                 }
114                 if (sanitized[len] == '/')
115                         len++;
116                 memmove(sanitized, sanitized + len, total - len);
117         }
118         return sanitized;
121 /*
122  * Unlike prefix_path, this should be used if the named file does
123  * not have to interact with index entry; i.e. name of a random file
124  * on the filesystem.
125  */
126 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
128         static char path[PATH_MAX];
129         if (!pfx || !*pfx || is_absolute_path(arg))
130                 return arg;
131         memcpy(path, pfx, pfx_len);
132         strcpy(path + pfx_len, arg);
133         return path;
136 /*
137  * Verify a filename that we got as an argument for a pathspec
138  * entry. Note that a filename that begins with "-" never verifies
139  * as true, because even if such a filename were to exist, we want
140  * it to be preceded by the "--" marker (or we want the user to
141  * use a format like "./-filename")
142  */
143 void verify_filename(const char *prefix, const char *arg)
145         const char *name;
146         struct stat st;
148         if (*arg == '-')
149                 die("bad flag '%s' used after filename", arg);
150         name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
151         if (!lstat(name, &st))
152                 return;
153         if (errno == ENOENT)
154                 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
155                     "Use '--' to separate paths from revisions", arg);
156         die("'%s': %s", arg, strerror(errno));
159 /*
160  * Opposite of the above: the command line did not have -- marker
161  * and we parsed the arg as a refname.  It should not be interpretable
162  * as a filename.
163  */
164 void verify_non_filename(const char *prefix, const char *arg)
166         const char *name;
167         struct stat st;
169         if (!is_inside_work_tree() || is_inside_git_dir())
170                 return;
171         if (*arg == '-')
172                 return; /* flag */
173         name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
174         if (!lstat(name, &st))
175                 die("ambiguous argument '%s': both revision and filename\n"
176                     "Use '--' to separate filenames from revisions", arg);
177         if (errno != ENOENT && errno != ENOTDIR)
178                 die("'%s': %s", arg, strerror(errno));
181 const char **get_pathspec(const char *prefix, const char **pathspec)
183         const char *entry = *pathspec;
184         const char **src, **dst;
185         int prefixlen;
187         if (!prefix && !entry)
188                 return NULL;
190         if (!entry) {
191                 static const char *spec[2];
192                 spec[0] = prefix;
193                 spec[1] = NULL;
194                 return spec;
195         }
197         /* Otherwise we have to re-write the entries.. */
198         src = pathspec;
199         dst = pathspec;
200         prefixlen = prefix ? strlen(prefix) : 0;
201         while (*src) {
202                 const char *p = prefix_path(prefix, prefixlen, *src);
203                 if (p)
204                         *(dst++) = p;
205                 else
206                         exit(128); /* error message already given */
207                 src++;
208         }
209         *dst = NULL;
210         if (!*pathspec)
211                 return NULL;
212         return pathspec;
215 /*
216  * Test if it looks like we're at a git directory.
217  * We want to see:
218  *
219  *  - either an objects/ directory _or_ the proper
220  *    GIT_OBJECT_DIRECTORY environment variable
221  *  - a refs/ directory
222  *  - either a HEAD symlink or a HEAD file that is formatted as
223  *    a proper "ref:", or a regular file HEAD that has a properly
224  *    formatted sha1 object name.
225  */
226 static int is_git_directory(const char *suspect)
228         char path[PATH_MAX];
229         size_t len = strlen(suspect);
231         strcpy(path, suspect);
232         if (getenv(DB_ENVIRONMENT)) {
233                 if (access(getenv(DB_ENVIRONMENT), X_OK))
234                         return 0;
235         }
236         else {
237                 strcpy(path + len, "/objects");
238                 if (access(path, X_OK))
239                         return 0;
240         }
242         strcpy(path + len, "/refs");
243         if (access(path, X_OK))
244                 return 0;
246         strcpy(path + len, "/HEAD");
247         if (validate_headref(path))
248                 return 0;
250         return 1;
253 int is_inside_git_dir(void)
255         if (inside_git_dir < 0)
256                 inside_git_dir = is_inside_dir(get_git_dir());
257         return inside_git_dir;
260 int is_inside_work_tree(void)
262         if (inside_work_tree < 0)
263                 inside_work_tree = is_inside_dir(get_git_work_tree());
264         return inside_work_tree;
267 /*
268  * set_work_tree() is only ever called if you set GIT_DIR explicitely.
269  * The old behaviour (which we retain here) is to set the work tree root
270  * to the cwd, unless overridden by the config, the command line, or
271  * GIT_WORK_TREE.
272  */
273 static const char *set_work_tree(const char *dir)
275         char buffer[PATH_MAX + 1];
277         if (!getcwd(buffer, sizeof(buffer)))
278                 die ("Could not get the current working directory");
279         git_work_tree_cfg = xstrdup(buffer);
280         inside_work_tree = 1;
282         return NULL;
285 void setup_work_tree(void)
287         const char *work_tree, *git_dir;
288         static int initialized = 0;
290         if (initialized)
291                 return;
292         work_tree = get_git_work_tree();
293         git_dir = get_git_dir();
294         if (!is_absolute_path(git_dir))
295                 git_dir = make_absolute_path(git_dir);
296         if (!work_tree || chdir(work_tree))
297                 die("This operation must be run in a work tree");
298         set_git_dir(make_relative_path(git_dir, work_tree));
299         initialized = 1;
302 static int check_repository_format_gently(int *nongit_ok)
304         git_config(check_repository_format_version, NULL);
305         if (GIT_REPO_VERSION < repository_format_version) {
306                 if (!nongit_ok)
307                         die ("Expected git repo version <= %d, found %d",
308                              GIT_REPO_VERSION, repository_format_version);
309                 warning("Expected git repo version <= %d, found %d",
310                         GIT_REPO_VERSION, repository_format_version);
311                 warning("Please upgrade Git");
312                 *nongit_ok = -1;
313                 return -1;
314         }
315         return 0;
318 /*
319  * Try to read the location of the git directory from the .git file,
320  * return path to git directory if found.
321  */
322 const char *read_gitfile_gently(const char *path)
324         char *buf;
325         struct stat st;
326         int fd;
327         size_t len;
329         if (stat(path, &st))
330                 return NULL;
331         if (!S_ISREG(st.st_mode))
332                 return NULL;
333         fd = open(path, O_RDONLY);
334         if (fd < 0)
335                 die("Error opening %s: %s", path, strerror(errno));
336         buf = xmalloc(st.st_size + 1);
337         len = read_in_full(fd, buf, st.st_size);
338         close(fd);
339         if (len != st.st_size)
340                 die("Error reading %s", path);
341         buf[len] = '\0';
342         if (prefixcmp(buf, "gitdir: "))
343                 die("Invalid gitfile format: %s", path);
344         while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
345                 len--;
346         if (len < 9)
347                 die("No path in gitfile: %s", path);
348         buf[len] = '\0';
349         if (!is_git_directory(buf + 8))
350                 die("Not a git repository: %s", buf + 8);
351         path = make_absolute_path(buf + 8);
352         free(buf);
353         return path;
356 /*
357  * We cannot decide in this function whether we are in the work tree or
358  * not, since the config can only be read _after_ this function was called.
359  */
360 const char *setup_git_directory_gently(int *nongit_ok)
362         const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
363         static char cwd[PATH_MAX+1];
364         const char *gitdirenv;
365         const char *gitfile_dir;
366         int len, offset;
368         /*
369          * Let's assume that we are in a git repository.
370          * If it turns out later that we are somewhere else, the value will be
371          * updated accordingly.
372          */
373         if (nongit_ok)
374                 *nongit_ok = 0;
376         /*
377          * If GIT_DIR is set explicitly, we're not going
378          * to do any discovery, but we still do repository
379          * validation.
380          */
381         gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
382         if (gitdirenv) {
383                 if (PATH_MAX - 40 < strlen(gitdirenv))
384                         die("'$%s' too big", GIT_DIR_ENVIRONMENT);
385                 if (is_git_directory(gitdirenv)) {
386                         static char buffer[1024 + 1];
387                         const char *retval;
389                         if (!work_tree_env) {
390                                 retval = set_work_tree(gitdirenv);
391                                 /* config may override worktree */
392                                 if (check_repository_format_gently(nongit_ok))
393                                         return NULL;
394                                 return retval;
395                         }
396                         if (check_repository_format_gently(nongit_ok))
397                                 return NULL;
398                         retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
399                                         get_git_work_tree());
400                         if (!retval || !*retval)
401                                 return NULL;
402                         set_git_dir(make_absolute_path(gitdirenv));
403                         if (chdir(work_tree_env) < 0)
404                                 die ("Could not chdir to %s", work_tree_env);
405                         strcat(buffer, "/");
406                         return retval;
407                 }
408                 if (nongit_ok) {
409                         *nongit_ok = 1;
410                         return NULL;
411                 }
412                 die("Not a git repository: '%s'", gitdirenv);
413         }
415         if (!getcwd(cwd, sizeof(cwd)-1))
416                 die("Unable to read current working directory");
418         /*
419          * Test in the following order (relative to the cwd):
420          * - .git (file containing "gitdir: <path>")
421          * - .git/
422          * - ./ (bare)
423          * - ../.git
424          * - ../.git/
425          * - ../ (bare)
426          * - ../../.git/
427          *   etc.
428          */
429         offset = len = strlen(cwd);
430         for (;;) {
431                 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
432                 if (gitfile_dir) {
433                         if (set_git_dir(gitfile_dir))
434                                 die("Repository setup failed");
435                         break;
436                 }
437                 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
438                         break;
439                 if (is_git_directory(".")) {
440                         inside_git_dir = 1;
441                         if (!work_tree_env)
442                                 inside_work_tree = 0;
443                         setenv(GIT_DIR_ENVIRONMENT, ".", 1);
444                         check_repository_format_gently(nongit_ok);
445                         return NULL;
446                 }
447                 chdir("..");
448                 do {
449                         if (!offset) {
450                                 if (nongit_ok) {
451                                         if (chdir(cwd))
452                                                 die("Cannot come back to cwd");
453                                         *nongit_ok = 1;
454                                         return NULL;
455                                 }
456                                 die("Not a git repository");
457                         }
458                 } while (cwd[--offset] != '/');
459         }
461         inside_git_dir = 0;
462         if (!work_tree_env)
463                 inside_work_tree = 1;
464         git_work_tree_cfg = xstrndup(cwd, offset);
465         if (check_repository_format_gently(nongit_ok))
466                 return NULL;
467         if (offset == len)
468                 return NULL;
470         /* Make "offset" point to past the '/', and add a '/' at the end */
471         offset++;
472         cwd[len++] = '/';
473         cwd[len] = 0;
474         return cwd + offset;
477 int git_config_perm(const char *var, const char *value)
479         int i;
480         char *endptr;
482         if (value == NULL)
483                 return PERM_GROUP;
485         if (!strcmp(value, "umask"))
486                 return PERM_UMASK;
487         if (!strcmp(value, "group"))
488                 return PERM_GROUP;
489         if (!strcmp(value, "all") ||
490             !strcmp(value, "world") ||
491             !strcmp(value, "everybody"))
492                 return PERM_EVERYBODY;
494         /* Parse octal numbers */
495         i = strtol(value, &endptr, 8);
497         /* If not an octal number, maybe true/false? */
498         if (*endptr != 0)
499                 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
501         /*
502          * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
503          * a chmod value.
504          */
505         switch (i) {
506         case PERM_UMASK:               /* 0 */
507                 return PERM_UMASK;
508         case OLD_PERM_GROUP:           /* 1 */
509                 return PERM_GROUP;
510         case OLD_PERM_EVERYBODY:       /* 2 */
511                 return PERM_EVERYBODY;
512         }
514         /* A filemode value was given: 0xxx */
516         if ((i & 0600) != 0600)
517                 die("Problem with core.sharedRepository filemode value "
518                     "(0%.3o).\nThe owner of files must always have "
519                     "read and write permissions.", i);
521         /*
522          * Mask filemode value. Others can not get write permission.
523          * x flags for directories are handled separately.
524          */
525         return i & 0666;
528 int check_repository_format_version(const char *var, const char *value, void *cb)
530         if (strcmp(var, "core.repositoryformatversion") == 0)
531                 repository_format_version = git_config_int(var, value);
532         else if (strcmp(var, "core.sharedrepository") == 0)
533                 shared_repository = git_config_perm(var, value);
534         else if (strcmp(var, "core.bare") == 0) {
535                 is_bare_repository_cfg = git_config_bool(var, value);
536                 if (is_bare_repository_cfg == 1)
537                         inside_work_tree = -1;
538         } else if (strcmp(var, "core.worktree") == 0) {
539                 if (!value)
540                         return config_error_nonbool(var);
541                 free(git_work_tree_cfg);
542                 git_work_tree_cfg = xstrdup(value);
543                 inside_work_tree = -1;
544         }
545         return 0;
548 int check_repository_format(void)
550         return check_repository_format_gently(NULL);
553 const char *setup_git_directory(void)
555         const char *retval = setup_git_directory_gently(NULL);
557         /* If the work tree is not the default one, recompute prefix */
558         if (inside_work_tree < 0) {
559                 static char buffer[PATH_MAX + 1];
560                 char *rel;
561                 if (retval && chdir(retval))
562                         die ("Could not jump back into original cwd");
563                 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
564                 return rel && *rel ? strcat(rel, "/") : NULL;
565         }
567         return retval;