Detailed diagnosis when parsing an object name fails.
[git/dscho.git] / setup.c
blob5792eb7ddfbe9a3e520dcf33081a6c098061d643
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 const char *work_tree = get_git_work_tree();
22 size_t len = strlen(work_tree);
23 size_t total = strlen(sanitized) + 1;
24 if (strncmp(sanitized, work_tree, len) ||
25 (sanitized[len] != '\0' && sanitized[len] != '/')) {
26 error_out:
27 die("'%s' is outside repository", orig);
29 if (sanitized[len] == '/')
30 len++;
31 memmove(sanitized, sanitized + len, total - len);
33 return sanitized;
37 * Unlike prefix_path, this should be used if the named file does
38 * not have to interact with index entry; i.e. name of a random file
39 * on the filesystem.
41 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
43 static char path[PATH_MAX];
44 #ifndef WIN32
45 if (!pfx || !*pfx || is_absolute_path(arg))
46 return arg;
47 memcpy(path, pfx, pfx_len);
48 strcpy(path + pfx_len, arg);
49 #else
50 char *p;
51 /* don't add prefix to absolute paths, but still replace '\' by '/' */
52 if (is_absolute_path(arg))
53 pfx_len = 0;
54 else
55 memcpy(path, pfx, pfx_len);
56 strcpy(path + pfx_len, arg);
57 for (p = path + pfx_len; *p; p++)
58 if (*p == '\\')
59 *p = '/';
60 #endif
61 return path;
64 int check_filename(const char *prefix, const char *arg)
66 const char *name;
67 struct stat st;
69 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
70 if (!lstat(name, &st))
71 return 1; /* file exists */
72 if (errno == ENOENT || errno == ENOTDIR)
73 return 0; /* file does not exist */
74 die_errno("failed to stat '%s'", arg);
77 static void NORETURN die_verify_filename(const char *prefix, const char *arg)
79 unsigned char sha1[20];
80 unsigned mode;
81 /* try a detailed diagnostic ... */
82 get_sha1_with_mode_1(arg, sha1, &mode, 0, prefix);
83 /* ... or fall back the most general message. */
84 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
85 "Use '--' to separate paths from revisions", arg);
90 * Verify a filename that we got as an argument for a pathspec
91 * entry. Note that a filename that begins with "-" never verifies
92 * as true, because even if such a filename were to exist, we want
93 * it to be preceded by the "--" marker (or we want the user to
94 * use a format like "./-filename")
96 void verify_filename(const char *prefix, const char *arg)
98 if (*arg == '-')
99 die("bad flag '%s' used after filename", arg);
100 if (check_filename(prefix, arg))
101 return;
102 die_verify_filename(prefix, arg);
106 * Opposite of the above: the command line did not have -- marker
107 * and we parsed the arg as a refname. It should not be interpretable
108 * as a filename.
110 void verify_non_filename(const char *prefix, const char *arg)
112 if (!is_inside_work_tree() || is_inside_git_dir())
113 return;
114 if (*arg == '-')
115 return; /* flag */
116 if (!check_filename(prefix, arg))
117 return;
118 die("ambiguous argument '%s': both revision and filename\n"
119 "Use '--' to separate filenames from revisions", arg);
122 const char **get_pathspec(const char *prefix, const char **pathspec)
124 const char *entry = *pathspec;
125 const char **src, **dst;
126 int prefixlen;
128 if (!prefix && !entry)
129 return NULL;
131 if (!entry) {
132 static const char *spec[2];
133 spec[0] = prefix;
134 spec[1] = NULL;
135 return spec;
138 /* Otherwise we have to re-write the entries.. */
139 src = pathspec;
140 dst = pathspec;
141 prefixlen = prefix ? strlen(prefix) : 0;
142 while (*src) {
143 const char *p = prefix_path(prefix, prefixlen, *src);
144 *(dst++) = p;
145 src++;
147 *dst = NULL;
148 if (!*pathspec)
149 return NULL;
150 return pathspec;
154 * Test if it looks like we're at a git directory.
155 * We want to see:
157 * - either an objects/ directory _or_ the proper
158 * GIT_OBJECT_DIRECTORY environment variable
159 * - a refs/ directory
160 * - either a HEAD symlink or a HEAD file that is formatted as
161 * a proper "ref:", or a regular file HEAD that has a properly
162 * formatted sha1 object name.
164 static int is_git_directory(const char *suspect)
166 char path[PATH_MAX];
167 size_t len = strlen(suspect);
169 strcpy(path, suspect);
170 if (getenv(DB_ENVIRONMENT)) {
171 if (access(getenv(DB_ENVIRONMENT), X_OK))
172 return 0;
174 else {
175 strcpy(path + len, "/objects");
176 if (access(path, X_OK))
177 return 0;
180 strcpy(path + len, "/refs");
181 if (access(path, X_OK))
182 return 0;
184 strcpy(path + len, "/HEAD");
185 if (validate_headref(path))
186 return 0;
188 return 1;
191 int is_inside_git_dir(void)
193 if (inside_git_dir < 0)
194 inside_git_dir = is_inside_dir(get_git_dir());
195 return inside_git_dir;
198 int is_inside_work_tree(void)
200 if (inside_work_tree < 0)
201 inside_work_tree = is_inside_dir(get_git_work_tree());
202 return inside_work_tree;
206 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
207 * The old behaviour (which we retain here) is to set the work tree root
208 * to the cwd, unless overridden by the config, the command line, or
209 * GIT_WORK_TREE.
211 static const char *set_work_tree(const char *dir)
213 char buffer[PATH_MAX + 1];
215 if (!getcwd(buffer, sizeof(buffer)))
216 die ("Could not get the current working directory");
217 git_work_tree_cfg = xstrdup(buffer);
218 inside_work_tree = 1;
220 return NULL;
223 void setup_work_tree(void)
225 const char *work_tree, *git_dir;
226 static int initialized = 0;
228 if (initialized)
229 return;
230 work_tree = get_git_work_tree();
231 git_dir = get_git_dir();
232 if (!is_absolute_path(git_dir))
233 git_dir = make_absolute_path(git_dir);
234 if (!work_tree || chdir(work_tree))
235 die("This operation must be run in a work tree");
236 set_git_dir(make_relative_path(git_dir, work_tree));
237 initialized = 1;
240 static int check_repository_format_gently(int *nongit_ok)
242 git_config(check_repository_format_version, NULL);
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;
253 return 0;
257 * Try to read the location of the git directory from the .git file,
258 * return path to git directory if found.
260 const char *read_gitfile_gently(const char *path)
262 char *buf;
263 struct stat st;
264 int fd;
265 size_t len;
267 if (stat(path, &st))
268 return NULL;
269 if (!S_ISREG(st.st_mode))
270 return NULL;
271 fd = open(path, O_RDONLY);
272 if (fd < 0)
273 die_errno("Error opening '%s'", path);
274 buf = xmalloc(st.st_size + 1);
275 len = read_in_full(fd, buf, st.st_size);
276 close(fd);
277 if (len != st.st_size)
278 die("Error reading %s", path);
279 buf[len] = '\0';
280 if (prefixcmp(buf, "gitdir: "))
281 die("Invalid gitfile format: %s", path);
282 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
283 len--;
284 if (len < 9)
285 die("No path in gitfile: %s", path);
286 buf[len] = '\0';
287 if (!is_git_directory(buf + 8))
288 die("Not a git repository: %s", buf + 8);
289 path = make_absolute_path(buf + 8);
290 free(buf);
291 return path;
295 * We cannot decide in this function whether we are in the work tree or
296 * not, since the config can only be read _after_ this function was called.
298 const char *setup_git_directory_gently(int *nongit_ok)
300 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
301 const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
302 static char cwd[PATH_MAX+1];
303 const char *gitdirenv;
304 const char *gitfile_dir;
305 int len, offset, ceil_offset;
308 * Let's assume that we are in a git repository.
309 * If it turns out later that we are somewhere else, the value will be
310 * updated accordingly.
312 if (nongit_ok)
313 *nongit_ok = 0;
316 * If GIT_DIR is set explicitly, we're not going
317 * to do any discovery, but we still do repository
318 * validation.
320 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
321 if (gitdirenv) {
322 if (PATH_MAX - 40 < strlen(gitdirenv))
323 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
324 if (is_git_directory(gitdirenv)) {
325 static char buffer[1024 + 1];
326 const char *retval;
328 if (!work_tree_env) {
329 retval = set_work_tree(gitdirenv);
330 /* config may override worktree */
331 if (check_repository_format_gently(nongit_ok))
332 return NULL;
333 return retval;
335 if (check_repository_format_gently(nongit_ok))
336 return NULL;
337 retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
338 get_git_work_tree());
339 if (!retval || !*retval)
340 return NULL;
341 set_git_dir(make_absolute_path(gitdirenv));
342 if (chdir(work_tree_env) < 0)
343 die_errno ("Could not chdir to '%s'", work_tree_env);
344 strcat(buffer, "/");
345 return retval;
347 if (nongit_ok) {
348 *nongit_ok = 1;
349 return NULL;
351 die("Not a git repository: '%s'", gitdirenv);
354 if (!getcwd(cwd, sizeof(cwd)-1))
355 die_errno("Unable to read current working directory");
357 ceil_offset = longest_ancestor_length(cwd, env_ceiling_dirs);
358 if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
359 ceil_offset = 1;
362 * Test in the following order (relative to the cwd):
363 * - .git (file containing "gitdir: <path>")
364 * - .git/
365 * - ./ (bare)
366 * - ../.git
367 * - ../.git/
368 * - ../ (bare)
369 * - ../../.git/
370 * etc.
372 offset = len = strlen(cwd);
373 for (;;) {
374 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
375 if (gitfile_dir) {
376 if (set_git_dir(gitfile_dir))
377 die("Repository setup failed");
378 break;
380 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
381 break;
382 if (is_git_directory(".")) {
383 inside_git_dir = 1;
384 if (!work_tree_env)
385 inside_work_tree = 0;
386 if (offset != len) {
387 cwd[offset] = '\0';
388 setenv(GIT_DIR_ENVIRONMENT, cwd, 1);
389 } else
390 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
391 check_repository_format_gently(nongit_ok);
392 return NULL;
394 while (--offset > ceil_offset && cwd[offset] != '/');
395 if (offset <= ceil_offset) {
396 if (nongit_ok) {
397 if (chdir(cwd))
398 die_errno("Cannot come back to cwd");
399 *nongit_ok = 1;
400 return NULL;
402 die("Not a git repository (or any of the parent directories): %s", DEFAULT_GIT_DIR_ENVIRONMENT);
404 if (chdir(".."))
405 die_errno("Cannot change to '%s/..'", cwd);
408 inside_git_dir = 0;
409 if (!work_tree_env)
410 inside_work_tree = 1;
411 git_work_tree_cfg = xstrndup(cwd, offset);
412 if (check_repository_format_gently(nongit_ok))
413 return NULL;
414 if (offset == len)
415 return NULL;
417 /* Make "offset" point to past the '/', and add a '/' at the end */
418 offset++;
419 cwd[len++] = '/';
420 cwd[len] = 0;
421 return cwd + offset;
424 int git_config_perm(const char *var, const char *value)
426 int i;
427 char *endptr;
429 if (value == NULL)
430 return PERM_GROUP;
432 if (!strcmp(value, "umask"))
433 return PERM_UMASK;
434 if (!strcmp(value, "group"))
435 return PERM_GROUP;
436 if (!strcmp(value, "all") ||
437 !strcmp(value, "world") ||
438 !strcmp(value, "everybody"))
439 return PERM_EVERYBODY;
441 /* Parse octal numbers */
442 i = strtol(value, &endptr, 8);
444 /* If not an octal number, maybe true/false? */
445 if (*endptr != 0)
446 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
449 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
450 * a chmod value to restrict to.
452 switch (i) {
453 case PERM_UMASK: /* 0 */
454 return PERM_UMASK;
455 case OLD_PERM_GROUP: /* 1 */
456 return PERM_GROUP;
457 case OLD_PERM_EVERYBODY: /* 2 */
458 return PERM_EVERYBODY;
461 /* A filemode value was given: 0xxx */
463 if ((i & 0600) != 0600)
464 die("Problem with core.sharedRepository filemode value "
465 "(0%.3o).\nThe owner of files must always have "
466 "read and write permissions.", i);
469 * Mask filemode value. Others can not get write permission.
470 * x flags for directories are handled separately.
472 return -(i & 0666);
475 int check_repository_format_version(const char *var, const char *value, void *cb)
477 if (strcmp(var, "core.repositoryformatversion") == 0)
478 repository_format_version = git_config_int(var, value);
479 else if (strcmp(var, "core.sharedrepository") == 0)
480 shared_repository = git_config_perm(var, value);
481 else if (strcmp(var, "core.bare") == 0) {
482 is_bare_repository_cfg = git_config_bool(var, value);
483 if (is_bare_repository_cfg == 1)
484 inside_work_tree = -1;
485 } else if (strcmp(var, "core.worktree") == 0) {
486 if (!value)
487 return config_error_nonbool(var);
488 free(git_work_tree_cfg);
489 git_work_tree_cfg = xstrdup(value);
490 inside_work_tree = -1;
492 return 0;
495 int check_repository_format(void)
497 return check_repository_format_gently(NULL);
500 const char *setup_git_directory(void)
502 const char *retval = setup_git_directory_gently(NULL);
504 /* If the work tree is not the default one, recompute prefix */
505 if (inside_work_tree < 0) {
506 static char buffer[PATH_MAX + 1];
507 char *rel;
508 if (retval && chdir(retval))
509 die_errno ("Could not jump back into original cwd");
510 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
511 if (rel && *rel && chdir(get_git_work_tree()))
512 die_errno ("Could not jump to working directory");
513 return rel && *rel ? strcat(rel, "/") : NULL;
516 return retval;