worktree: don't segfault with an absolute pathspec without a work tree
[git/git.git] / setup.c
CommitLineData
d288a700 1#include "cache.h"
e90fdc39
JS
2#include "dir.h"
3
4static int inside_git_dir = -1;
5static int inside_work_tree = -1;
d288a700 6
d089ebaa
JH
7const 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);
9a13ba1b 11 if (is_absolute_path(orig))
d089ebaa
JH
12 strcpy(sanitized, path);
13 else {
14 if (len)
15 memcpy(sanitized, prefix, len);
16 strcpy(sanitized + len, path);
f332726e 17 }
f3cad0ad 18 if (normalize_path_copy(sanitized, sanitized))
d089ebaa 19 goto error_out;
9a13ba1b 20 if (is_absolute_path(orig)) {
b3100fd5 21 size_t len, total;
d089ebaa 22 const char *work_tree = get_git_work_tree();
b3100fd5
JH
23 if (!work_tree)
24 goto error_out;
25 len = strlen(work_tree);
26 total = strlen(sanitized) + 1;
d089ebaa
JH
27 if (strncmp(sanitized, work_tree, len) ||
28 (sanitized[len] != '\0' && sanitized[len] != '/')) {
29 error_out:
62525ef7 30 die("'%s' is outside repository", orig);
d089ebaa
JH
31 }
32 if (sanitized[len] == '/')
33 len++;
34 memmove(sanitized, sanitized + len, total - len);
35 }
36 return sanitized;
f332726e
LT
37}
38
a6080a0a 39/*
4ca06608
JH
40 * Unlike prefix_path, this should be used if the named file does
41 * not have to interact with index entry; i.e. name of a random file
42 * on the filesystem.
43 */
44const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
45{
46 static char path[PATH_MAX];
71064e3f 47#ifndef WIN32
ecf4831d 48 if (!pfx || !*pfx || is_absolute_path(arg))
4ca06608
JH
49 return arg;
50 memcpy(path, pfx, pfx_len);
51 strcpy(path + pfx_len, arg);
25fe217b
JS
52#else
53 char *p;
54 /* don't add prefix to absolute paths, but still replace '\' by '/' */
55 if (is_absolute_path(arg))
56 pfx_len = 0;
57 else
58 memcpy(path, pfx, pfx_len);
59 strcpy(path + pfx_len, arg);
60 for (p = path + pfx_len; *p; p++)
61 if (*p == '\\')
62 *p = '/';
63#endif
4ca06608
JH
64 return path;
65}
66
e23d0b4a
LT
67/*
68 * Verify a filename that we got as an argument for a pathspec
69 * entry. Note that a filename that begins with "-" never verifies
70 * as true, because even if such a filename were to exist, we want
71 * it to be preceded by the "--" marker (or we want the user to
72 * use a format like "./-filename")
73 */
74void verify_filename(const char *prefix, const char *arg)
75{
76 const char *name;
77 struct stat st;
78
79 if (*arg == '-')
80 die("bad flag '%s' used after filename", arg);
81 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
82 if (!lstat(name, &st))
83 return;
84 if (errno == ENOENT)
ea92f41f
JH
85 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
86 "Use '--' to separate paths from revisions", arg);
d824cbba 87 die_errno("failed to stat '%s'", arg);
e23d0b4a
LT
88}
89
ea92f41f
JH
90/*
91 * Opposite of the above: the command line did not have -- marker
92 * and we parsed the arg as a refname. It should not be interpretable
93 * as a filename.
94 */
95void verify_non_filename(const char *prefix, const char *arg)
96{
97 const char *name;
98 struct stat st;
99
7ae3df8c 100 if (!is_inside_work_tree() || is_inside_git_dir())
68025633 101 return;
ea92f41f
JH
102 if (*arg == '-')
103 return; /* flag */
104 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
105 if (!lstat(name, &st))
106 die("ambiguous argument '%s': both revision and filename\n"
107 "Use '--' to separate filenames from revisions", arg);
33a798c8 108 if (errno != ENOENT && errno != ENOTDIR)
d824cbba 109 die_errno("failed to stat '%s'", arg);
ea92f41f
JH
110}
111
6b5ee137 112const char **get_pathspec(const char *prefix, const char **pathspec)
d288a700 113{
6b5ee137 114 const char *entry = *pathspec;
d089ebaa 115 const char **src, **dst;
d288a700
LT
116 int prefixlen;
117
f332726e
LT
118 if (!prefix && !entry)
119 return NULL;
d288a700
LT
120
121 if (!entry) {
122 static const char *spec[2];
123 spec[0] = prefix;
124 spec[1] = NULL;
125 return spec;
126 }
127
128 /* Otherwise we have to re-write the entries.. */
d089ebaa
JH
129 src = pathspec;
130 dst = pathspec;
f332726e 131 prefixlen = prefix ? strlen(prefix) : 0;
d089ebaa
JH
132 while (*src) {
133 const char *p = prefix_path(prefix, prefixlen, *src);
62525ef7 134 *(dst++) = p;
d089ebaa
JH
135 src++;
136 }
137 *dst = NULL;
138 if (!*pathspec)
139 return NULL;
140 return pathspec;
d288a700
LT
141}
142
5f5608bc 143/*
ad1a382f 144 * Test if it looks like we're at a git directory.
5e7bfe25 145 * We want to see:
5f5608bc 146 *
790296fd 147 * - either an objects/ directory _or_ the proper
5f5608bc 148 * GIT_OBJECT_DIRECTORY environment variable
ad1a382f 149 * - a refs/ directory
8098a178 150 * - either a HEAD symlink or a HEAD file that is formatted as
c847f537
JH
151 * a proper "ref:", or a regular file HEAD that has a properly
152 * formatted sha1 object name.
5f5608bc 153 */
ad1a382f 154static int is_git_directory(const char *suspect)
5f5608bc 155{
ad1a382f
SP
156 char path[PATH_MAX];
157 size_t len = strlen(suspect);
158
159 strcpy(path, suspect);
160 if (getenv(DB_ENVIRONMENT)) {
161 if (access(getenv(DB_ENVIRONMENT), X_OK))
162 return 0;
163 }
164 else {
165 strcpy(path + len, "/objects");
166 if (access(path, X_OK))
167 return 0;
168 }
169
170 strcpy(path + len, "/refs");
171 if (access(path, X_OK))
8098a178 172 return 0;
ad1a382f
SP
173
174 strcpy(path + len, "/HEAD");
c847f537 175 if (validate_headref(path))
ad1a382f
SP
176 return 0;
177
8098a178 178 return 1;
5f5608bc
LT
179}
180
68025633
JS
181int is_inside_git_dir(void)
182{
e90fdc39
JS
183 if (inside_git_dir < 0)
184 inside_git_dir = is_inside_dir(get_git_dir());
185 return inside_git_dir;
892c41b9
ML
186}
187
892c41b9
ML
188int is_inside_work_tree(void)
189{
e90fdc39
JS
190 if (inside_work_tree < 0)
191 inside_work_tree = is_inside_dir(get_git_work_tree());
192 return inside_work_tree;
892c41b9
ML
193}
194
e90fdc39 195/*
7efeb8f0
JS
196 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
197 * The old behaviour (which we retain here) is to set the work tree root
198 * to the cwd, unless overridden by the config, the command line, or
199 * GIT_WORK_TREE.
e90fdc39 200 */
7efeb8f0 201static const char *set_work_tree(const char *dir)
892c41b9 202{
7efeb8f0 203 char buffer[PATH_MAX + 1];
e90fdc39 204
7efeb8f0
JS
205 if (!getcwd(buffer, sizeof(buffer)))
206 die ("Could not get the current working directory");
207 git_work_tree_cfg = xstrdup(buffer);
e90fdc39
JS
208 inside_work_tree = 1;
209
7efeb8f0 210 return NULL;
68025633
JS
211}
212
f3fa1838
JH
213void setup_work_tree(void)
214{
354e6534
JS
215 const char *work_tree, *git_dir;
216 static int initialized = 0;
217
218 if (initialized)
219 return;
220 work_tree = get_git_work_tree();
221 git_dir = get_git_dir();
59f0f2f3 222 if (!is_absolute_path(git_dir))
044bbbcb 223 git_dir = make_absolute_path(git_dir);
59f0f2f3
MH
224 if (!work_tree || chdir(work_tree))
225 die("This operation must be run in a work tree");
044bbbcb 226 set_git_dir(make_relative_path(git_dir, work_tree));
354e6534 227 initialized = 1;
59f0f2f3
MH
228}
229
9459aa77
NTND
230static int check_repository_format_gently(int *nongit_ok)
231{
ef90d6d4 232 git_config(check_repository_format_version, NULL);
9459aa77
NTND
233 if (GIT_REPO_VERSION < repository_format_version) {
234 if (!nongit_ok)
235 die ("Expected git repo version <= %d, found %d",
236 GIT_REPO_VERSION, repository_format_version);
237 warning("Expected git repo version <= %d, found %d",
238 GIT_REPO_VERSION, repository_format_version);
239 warning("Please upgrade Git");
240 *nongit_ok = -1;
241 return -1;
242 }
243 return 0;
244}
245
b44ebb19
LH
246/*
247 * Try to read the location of the git directory from the .git file,
248 * return path to git directory if found.
249 */
250const char *read_gitfile_gently(const char *path)
251{
252 char *buf;
253 struct stat st;
254 int fd;
255 size_t len;
256
257 if (stat(path, &st))
258 return NULL;
259 if (!S_ISREG(st.st_mode))
260 return NULL;
261 fd = open(path, O_RDONLY);
262 if (fd < 0)
d824cbba 263 die_errno("Error opening '%s'", path);
b44ebb19
LH
264 buf = xmalloc(st.st_size + 1);
265 len = read_in_full(fd, buf, st.st_size);
266 close(fd);
267 if (len != st.st_size)
268 die("Error reading %s", path);
269 buf[len] = '\0';
270 if (prefixcmp(buf, "gitdir: "))
271 die("Invalid gitfile format: %s", path);
272 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
273 len--;
274 if (len < 9)
275 die("No path in gitfile: %s", path);
276 buf[len] = '\0';
277 if (!is_git_directory(buf + 8))
278 die("Not a git repository: %s", buf + 8);
279 path = make_absolute_path(buf + 8);
280 free(buf);
281 return path;
282}
283
e90fdc39
JS
284/*
285 * We cannot decide in this function whether we are in the work tree or
286 * not, since the config can only be read _after_ this function was called.
287 */
4ca06608 288const char *setup_git_directory_gently(int *nongit_ok)
d288a700 289{
e90fdc39 290 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
0454dd93 291 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
d288a700 292 static char cwd[PATH_MAX+1];
e90fdc39 293 const char *gitdirenv;
b44ebb19 294 const char *gitfile_dir;
0454dd93 295 int len, offset, ceil_offset;
d288a700 296
af05d679
SG
297 /*
298 * Let's assume that we are in a git repository.
299 * If it turns out later that we are somewhere else, the value will be
300 * updated accordingly.
301 */
302 if (nongit_ok)
303 *nongit_ok = 0;
304
e90fdc39
JS
305 /*
306 * If GIT_DIR is set explicitly, we're not going
307 * to do any discovery, but we still do repository
308 * validation.
309 */
ad1a382f 310 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
e90fdc39
JS
311 if (gitdirenv) {
312 if (PATH_MAX - 40 < strlen(gitdirenv))
313 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
314 if (is_git_directory(gitdirenv)) {
dd5c8af1
JS
315 static char buffer[1024 + 1];
316 const char *retval;
317
138dd1e9
NTND
318 if (!work_tree_env) {
319 retval = set_work_tree(gitdirenv);
9459aa77
NTND
320 /* config may override worktree */
321 if (check_repository_format_gently(nongit_ok))
322 return NULL;
138dd1e9
NTND
323 return retval;
324 }
9459aa77
NTND
325 if (check_repository_format_gently(nongit_ok))
326 return NULL;
dd5c8af1
JS
327 retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
328 get_git_work_tree());
329 if (!retval || !*retval)
330 return NULL;
331 set_git_dir(make_absolute_path(gitdirenv));
332 if (chdir(work_tree_env) < 0)
0721c314 333 die_errno ("Could not chdir to '%s'", work_tree_env);
dd5c8af1
JS
334 strcat(buffer, "/");
335 return retval;
892c41b9 336 }
3a3c3fc4 337 if (nongit_ok) {
41e95f69
ML
338 *nongit_ok = 1;
339 return NULL;
340 }
ad1a382f 341 die("Not a git repository: '%s'", gitdirenv);
5e7bfe25 342 }
d288a700 343
f66a4d68 344 if (!getcwd(cwd, sizeof(cwd)-1))
0721c314 345 die_errno("Unable to read current working directory");
d288a700 346
0454dd93 347 ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
17d778e7
JH
348 if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
349 ceil_offset = 1;
d288a700 350
892c41b9 351 /*
e90fdc39 352 * Test in the following order (relative to the cwd):
b44ebb19 353 * - .git (file containing "gitdir: <path>")
e90fdc39
JS
354 * - .git/
355 * - ./ (bare)
b44ebb19 356 * - ../.git
e90fdc39
JS
357 * - ../.git/
358 * - ../ (bare)
359 * - ../../.git/
360 * etc.
892c41b9 361 */
e90fdc39
JS
362 offset = len = strlen(cwd);
363 for (;;) {
b44ebb19
LH
364 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
365 if (gitfile_dir) {
366 if (set_git_dir(gitfile_dir))
367 die("Repository setup failed");
368 break;
369 }
e90fdc39
JS
370 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
371 break;
372 if (is_git_directory(".")) {
373 inside_git_dir = 1;
374 if (!work_tree_env)
375 inside_work_tree = 0;
72183cb2
SG
376 if (offset != len) {
377 cwd[offset] = '\0';
378 setenv(GIT_DIR_ENVIRONMENT, cwd, 1);
379 } else
380 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
9459aa77 381 check_repository_format_gently(nongit_ok);
892c41b9
ML
382 return NULL;
383 }
0454dd93
DR
384 while (--offset > ceil_offset && cwd[offset] != '/');
385 if (offset <= ceil_offset) {
386 if (nongit_ok) {
387 if (chdir(cwd))
0721c314 388 die_errno("Cannot come back to cwd");
0454dd93
DR
389 *nongit_ok = 1;
390 return NULL;
e90fdc39 391 }
f66bc5f9 392 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
0454dd93 393 }
7be77de2 394 if (chdir(".."))
d824cbba 395 die_errno("Cannot change to '%s/..'", cwd);
892c41b9
ML
396 }
397
e90fdc39
JS
398 inside_git_dir = 0;
399 if (!work_tree_env)
400 inside_work_tree = 1;
401 git_work_tree_cfg = xstrndup(cwd, offset);
9459aa77
NTND
402 if (check_repository_format_gently(nongit_ok))
403 return NULL;
e90fdc39 404 if (offset == len)
d288a700
LT
405 return NULL;
406
e90fdc39
JS
407 /* Make "offset" point to past the '/', and add a '/' at the end */
408 offset++;
409 cwd[len++] = '/';
410 cwd[len] = 0;
411 return cwd + offset;
d288a700 412}
5e7bfe25 413
94df2506
JH
414int git_config_perm(const char *var, const char *value)
415{
06cbe855
HO
416 int i;
417 char *endptr;
418
419 if (value == NULL)
420 return PERM_GROUP;
421
422 if (!strcmp(value, "umask"))
423 return PERM_UMASK;
424 if (!strcmp(value, "group"))
425 return PERM_GROUP;
426 if (!strcmp(value, "all") ||
427 !strcmp(value, "world") ||
428 !strcmp(value, "everybody"))
429 return PERM_EVERYBODY;
430
431 /* Parse octal numbers */
432 i = strtol(value, &endptr, 8);
433
434 /* If not an octal number, maybe true/false? */
435 if (*endptr != 0)
436 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
437
438 /*
439 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
5a688fe4 440 * a chmod value to restrict to.
06cbe855
HO
441 */
442 switch (i) {
443 case PERM_UMASK: /* 0 */
444 return PERM_UMASK;
445 case OLD_PERM_GROUP: /* 1 */
446 return PERM_GROUP;
447 case OLD_PERM_EVERYBODY: /* 2 */
448 return PERM_EVERYBODY;
94df2506 449 }
06cbe855
HO
450
451 /* A filemode value was given: 0xxx */
452
453 if ((i & 0600) != 0600)
454 die("Problem with core.sharedRepository filemode value "
455 "(0%.3o).\nThe owner of files must always have "
456 "read and write permissions.", i);
457
458 /*
459 * Mask filemode value. Others can not get write permission.
460 * x flags for directories are handled separately.
461 */
5a688fe4 462 return -(i & 0666);
94df2506
JH
463}
464
ef90d6d4 465int check_repository_format_version(const char *var, const char *value, void *cb)
ab9cb76f 466{
299726d5
JS
467 if (strcmp(var, "core.repositoryformatversion") == 0)
468 repository_format_version = git_config_int(var, value);
457f06d6 469 else if (strcmp(var, "core.sharedrepository") == 0)
94df2506 470 shared_repository = git_config_perm(var, value);
e90fdc39
JS
471 else if (strcmp(var, "core.bare") == 0) {
472 is_bare_repository_cfg = git_config_bool(var, value);
473 if (is_bare_repository_cfg == 1)
474 inside_work_tree = -1;
475 } else if (strcmp(var, "core.worktree") == 0) {
180483c5
JH
476 if (!value)
477 return config_error_nonbool(var);
8e0f7003 478 free(git_work_tree_cfg);
e90fdc39
JS
479 git_work_tree_cfg = xstrdup(value);
480 inside_work_tree = -1;
481 }
299726d5 482 return 0;
ab9cb76f
JH
483}
484
485int check_repository_format(void)
486{
9459aa77 487 return check_repository_format_gently(NULL);
ab9cb76f
JH
488}
489
5e7bfe25
JH
490const char *setup_git_directory(void)
491{
4ca06608 492 const char *retval = setup_git_directory_gently(NULL);
e90fdc39
JS
493
494 /* If the work tree is not the default one, recompute prefix */
495 if (inside_work_tree < 0) {
496 static char buffer[PATH_MAX + 1];
497 char *rel;
498 if (retval && chdir(retval))
0721c314 499 die_errno ("Could not jump back into original cwd");
e90fdc39 500 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
bb528633 501 if (rel && *rel && chdir(get_git_work_tree()))
0721c314 502 die_errno ("Could not jump to working directory");
e90fdc39
JS
503 return rel && *rel ? strcat(rel, "/") : NULL;
504 }
505
5e7bfe25
JH
506 return retval;
507}