Handle relative paths in submodule .git files
[git/mingw.git] / setup.c
blob7fc42517136955f7748855818999eaaeec9160bf
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)
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);
18 if (normalize_path_copy(sanitized, sanitized))
19 goto error_out;
20 if (is_absolute_path(orig)) {
21 size_t 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 total = strlen(sanitized) + 1;
27 if (strncmp(sanitized, work_tree, len) ||
28 (sanitized[len] != '\0' && sanitized[len] != '/')) {
29 error_out:
30 die("'%s' is outside repository", orig);
32 if (sanitized[len] == '/')
33 len++;
34 memmove(sanitized, sanitized + len, total - len);
36 return sanitized;
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.
44 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
46 static char path[PATH_MAX];
47 #ifndef WIN32
48 if (!pfx || !*pfx || is_absolute_path(arg))
49 return arg;
50 memcpy(path, pfx, pfx_len);
51 strcpy(path + pfx_len, arg);
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
64 return path;
67 int check_filename(const char *prefix, const char *arg)
69 const char *name;
70 struct stat st;
72 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
73 if (!lstat(name, &st))
74 return 1; /* file exists */
75 if (errno == ENOENT || errno == ENOTDIR)
76 return 0; /* file does not exist */
77 die_errno("failed to stat '%s'", arg);
81 * Verify a filename that we got as an argument for a pathspec
82 * entry. Note that a filename that begins with "-" never verifies
83 * as true, because even if such a filename were to exist, we want
84 * it to be preceded by the "--" marker (or we want the user to
85 * use a format like "./-filename")
87 void verify_filename(const char *prefix, const char *arg)
89 if (*arg == '-')
90 die("bad flag '%s' used after filename", arg);
91 if (check_filename(prefix, arg))
92 return;
93 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
94 "Use '--' to separate paths from revisions", arg);
98 * Opposite of the above: the command line did not have -- marker
99 * and we parsed the arg as a refname. It should not be interpretable
100 * as a filename.
102 void verify_non_filename(const char *prefix, const char *arg)
104 if (!is_inside_work_tree() || is_inside_git_dir())
105 return;
106 if (*arg == '-')
107 return; /* flag */
108 if (!check_filename(prefix, arg))
109 return;
110 die("ambiguous argument '%s': both revision and filename\n"
111 "Use '--' to separate filenames from revisions", arg);
114 const char **get_pathspec(const char *prefix, const char **pathspec)
116 const char *entry = *pathspec;
117 const char **src, **dst;
118 int prefixlen;
120 if (!prefix && !entry)
121 return NULL;
123 if (!entry) {
124 static const char *spec[2];
125 spec[0] = prefix;
126 spec[1] = NULL;
127 return spec;
130 /* Otherwise we have to re-write the entries.. */
131 src = pathspec;
132 dst = pathspec;
133 prefixlen = prefix ? strlen(prefix) : 0;
134 while (*src) {
135 const char *p = prefix_path(prefix, prefixlen, *src);
136 *(dst++) = p;
137 src++;
139 *dst = NULL;
140 if (!*pathspec)
141 return NULL;
142 return pathspec;
146 * Test if it looks like we're at a git directory.
147 * We want to see:
149 * - either an objects/ directory _or_ the proper
150 * GIT_OBJECT_DIRECTORY environment variable
151 * - a refs/ directory
152 * - either a HEAD symlink or a HEAD file that is formatted as
153 * a proper "ref:", or a regular file HEAD that has a properly
154 * formatted sha1 object name.
156 static int is_git_directory(const char *suspect)
158 char path[PATH_MAX];
159 size_t len = strlen(suspect);
161 strcpy(path, suspect);
162 if (getenv(DB_ENVIRONMENT)) {
163 if (access(getenv(DB_ENVIRONMENT), X_OK))
164 return 0;
166 else {
167 strcpy(path + len, "/objects");
168 if (access(path, X_OK))
169 return 0;
172 strcpy(path + len, "/refs");
173 if (access(path, X_OK))
174 return 0;
176 strcpy(path + len, "/HEAD");
177 if (validate_headref(path))
178 return 0;
180 return 1;
183 int is_inside_git_dir(void)
185 if (inside_git_dir < 0)
186 inside_git_dir = is_inside_dir(get_git_dir());
187 return inside_git_dir;
190 int is_inside_work_tree(void)
192 if (inside_work_tree < 0)
193 inside_work_tree = is_inside_dir(get_git_work_tree());
194 return inside_work_tree;
198 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
199 * The old behaviour (which we retain here) is to set the work tree root
200 * to the cwd, unless overridden by the config, the command line, or
201 * GIT_WORK_TREE.
203 static const char *set_work_tree(const char *dir)
205 char buffer[PATH_MAX + 1];
207 if (!getcwd(buffer, sizeof(buffer)))
208 die ("Could not get the current working directory");
209 git_work_tree_cfg = xstrdup(buffer);
210 inside_work_tree = 1;
212 return NULL;
215 void setup_work_tree(void)
217 const char *work_tree, *git_dir;
218 static int initialized = 0;
220 if (initialized)
221 return;
222 work_tree = get_git_work_tree();
223 git_dir = get_git_dir();
224 if (!is_absolute_path(git_dir))
225 git_dir = make_absolute_path(git_dir);
226 if (!work_tree || chdir(work_tree))
227 die("This operation must be run in a work tree");
228 set_git_dir(make_relative_path(git_dir, work_tree));
229 initialized = 1;
232 static int check_repository_format_gently(int *nongit_ok)
234 git_config(check_repository_format_version, NULL);
235 if (GIT_REPO_VERSION < repository_format_version) {
236 if (!nongit_ok)
237 die ("Expected git repo version <= %d, found %d",
238 GIT_REPO_VERSION, repository_format_version);
239 warning("Expected git repo version <= %d, found %d",
240 GIT_REPO_VERSION, repository_format_version);
241 warning("Please upgrade Git");
242 *nongit_ok = -1;
243 return -1;
245 return 0;
249 * Try to read the location of the git directory from the .git file,
250 * return path to git directory if found.
252 const char *read_gitfile_gently(const char *path)
254 char *buf;
255 char *dir;
256 const char *slash;
257 struct stat st;
258 int fd;
259 size_t len;
261 if (stat(path, &st))
262 return NULL;
263 if (!S_ISREG(st.st_mode))
264 return NULL;
265 fd = open(path, O_RDONLY);
266 if (fd < 0)
267 die_errno("Error opening '%s'", path);
268 buf = xmalloc(st.st_size + 1);
269 len = read_in_full(fd, buf, st.st_size);
270 close(fd);
271 if (len != st.st_size)
272 die("Error reading %s", path);
273 buf[len] = '\0';
274 if (prefixcmp(buf, "gitdir: "))
275 die("Invalid gitfile format: %s", path);
276 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
277 len--;
278 if (len < 9)
279 die("No path in gitfile: %s", path);
280 buf[len] = '\0';
281 dir = buf + 8;
283 if (!is_absolute_path(dir) && (slash = strrchr(path, '/'))) {
284 size_t pathlen = slash+1 - path;
285 size_t dirlen = pathlen + len - 8;
286 dir = xmalloc(dirlen + 1);
287 strncpy(dir, path, pathlen);
288 strncpy(dir + pathlen, buf + 8, len - 8);
289 dir[dirlen] = '\0';
290 free(buf);
291 buf = dir;
294 if (!is_git_directory(dir))
295 die("Not a git repository: %s", dir);
296 path = make_absolute_path(dir);
298 free(buf);
299 return path;
303 * We cannot decide in this function whether we are in the work tree or
304 * not, since the config can only be read _after_ this function was called.
306 const char *setup_git_directory_gently(int *nongit_ok)
308 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
309 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
310 static char cwd[PATH_MAX+1];
311 const char *gitdirenv;
312 const char *gitfile_dir;
313 int len, offset, ceil_offset;
316 * Let's assume that we are in a git repository.
317 * If it turns out later that we are somewhere else, the value will be
318 * updated accordingly.
320 if (nongit_ok)
321 *nongit_ok = 0;
324 * If GIT_DIR is set explicitly, we're not going
325 * to do any discovery, but we still do repository
326 * validation.
328 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
329 if (gitdirenv) {
330 if (PATH_MAX - 40 < strlen(gitdirenv))
331 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
332 if (is_git_directory(gitdirenv)) {
333 static char buffer[1024 + 1];
334 const char *retval;
336 if (!work_tree_env) {
337 retval = set_work_tree(gitdirenv);
338 /* config may override worktree */
339 if (check_repository_format_gently(nongit_ok))
340 return NULL;
341 return retval;
343 if (check_repository_format_gently(nongit_ok))
344 return NULL;
345 retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
346 get_git_work_tree());
347 if (!retval || !*retval)
348 return NULL;
349 set_git_dir(make_absolute_path(gitdirenv));
350 if (chdir(work_tree_env) < 0)
351 die_errno ("Could not chdir to '%s'", work_tree_env);
352 strcat(buffer, "/");
353 return retval;
355 if (nongit_ok) {
356 *nongit_ok = 1;
357 return NULL;
359 die("Not a git repository: '%s'", gitdirenv);
362 if (!getcwd(cwd, sizeof(cwd)-1))
363 die_errno("Unable to read current working directory");
365 ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
366 if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
367 ceil_offset = 1;
370 * Test in the following order (relative to the cwd):
371 * - .git (file containing "gitdir: <path>")
372 * - .git/
373 * - ./ (bare)
374 * - ../.git
375 * - ../.git/
376 * - ../ (bare)
377 * - ../../.git/
378 * etc.
380 offset = len = strlen(cwd);
381 for (;;) {
382 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
383 if (gitfile_dir) {
384 if (set_git_dir(gitfile_dir))
385 die("Repository setup failed");
386 break;
388 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
389 break;
390 if (is_git_directory(".")) {
391 inside_git_dir = 1;
392 if (!work_tree_env)
393 inside_work_tree = 0;
394 if (offset != len) {
395 cwd[offset] = '\0';
396 setenv(GIT_DIR_ENVIRONMENT, cwd, 1);
397 } else
398 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
399 check_repository_format_gently(nongit_ok);
400 return NULL;
402 while (--offset > ceil_offset && cwd[offset] != '/');
403 if (offset <= ceil_offset) {
404 if (nongit_ok) {
405 if (chdir(cwd))
406 die_errno("Cannot come back to cwd");
407 *nongit_ok = 1;
408 return NULL;
410 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
412 if (chdir(".."))
413 die_errno("Cannot change to '%s/..'", cwd);
416 inside_git_dir = 0;
417 if (!work_tree_env)
418 inside_work_tree = 1;
419 git_work_tree_cfg = xstrndup(cwd, offset);
420 if (check_repository_format_gently(nongit_ok))
421 return NULL;
422 if (offset == len)
423 return NULL;
425 /* Make "offset" point to past the '/', and add a '/' at the end */
426 offset++;
427 cwd[len++] = '/';
428 cwd[len] = 0;
429 return cwd + offset;
432 int git_config_perm(const char *var, const char *value)
434 int i;
435 char *endptr;
437 if (value == NULL)
438 return PERM_GROUP;
440 if (!strcmp(value, "umask"))
441 return PERM_UMASK;
442 if (!strcmp(value, "group"))
443 return PERM_GROUP;
444 if (!strcmp(value, "all") ||
445 !strcmp(value, "world") ||
446 !strcmp(value, "everybody"))
447 return PERM_EVERYBODY;
449 /* Parse octal numbers */
450 i = strtol(value, &endptr, 8);
452 /* If not an octal number, maybe true/false? */
453 if (*endptr != 0)
454 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
457 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
458 * a chmod value to restrict to.
460 switch (i) {
461 case PERM_UMASK: /* 0 */
462 return PERM_UMASK;
463 case OLD_PERM_GROUP: /* 1 */
464 return PERM_GROUP;
465 case OLD_PERM_EVERYBODY: /* 2 */
466 return PERM_EVERYBODY;
469 /* A filemode value was given: 0xxx */
471 if ((i & 0600) != 0600)
472 die("Problem with core.sharedRepository filemode value "
473 "(0%.3o).\nThe owner of files must always have "
474 "read and write permissions.", i);
477 * Mask filemode value. Others can not get write permission.
478 * x flags for directories are handled separately.
480 return -(i & 0666);
483 int check_repository_format_version(const char *var, const char *value, void *cb)
485 if (strcmp(var, "core.repositoryformatversion") == 0)
486 repository_format_version = git_config_int(var, value);
487 else if (strcmp(var, "core.sharedrepository") == 0)
488 shared_repository = git_config_perm(var, value);
489 else if (strcmp(var, "core.bare") == 0) {
490 is_bare_repository_cfg = git_config_bool(var, value);
491 if (is_bare_repository_cfg == 1)
492 inside_work_tree = -1;
493 } else if (strcmp(var, "core.worktree") == 0) {
494 if (!value)
495 return config_error_nonbool(var);
496 free(git_work_tree_cfg);
497 git_work_tree_cfg = xstrdup(value);
498 inside_work_tree = -1;
500 return 0;
503 int check_repository_format(void)
505 return check_repository_format_gently(NULL);
508 const char *setup_git_directory(void)
510 const char *retval = setup_git_directory_gently(NULL);
512 /* If the work tree is not the default one, recompute prefix */
513 if (inside_work_tree < 0) {
514 static char buffer[PATH_MAX + 1];
515 char *rel;
516 if (retval && chdir(retval))
517 die_errno ("Could not jump back into original cwd");
518 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
519 if (rel && *rel && chdir(get_git_work_tree()))
520 die_errno ("Could not jump to working directory");
521 return rel && *rel ? strcat(rel, "/") : NULL;
524 return retval;