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)
11 if (has_dos_drive_prefix(src)) {
17 if (is_dir_sep(*src)) {
19 while (is_dir_sep(*src))
27 * A path component that begins with . could be
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.
38 } else if (is_dir_sep(src[1])) {
41 while (is_dir_sep(*src))
44 } else if (src[1] == '.') {
49 } else if (is_dir_sep(src[2])) {
52 while (is_dir_sep(*src))
59 /* copy up to the next '/', and eat all '/' */
60 while ((c = *src++) != '\0' && !is_dir_sep(c))
73 * dst0..dst is prefix portion, and dst[-1] is '/';
76 dst -= 2; /* go past trailing '/' if any */
83 if (c == '/') { /* MinGW: cannot be '\\' anymore */
93 const char *prefix_path(const char *prefix, int len, const char *path)
95 const char *orig = path;
96 char *sanitized = xmalloc(len + strlen(path) + 1);
97 if (is_absolute_path(orig))
98 strcpy(sanitized, path);
101 memcpy(sanitized, prefix, len);
102 strcpy(sanitized + len, path);
104 if (sanitary_path_copy(sanitized, sanitized))
106 if (is_absolute_path(orig)) {
107 const char *work_tree = get_git_work_tree();
108 size_t len = strlen(work_tree);
109 size_t total = strlen(sanitized) + 1;
110 if (strncmp(sanitized, work_tree, len) ||
111 (sanitized[len] != '\0' && sanitized[len] != '/')) {
113 error("'%s' is outside repository", orig);
117 if (sanitized[len] == '/')
119 memmove(sanitized, sanitized + len, total - len);
125 * Unlike prefix_path, this should be used if the named file does
126 * not have to interact with index entry; i.e. name of a random file
129 const char *prefix_filename(const char *pfx, int pfx_len, const char *arg)
131 static char path[PATH_MAX];
133 if (!pfx || !*pfx || is_absolute_path(arg))
135 memcpy(path, pfx, pfx_len);
136 strcpy(path + pfx_len, arg);
139 /* don't add prefix to absolute paths, but still replace '\' by '/' */
140 if (is_absolute_path(arg))
143 memcpy(path, pfx, pfx_len);
144 strcpy(path + pfx_len, arg);
145 for (p = path + pfx_len; *p; p++)
153 * Verify a filename that we got as an argument for a pathspec
154 * entry. Note that a filename that begins with "-" never verifies
155 * as true, because even if such a filename were to exist, we want
156 * it to be preceded by the "--" marker (or we want the user to
157 * use a format like "./-filename")
159 void verify_filename(const char *prefix, const char *arg)
165 die("bad flag '%s' used after filename", arg);
166 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
167 if (!lstat(name, &st))
170 die("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
171 "Use '--' to separate paths from revisions", arg);
172 die("'%s': %s", arg, strerror(errno));
176 * Opposite of the above: the command line did not have -- marker
177 * and we parsed the arg as a refname. It should not be interpretable
180 void verify_non_filename(const char *prefix, const char *arg)
185 if (!is_inside_work_tree() || is_inside_git_dir())
189 name = prefix ? prefix_filename(prefix, strlen(prefix), arg) : arg;
190 if (!lstat(name, &st))
191 die("ambiguous argument '%s': both revision and filename\n"
192 "Use '--' to separate filenames from revisions", arg);
193 if (errno != ENOENT && errno != ENOTDIR)
194 die("'%s': %s", arg, strerror(errno));
197 const char **get_pathspec(const char *prefix, const char **pathspec)
199 const char *entry = *pathspec;
200 const char **src, **dst;
203 if (!prefix && !entry)
207 static const char *spec[2];
213 /* Otherwise we have to re-write the entries.. */
216 prefixlen = prefix ? strlen(prefix) : 0;
218 const char *p = prefix_path(prefix, prefixlen, *src);
222 exit(128); /* error message already given */
232 * Test if it looks like we're at a git directory.
235 * - either an objects/ directory _or_ the proper
236 * GIT_OBJECT_DIRECTORY environment variable
237 * - a refs/ directory
238 * - either a HEAD symlink or a HEAD file that is formatted as
239 * a proper "ref:", or a regular file HEAD that has a properly
240 * formatted sha1 object name.
242 static int is_git_directory(const char *suspect)
245 size_t len = strlen(suspect);
247 strcpy(path, suspect);
248 if (getenv(DB_ENVIRONMENT)) {
249 if (access(getenv(DB_ENVIRONMENT), X_OK))
253 strcpy(path + len, "/objects");
254 if (access(path, X_OK))
258 strcpy(path + len, "/refs");
259 if (access(path, X_OK))
262 strcpy(path + len, "/HEAD");
263 if (validate_headref(path))
269 int is_inside_git_dir(void)
271 if (inside_git_dir < 0)
272 inside_git_dir = is_inside_dir(get_git_dir());
273 return inside_git_dir;
276 int is_inside_work_tree(void)
278 if (inside_work_tree < 0)
279 inside_work_tree = is_inside_dir(get_git_work_tree());
280 return inside_work_tree;
284 * set_work_tree() is only ever called if you set GIT_DIR explicitely.
285 * The old behaviour (which we retain here) is to set the work tree root
286 * to the cwd, unless overridden by the config, the command line, or
289 static const char *set_work_tree(const char *dir)
291 char buffer[PATH_MAX + 1];
293 if (!getcwd(buffer, sizeof(buffer)))
294 die ("Could not get the current working directory");
295 git_work_tree_cfg = xstrdup(buffer);
296 inside_work_tree = 1;
301 void setup_work_tree(void)
303 const char *work_tree, *git_dir;
304 static int initialized = 0;
308 work_tree = get_git_work_tree();
309 git_dir = get_git_dir();
310 if (!is_absolute_path(git_dir))
311 set_git_dir(make_absolute_path(git_dir));
312 if (!work_tree || chdir(work_tree))
313 die("This operation must be run in a work tree");
317 static int check_repository_format_gently(int *nongit_ok)
319 git_config(check_repository_format_version, NULL);
320 if (GIT_REPO_VERSION < repository_format_version) {
322 die ("Expected git repo version <= %d, found %d",
323 GIT_REPO_VERSION, repository_format_version);
324 warning("Expected git repo version <= %d, found %d",
325 GIT_REPO_VERSION, repository_format_version);
326 warning("Please upgrade Git");
334 * Try to read the location of the git directory from the .git file,
335 * return path to git directory if found.
337 const char *read_gitfile_gently(const char *path)
346 if (!S_ISREG(st.st_mode))
348 fd = open(path, O_RDONLY);
350 die("Error opening %s: %s", path, strerror(errno));
351 buf = xmalloc(st.st_size + 1);
352 len = read_in_full(fd, buf, st.st_size);
354 if (len != st.st_size)
355 die("Error reading %s", path);
357 if (prefixcmp(buf, "gitdir: "))
358 die("Invalid gitfile format: %s", path);
359 while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
362 die("No path in gitfile: %s", path);
364 if (!is_git_directory(buf + 8))
365 die("Not a git repository: %s", buf + 8);
366 path = make_absolute_path(buf + 8);
372 * We cannot decide in this function whether we are in the work tree or
373 * not, since the config can only be read _after_ this function was called.
375 const char *setup_git_directory_gently(int *nongit_ok)
377 const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
378 static char cwd[PATH_MAX+1];
379 const char *gitdirenv;
380 const char *gitfile_dir;
385 * Let's assume that we are in a git repository.
386 * If it turns out later that we are somewhere else, the value will be
387 * updated accordingly.
393 * If GIT_DIR is set explicitly, we're not going
394 * to do any discovery, but we still do repository
397 gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
399 if (PATH_MAX - 40 < strlen(gitdirenv))
400 die("'$%s' too big", GIT_DIR_ENVIRONMENT);
401 if (is_git_directory(gitdirenv)) {
402 static char buffer[1024 + 1];
405 if (!work_tree_env) {
406 retval = set_work_tree(gitdirenv);
407 /* config may override worktree */
408 if (check_repository_format_gently(nongit_ok))
412 if (check_repository_format_gently(nongit_ok))
414 retval = get_relative_cwd(buffer, sizeof(buffer) - 1,
415 get_git_work_tree());
416 if (!retval || !*retval)
418 set_git_dir(make_absolute_path(gitdirenv));
419 if (chdir(work_tree_env) < 0)
420 die ("Could not chdir to %s", work_tree_env);
428 die("Not a git repository: '%s'", gitdirenv);
431 if (!getcwd(cwd, sizeof(cwd)-1))
432 die("Unable to read current working directory");
433 if (has_dos_drive_prefix(cwd))
437 * Test in the following order (relative to the cwd):
438 * - .git (file containing "gitdir: <path>")
447 offset = len = strlen(cwd);
449 gitfile_dir = read_gitfile_gently(DEFAULT_GIT_DIR_ENVIRONMENT);
451 if (set_git_dir(gitfile_dir))
452 die("Repository setup failed");
455 if (is_git_directory(DEFAULT_GIT_DIR_ENVIRONMENT))
457 if (is_git_directory(".")) {
460 inside_work_tree = 0;
461 setenv(GIT_DIR_ENVIRONMENT, ".", 1);
462 check_repository_format_gently(nongit_ok);
467 if (offset <= minoffset) {
470 die("Cannot come back to cwd");
474 die("Not a git repository");
476 } while (offset > minoffset && cwd[--offset] != '/');
481 inside_work_tree = 1;
482 git_work_tree_cfg = xstrndup(cwd, offset);
483 if (check_repository_format_gently(nongit_ok))
488 /* Make "offset" point to past the '/', and add a '/' at the end */
495 int git_config_perm(const char *var, const char *value)
503 if (!strcmp(value, "umask"))
505 if (!strcmp(value, "group"))
507 if (!strcmp(value, "all") ||
508 !strcmp(value, "world") ||
509 !strcmp(value, "everybody"))
510 return PERM_EVERYBODY;
512 /* Parse octal numbers */
513 i = strtol(value, &endptr, 8);
515 /* If not an octal number, maybe true/false? */
517 return git_config_bool(var, value) ? PERM_GROUP : PERM_UMASK;
520 * Treat values 0, 1 and 2 as compatibility cases, otherwise it is
524 case PERM_UMASK: /* 0 */
526 case OLD_PERM_GROUP: /* 1 */
528 case OLD_PERM_EVERYBODY: /* 2 */
529 return PERM_EVERYBODY;
532 /* A filemode value was given: 0xxx */
534 if ((i & 0600) != 0600)
535 die("Problem with core.sharedRepository filemode value "
536 "(0%.3o).\nThe owner of files must always have "
537 "read and write permissions.", i);
540 * Mask filemode value. Others can not get write permission.
541 * x flags for directories are handled separately.
546 int check_repository_format_version(const char *var, const char *value, void *cb)
548 if (strcmp(var, "core.repositoryformatversion") == 0)
549 repository_format_version = git_config_int(var, value);
550 else if (strcmp(var, "core.sharedrepository") == 0)
551 shared_repository = git_config_perm(var, value);
552 else if (strcmp(var, "core.bare") == 0) {
553 is_bare_repository_cfg = git_config_bool(var, value);
554 if (is_bare_repository_cfg == 1)
555 inside_work_tree = -1;
556 } else if (strcmp(var, "core.worktree") == 0) {
558 return config_error_nonbool(var);
559 free(git_work_tree_cfg);
560 git_work_tree_cfg = xstrdup(value);
561 inside_work_tree = -1;
566 int check_repository_format(void)
568 return check_repository_format_gently(NULL);
571 const char *setup_git_directory(void)
573 const char *retval = setup_git_directory_gently(NULL);
575 /* If the work tree is not the default one, recompute prefix */
576 if (inside_work_tree < 0) {
577 static char buffer[PATH_MAX + 1];
579 if (retval && chdir(retval))
580 die ("Could not jump back into original cwd");
581 rel = get_relative_cwd(buffer, PATH_MAX, get_git_work_tree());
582 return rel && *rel ? strcat(rel, "/") : NULL;