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