Sync with maint
[gitweb.git] / setup.c
diff --git a/setup.c b/setup.c
index 5262319be69b3bf3fd2492dea3d30e7353d66a23..a17c51e61d75ac8280bf04d95c50d7bdfd6d7a0e 100644 (file)
--- a/setup.c
+++ b/setup.c
 
 static int inside_git_dir = -1;
 static int inside_work_tree = -1;
+static int work_tree_config_is_bogus;
 
-static char *prefix_path_gently(const char *prefix, int len, const char *path)
+/*
+ * The input parameter must contain an absolute path, and it must already be
+ * normalized.
+ *
+ * Find the part of an absolute path that lies inside the work tree by
+ * dereferencing symlinks outside the work tree, for example:
+ * /dir1/repo/dir2/file   (work tree is /dir1/repo)      -> dir2/file
+ * /dir/file              (work tree is /)               -> dir/file
+ * /dir/symlink1/symlink2 (symlink1 points to work tree) -> symlink2
+ * /dir/repolink/file     (repolink points to /dir/repo) -> file
+ * /dir/repo              (exactly equal to work tree)   -> (empty string)
+ */
+static int abspath_part_inside_repo(char *path)
+{
+       size_t len;
+       size_t wtlen;
+       char *path0;
+       int off;
+       const char *work_tree = get_git_work_tree();
+
+       if (!work_tree)
+               return -1;
+       wtlen = strlen(work_tree);
+       len = strlen(path);
+       off = offset_1st_component(path);
+
+       /* check if work tree is already the prefix */
+       if (wtlen <= len && !strncmp(path, work_tree, wtlen)) {
+               if (path[wtlen] == '/') {
+                       memmove(path, path + wtlen + 1, len - wtlen);
+                       return 0;
+               } else if (path[wtlen - 1] == '/' || path[wtlen] == '\0') {
+                       /* work tree is the root, or the whole path */
+                       memmove(path, path + wtlen, len - wtlen + 1);
+                       return 0;
+               }
+               /* work tree might match beginning of a symlink to work tree */
+               off = wtlen;
+       }
+       path0 = path;
+       path += off;
+
+       /* check each '/'-terminated level */
+       while (*path) {
+               path++;
+               if (*path == '/') {
+                       *path = '\0';
+                       if (strcmp(real_path(path0), work_tree) == 0) {
+                               memmove(path0, path + 1, len - (path - path0));
+                               return 0;
+                       }
+                       *path = '/';
+               }
+       }
+
+       /* check whole path */
+       if (strcmp(real_path(path0), work_tree) == 0) {
+               *path0 = '\0';
+               return 0;
+       }
+
+       return -1;
+}
+
+/*
+ * Normalize "path", prepending the "prefix" for relative paths. If
+ * remaining_prefix is not NULL, return the actual prefix still
+ * remains in the path. For example, prefix = sub1/sub2/ and path is
+ *
+ *  foo          -> sub1/sub2/foo  (full prefix)
+ *  ../foo       -> sub1/foo       (remaining prefix is sub1/)
+ *  ../../bar    -> bar            (no remaining prefix)
+ *  ../../sub1/sub2/foo -> sub1/sub2/foo (but no remaining prefix)
+ *  `pwd`/../bar -> sub1/bar       (no remaining prefix)
+ */
+char *prefix_path_gently(const char *prefix, int len,
+                        int *remaining_prefix, const char *path)
 {
        const char *orig = path;
        char *sanitized;
        if (is_absolute_path(orig)) {
-               const char *temp = real_path(path);
-               sanitized = xmalloc(len + strlen(temp) + 1);
-               strcpy(sanitized, temp);
+               sanitized = xmalloc(strlen(path) + 1);
+               if (remaining_prefix)
+                       *remaining_prefix = 0;
+               if (normalize_path_copy_len(sanitized, path, remaining_prefix)) {
+                       free(sanitized);
+                       return NULL;
+               }
+               if (abspath_part_inside_repo(sanitized)) {
+                       free(sanitized);
+                       return NULL;
+               }
        } else {
                sanitized = xmalloc(len + strlen(path) + 1);
                if (len)
                        memcpy(sanitized, prefix, len);
                strcpy(sanitized + len, path);
-       }
-       if (normalize_path_copy(sanitized, sanitized))
-               goto error_out;
-       if (is_absolute_path(orig)) {
-               size_t root_len, len, total;
-               const char *work_tree = get_git_work_tree();
-               if (!work_tree)
-                       goto error_out;
-               len = strlen(work_tree);
-               root_len = offset_1st_component(work_tree);
-               total = strlen(sanitized) + 1;
-               if (strncmp(sanitized, work_tree, len) ||
-                   (len > root_len && sanitized[len] != '\0' && sanitized[len] != '/')) {
-               error_out:
+               if (remaining_prefix)
+                       *remaining_prefix = len;
+               if (normalize_path_copy_len(sanitized, sanitized, remaining_prefix)) {
                        free(sanitized);
                        return NULL;
                }
-               if (sanitized[len] == '/')
-                       len++;
-               memmove(sanitized, sanitized + len, total - len);
        }
        return sanitized;
 }
 
 char *prefix_path(const char *prefix, int len, const char *path)
 {
-       char *r = prefix_path_gently(prefix, len, path);
+       char *r = prefix_path_gently(prefix, len, NULL, path);
        if (!r)
                die("'%s' is outside repository", path);
        return r;
@@ -53,7 +124,7 @@ char *prefix_path(const char *prefix, int len, const char *path)
 int path_inside_repo(const char *prefix, const char *path)
 {
        int len = prefix ? strlen(prefix) : 0;
-       char *r = prefix_path_gently(prefix, len, path);
+       char *r = prefix_path_gently(prefix, len, NULL, path);
        if (r) {
                free(r);
                return 1;
@@ -66,11 +137,13 @@ int check_filename(const char *prefix, const char *arg)
        const char *name;
        struct stat st;
 
-       if (!prefixcmp(arg, ":/")) {
+       if (starts_with(arg, ":/")) {
                if (arg[2] == '\0') /* ":/" is root dir, always exists */
                        return 1;
                name = arg + 2;
-       } else if (prefix)
+       } else if (!no_wildcard(arg))
+               return 1;
+       else if (prefix)
                name = prefix_filename(prefix, strlen(prefix), arg);
        else
                name = arg;
@@ -154,154 +227,35 @@ void verify_non_filename(const char *prefix, const char *arg)
            "'git <command> [<revision>...] -- [<file>...]'", arg);
 }
 
-/*
- * Magic pathspec
- *
- * NEEDSWORK: These need to be moved to dir.h or even to a new
- * pathspec.h when we restructure get_pathspec() users to use the
- * "struct pathspec" interface.
- *
- * Possible future magic semantics include stuff like:
- *
- *     { PATHSPEC_NOGLOB, '!', "noglob" },
- *     { PATHSPEC_ICASE, '\0', "icase" },
- *     { PATHSPEC_RECURSIVE, '*', "recursive" },
- *     { PATHSPEC_REGEXP, '\0', "regexp" },
- *
- */
-#define PATHSPEC_FROMTOP    (1<<0)
-
-static struct pathspec_magic {
-       unsigned bit;
-       char mnemonic; /* this cannot be ':'! */
-       const char *name;
-} pathspec_magic[] = {
-       { PATHSPEC_FROMTOP, '/', "top" },
-};
-
-/*
- * Take an element of a pathspec and check for magic signatures.
- * Append the result to the prefix.
- *
- * For now, we only parse the syntax and throw out anything other than
- * "top" magic.
- *
- * NEEDSWORK: This needs to be rewritten when we start migrating
- * get_pathspec() users to use the "struct pathspec" interface.  For
- * example, a pathspec element may be marked as case-insensitive, but
- * the prefix part must always match literally, and a single stupid
- * string cannot express such a case.
- */
-static const char *prefix_pathspec(const char *prefix, int prefixlen, const char *elt)
-{
-       unsigned magic = 0;
-       const char *copyfrom = elt;
-       int i;
-
-       if (elt[0] != ':') {
-               ; /* nothing to do */
-       } else if (elt[1] == '(') {
-               /* longhand */
-               const char *nextat;
-               for (copyfrom = elt + 2;
-                    *copyfrom && *copyfrom != ')';
-                    copyfrom = nextat) {
-                       size_t len = strcspn(copyfrom, ",)");
-                       if (copyfrom[len] == ',')
-                               nextat = copyfrom + len + 1;
-                       else
-                               /* handle ')' and '\0' */
-                               nextat = copyfrom + len;
-                       if (!len)
-                               continue;
-                       for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
-                               if (strlen(pathspec_magic[i].name) == len &&
-                                   !strncmp(pathspec_magic[i].name, copyfrom, len)) {
-                                       magic |= pathspec_magic[i].bit;
-                                       break;
-                               }
-                       if (ARRAY_SIZE(pathspec_magic) <= i)
-                               die("Invalid pathspec magic '%.*s' in '%s'",
-                                   (int) len, copyfrom, elt);
-               }
-               if (*copyfrom != ')')
-                       die("Missing ')' at the end of pathspec magic in '%s'", elt);
-               copyfrom++;
-       } else {
-               /* shorthand */
-               for (copyfrom = elt + 1;
-                    *copyfrom && *copyfrom != ':';
-                    copyfrom++) {
-                       char ch = *copyfrom;
-
-                       if (!is_pathspec_magic(ch))
-                               break;
-                       for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
-                               if (pathspec_magic[i].mnemonic == ch) {
-                                       magic |= pathspec_magic[i].bit;
-                                       break;
-                               }
-                       if (ARRAY_SIZE(pathspec_magic) <= i)
-                               die("Unimplemented pathspec magic '%c' in '%s'",
-                                   ch, elt);
-               }
-               if (*copyfrom == ':')
-                       copyfrom++;
-       }
-
-       if (magic & PATHSPEC_FROMTOP)
-               return xstrdup(copyfrom);
-       else
-               return prefix_path(prefix, prefixlen, copyfrom);
-}
-
-/*
- * N.B. get_pathspec() is deprecated in favor of the "struct pathspec"
- * based interface - see pathspec_magic above.
- *
- * Arguments:
- *  - prefix - a path relative to the root of the working tree
- *  - pathspec - a list of paths underneath the prefix path
- *
- * Iterates over pathspec, prepending each path with prefix,
- * and return the resulting list.
- *
- * If pathspec is empty, return a singleton list containing prefix.
- *
- * If pathspec and prefix are both empty, return an empty list.
- *
- * This is typically used by built-in commands such as add.c, in order
- * to normalize argv arguments provided to the built-in into a list of
- * paths to process, all relative to the root of the working tree.
- */
-const char **get_pathspec(const char *prefix, const char **pathspec)
+int get_common_dir(struct strbuf *sb, const char *gitdir)
 {
-       const char *entry = *pathspec;
-       const char **src, **dst;
-       int prefixlen;
-
-       if (!prefix && !entry)
-               return NULL;
-
-       if (!entry) {
-               static const char *spec[2];
-               spec[0] = prefix;
-               spec[1] = NULL;
-               return spec;
-       }
-
-       /* Otherwise we have to re-write the entries.. */
-       src = pathspec;
-       dst = pathspec;
-       prefixlen = prefix ? strlen(prefix) : 0;
-       while (*src) {
-               *(dst++) = prefix_pathspec(prefix, prefixlen, *src);
-               src++;
+       struct strbuf data = STRBUF_INIT;
+       struct strbuf path = STRBUF_INIT;
+       const char *git_common_dir = getenv(GIT_COMMON_DIR_ENVIRONMENT);
+       int ret = 0;
+       if (git_common_dir) {
+               strbuf_addstr(sb, git_common_dir);
+               return 1;
        }
-       *dst = NULL;
-       if (!*pathspec)
-               return NULL;
-       return pathspec;
+       strbuf_addf(&path, "%s/commondir", gitdir);
+       if (file_exists(path.buf)) {
+               if (strbuf_read_file(&data, path.buf, 0) <= 0)
+                       die_errno(_("failed to read %s"), path.buf);
+               while (data.len && (data.buf[data.len - 1] == '\n' ||
+                                   data.buf[data.len - 1] == '\r'))
+                       data.len--;
+               data.buf[data.len] = '\0';
+               strbuf_reset(&path);
+               if (!is_absolute_path(data.buf))
+                       strbuf_addf(&path, "%s/", gitdir);
+               strbuf_addbuf(&path, &data);
+               strbuf_addstr(sb, real_path(path.buf));
+               ret = 1;
+       } else
+               strbuf_addstr(sb, gitdir);
+       strbuf_release(&data);
+       strbuf_release(&path);
+       return ret;
 }
 
 /*
@@ -317,31 +271,40 @@ const char **get_pathspec(const char *prefix, const char **pathspec)
  */
 int is_git_directory(const char *suspect)
 {
-       char path[PATH_MAX];
-       size_t len = strlen(suspect);
+       struct strbuf path = STRBUF_INIT;
+       int ret = 0;
+       size_t len;
+
+       /* Check worktree-related signatures */
+       strbuf_addf(&path, "%s/HEAD", suspect);
+       if (validate_headref(path.buf))
+               goto done;
 
-       if (PATH_MAX <= len + strlen("/objects"))
-               die("Too long path: %.*s", 60, suspect);
-       strcpy(path, suspect);
+       strbuf_reset(&path);
+       get_common_dir(&path, suspect);
+       len = path.len;
+
+       /* Check non-worktree-related signatures */
        if (getenv(DB_ENVIRONMENT)) {
                if (access(getenv(DB_ENVIRONMENT), X_OK))
-                       return 0;
+                       goto done;
        }
        else {
-               strcpy(path + len, "/objects");
-               if (access(path, X_OK))
-                       return 0;
+               strbuf_setlen(&path, len);
+               strbuf_addstr(&path, "/objects");
+               if (access(path.buf, X_OK))
+                       goto done;
        }
 
-       strcpy(path + len, "/refs");
-       if (access(path, X_OK))
-               return 0;
-
-       strcpy(path + len, "/HEAD");
-       if (validate_headref(path))
-               return 0;
+       strbuf_setlen(&path, len);
+       strbuf_addstr(&path, "/refs");
+       if (access(path.buf, X_OK))
+               goto done;
 
-       return 1;
+       ret = 1;
+done:
+       strbuf_release(&path);
+       return ret;
 }
 
 int is_inside_git_dir(void)
@@ -360,12 +323,15 @@ int is_inside_work_tree(void)
 
 void setup_work_tree(void)
 {
-       struct strbuf sb = STRBUF_INIT;
        const char *work_tree, *git_dir;
        static int initialized = 0;
 
        if (initialized)
                return;
+
+       if (work_tree_config_is_bogus)
+               die("unable to set up work tree using invalid config");
+
        work_tree = get_git_work_tree();
        git_dir = get_git_dir();
        if (!is_absolute_path(git_dir))
@@ -380,15 +346,32 @@ void setup_work_tree(void)
        if (getenv(GIT_WORK_TREE_ENVIRONMENT))
                setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
 
-       set_git_dir(relative_path(git_dir, work_tree, &sb));
+       set_git_dir(remove_leading_path(git_dir, work_tree));
        initialized = 1;
+}
 
-       strbuf_release(&sb);
+static int check_repo_format(const char *var, const char *value, void *cb)
+{
+       if (strcmp(var, "core.repositoryformatversion") == 0)
+               repository_format_version = git_config_int(var, value);
+       else if (strcmp(var, "core.sharedrepository") == 0)
+               shared_repository = git_config_perm(var, value);
+       return 0;
 }
 
 static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
 {
-       char repo_config[PATH_MAX+1];
+       struct strbuf sb = STRBUF_INIT;
+       const char *repo_config;
+       config_fn_t fn;
+       int ret = 0;
+
+       if (get_common_dir(&sb, gitdir))
+               fn = check_repo_format;
+       else
+               fn = check_repository_format_version;
+       strbuf_addstr(&sb, "/config");
+       repo_config = sb.buf;
 
        /*
         * git_config() can't be used here because it calls git_pathdup()
@@ -399,8 +382,7 @@ static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
         * Use a gentler version of git_config() to check if this repo
         * is a good one.
         */
-       snprintf(repo_config, PATH_MAX, "%s/config", gitdir);
-       git_config_early(check_repository_format_version, NULL, repo_config);
+       git_config_early(fn, NULL, repo_config);
        if (GIT_REPO_VERSION < repository_format_version) {
                if (!nongit_ok)
                        die ("Expected git repo version <= %d, found %d",
@@ -409,43 +391,78 @@ static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
                        GIT_REPO_VERSION, repository_format_version);
                warning("Please upgrade Git");
                *nongit_ok = -1;
-               return -1;
+               ret = -1;
        }
-       return 0;
+       strbuf_release(&sb);
+       return ret;
+}
+
+static void update_linked_gitdir(const char *gitfile, const char *gitdir)
+{
+       struct strbuf path = STRBUF_INIT;
+       struct stat st;
+
+       strbuf_addf(&path, "%s/gitdir", gitdir);
+       if (stat(path.buf, &st) || st.st_mtime + 24 * 3600 < time(NULL))
+               write_file(path.buf, "%s", gitfile);
+       strbuf_release(&path);
 }
 
 /*
  * Try to read the location of the git directory from the .git file,
  * return path to git directory if found.
+ *
+ * On failure, if return_error_code is not NULL, return_error_code
+ * will be set to an error code and NULL will be returned. If
+ * return_error_code is NULL the function will die instead (for most
+ * cases).
  */
-const char *read_gitfile(const char *path)
+const char *read_gitfile_gently(const char *path, int *return_error_code)
 {
-       char *buf;
-       char *dir;
+       const int max_file_size = 1 << 20;  /* 1MB */
+       int error_code = 0;
+       char *buf = NULL;
+       char *dir = NULL;
        const char *slash;
        struct stat st;
        int fd;
        ssize_t len;
 
-       if (stat(path, &st))
-               return NULL;
-       if (!S_ISREG(st.st_mode))
-               return NULL;
+       if (stat(path, &st)) {
+               error_code = READ_GITFILE_ERR_STAT_FAILED;
+               goto cleanup_return;
+       }
+       if (!S_ISREG(st.st_mode)) {
+               error_code = READ_GITFILE_ERR_NOT_A_FILE;
+               goto cleanup_return;
+       }
+       if (st.st_size > max_file_size) {
+               error_code = READ_GITFILE_ERR_TOO_LARGE;
+               goto cleanup_return;
+       }
        fd = open(path, O_RDONLY);
-       if (fd < 0)
-               die_errno("Error opening '%s'", path);
+       if (fd < 0) {
+               error_code = READ_GITFILE_ERR_OPEN_FAILED;
+               goto cleanup_return;
+       }
        buf = xmalloc(st.st_size + 1);
        len = read_in_full(fd, buf, st.st_size);
        close(fd);
-       if (len != st.st_size)
-               die("Error reading %s", path);
+       if (len != st.st_size) {
+               error_code = READ_GITFILE_ERR_READ_FAILED;
+               goto cleanup_return;
+       }
        buf[len] = '\0';
-       if (prefixcmp(buf, "gitdir: "))
-               die("Invalid gitfile format: %s", path);
+       if (!starts_with(buf, "gitdir: ")) {
+               error_code = READ_GITFILE_ERR_INVALID_FORMAT;
+               goto cleanup_return;
+       }
        while (buf[len - 1] == '\n' || buf[len - 1] == '\r')
                len--;
-       if (len < 9)
-               die("No path in gitfile: %s", path);
+       if (len < 9) {
+               error_code = READ_GITFILE_ERR_NO_PATH;
+               goto cleanup_return;
+       }
        buf[len] = '\0';
        dir = buf + 8;
 
@@ -459,17 +476,45 @@ const char *read_gitfile(const char *path)
                free(buf);
                buf = dir;
        }
-
-       if (!is_git_directory(dir))
-               die("Not a git repository: %s", dir);
+       if (!is_git_directory(dir)) {
+               error_code = READ_GITFILE_ERR_NOT_A_REPO;
+               goto cleanup_return;
+       }
+       update_linked_gitdir(path, dir);
        path = real_path(dir);
 
+cleanup_return:
+       if (return_error_code)
+               *return_error_code = error_code;
+       else if (error_code) {
+               switch (error_code) {
+               case READ_GITFILE_ERR_STAT_FAILED:
+               case READ_GITFILE_ERR_NOT_A_FILE:
+                       /* non-fatal; follow return path */
+                       break;
+               case READ_GITFILE_ERR_OPEN_FAILED:
+                       die_errno("Error opening '%s'", path);
+               case READ_GITFILE_ERR_TOO_LARGE:
+                       die("Too large to be a .git file: '%s'", path);
+               case READ_GITFILE_ERR_READ_FAILED:
+                       die("Error reading %s", path);
+               case READ_GITFILE_ERR_INVALID_FORMAT:
+                       die("Invalid gitfile format: %s", path);
+               case READ_GITFILE_ERR_NO_PATH:
+                       die("No path in gitfile: %s", path);
+               case READ_GITFILE_ERR_NOT_A_REPO:
+                       die("Not a git repository: %s", dir);
+               default:
+                       assert(0);
+               }
+       }
+
        free(buf);
-       return path;
+       return error_code ? NULL : path;
 }
 
 static const char *setup_explicit_git_dir(const char *gitdirenv,
-                                         char *cwd, int len,
+                                         struct strbuf *cwd,
                                          int *nongit_ok)
 {
        const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
@@ -504,8 +549,11 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
        if (work_tree_env)
                set_git_work_tree(work_tree_env);
        else if (is_bare_repository_cfg > 0) {
-               if (git_work_tree_cfg) /* #22.2, #30 */
-                       die("core.bare and core.worktree do not make sense");
+               if (git_work_tree_cfg) {
+                       /* #22.2, #30 */
+                       warning("core.bare and core.worktree do not make sense");
+                       work_tree_config_is_bogus = 1;
+               }
 
                /* #18, #26 */
                set_git_dir(gitdirenv);
@@ -516,16 +564,16 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
                if (is_absolute_path(git_work_tree_cfg))
                        set_git_work_tree(git_work_tree_cfg);
                else {
-                       char core_worktree[PATH_MAX];
+                       char *core_worktree;
                        if (chdir(gitdirenv))
                                die_errno("Could not chdir to '%s'", gitdirenv);
                        if (chdir(git_work_tree_cfg))
                                die_errno("Could not chdir to '%s'", git_work_tree_cfg);
-                       if (!getcwd(core_worktree, PATH_MAX))
-                               die_errno("Could not get directory '%s'", git_work_tree_cfg);
-                       if (chdir(cwd))
+                       core_worktree = xgetcwd();
+                       if (chdir(cwd->buf))
                                die_errno("Could not come back to cwd");
                        set_git_work_tree(core_worktree);
+                       free(core_worktree);
                }
        }
        else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
@@ -541,21 +589,20 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
        worktree = get_git_work_tree();
 
        /* both get_git_work_tree() and cwd are already normalized */
-       if (!strcmp(cwd, worktree)) { /* cwd == worktree */
+       if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
                set_git_dir(gitdirenv);
                free(gitfile);
                return NULL;
        }
 
-       offset = dir_inside_of(cwd, worktree);
+       offset = dir_inside_of(cwd->buf, worktree);
        if (offset >= 0) {      /* cwd inside worktree? */
                set_git_dir(real_path(gitdirenv));
                if (chdir(worktree))
                        die_errno("Could not chdir to '%s'", worktree);
-               cwd[len++] = '/';
-               cwd[len] = '\0';
+               strbuf_addch(cwd, '/');
                free(gitfile);
-               return cwd + offset;
+               return cwd->buf + offset;
        }
 
        /* cwd outside worktree */
@@ -565,7 +612,7 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
 }
 
 static const char *setup_discovered_git_dir(const char *gitdir,
-                                           char *cwd, int offset, int len,
+                                           struct strbuf *cwd, int offset,
                                            int *nongit_ok)
 {
        if (check_repository_format_gently(gitdir, nongit_ok))
@@ -573,17 +620,17 @@ static const char *setup_discovered_git_dir(const char *gitdir,
 
        /* --work-tree is set without --git-dir; use discovered one */
        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
-               if (offset != len && !is_absolute_path(gitdir))
+               if (offset != cwd->len && !is_absolute_path(gitdir))
                        gitdir = xstrdup(real_path(gitdir));
-               if (chdir(cwd))
+               if (chdir(cwd->buf))
                        die_errno("Could not come back to cwd");
-               return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
+               return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
        }
 
        /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
        if (is_bare_repository_cfg > 0) {
-               set_git_dir(offset == len ? gitdir : real_path(gitdir));
-               if (chdir(cwd))
+               set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
+               if (chdir(cwd->buf))
                        die_errno("Could not come back to cwd");
                return NULL;
        }
@@ -594,18 +641,18 @@ static const char *setup_discovered_git_dir(const char *gitdir,
                set_git_dir(gitdir);
        inside_git_dir = 0;
        inside_work_tree = 1;
-       if (offset == len)
+       if (offset == cwd->len)
                return NULL;
 
        /* Make "offset" point to past the '/', and add a '/' at the end */
        offset++;
-       cwd[len++] = '/';
-       cwd[len] = 0;
-       return cwd + offset;
+       strbuf_addch(cwd, '/');
+       return cwd->buf + offset;
 }
 
 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
-static const char *setup_bare_git_dir(char *cwd, int offset, int len, int *nongit_ok)
+static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
+                                     int *nongit_ok)
 {
        int root_len;
 
@@ -618,20 +665,20 @@ static const char *setup_bare_git_dir(char *cwd, int offset, int len, int *nongi
        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
                const char *gitdir;
 
-               gitdir = offset == len ? "." : xmemdupz(cwd, offset);
-               if (chdir(cwd))
+               gitdir = offset == cwd->len ? "." : xmemdupz(cwd->buf, offset);
+               if (chdir(cwd->buf))
                        die_errno("Could not come back to cwd");
-               return setup_explicit_git_dir(gitdir, cwd, len, nongit_ok);
+               return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
        }
 
        inside_git_dir = 1;
        inside_work_tree = 0;
-       if (offset != len) {
-               if (chdir(cwd))
+       if (offset != cwd->len) {
+               if (chdir(cwd->buf))
                        die_errno("Cannot come back to cwd");
-               root_len = offset_1st_component(cwd);
-               cwd[offset > root_len ? offset : root_len] = '\0';
-               set_git_dir(cwd);
+               root_len = offset_1st_component(cwd->buf);
+               strbuf_setlen(cwd, offset > root_len ? offset : root_len);
+               set_git_dir(cwd->buf);
        }
        else
                set_git_dir(".");
@@ -699,13 +746,22 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
 {
        const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
        struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
-       static char cwd[PATH_MAX+1];
+       static struct strbuf cwd = STRBUF_INIT;
        const char *gitdirenv, *ret;
        char *gitfile;
-       int len, offset, offset_parent, ceil_offset = -1;
+       int offset, offset_parent, ceil_offset = -1;
        dev_t current_device = 0;
        int one_filesystem = 1;
 
+       /*
+        * We may have read an incomplete configuration before
+        * setting-up the git directory. If so, clear the cache so
+        * that the next queries to the configuration reload complete
+        * configuration (including the per-repo config file that we
+        * ignored previously).
+        */
+       git_config_clear();
+
        /*
         * Let's assume that we are in a git repository.
         * If it turns out later that we are somewhere else, the value will be
@@ -714,9 +770,9 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
        if (nongit_ok)
                *nongit_ok = 0;
 
-       if (!getcwd(cwd, sizeof(cwd)-1))
+       if (strbuf_getcwd(&cwd))
                die_errno("Unable to read current working directory");
-       offset = len = strlen(cwd);
+       offset = cwd.len;
 
        /*
         * If GIT_DIR is set explicitly, we're not going
@@ -725,7 +781,7 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
         */
        gitdirenv = getenv(GIT_DIR_ENVIRONMENT);
        if (gitdirenv)
-               return setup_explicit_git_dir(gitdirenv, cwd, len, nongit_ok);
+               return setup_explicit_git_dir(gitdirenv, &cwd, nongit_ok);
 
        if (env_ceiling_dirs) {
                int empty_entry_found = 0;
@@ -733,11 +789,11 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
                string_list_split(&ceiling_dirs, env_ceiling_dirs, PATH_SEP, -1);
                filter_string_list(&ceiling_dirs, 0,
                                   canonicalize_ceiling_entry, &empty_entry_found);
-               ceil_offset = longest_ancestor_length(cwd, &ceiling_dirs);
+               ceil_offset = longest_ancestor_length(cwd.buf, &ceiling_dirs);
                string_list_clear(&ceiling_dirs, 0);
        }
 
-       if (ceil_offset < 0 && has_dos_drive_prefix(cwd))
+       if (ceil_offset < 0 && has_dos_drive_prefix(cwd.buf))
                ceil_offset = 1;
 
        /*
@@ -765,7 +821,7 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
 
                if (gitdirenv) {
                        ret = setup_discovered_git_dir(gitdirenv,
-                                                      cwd, offset, len,
+                                                      &cwd, offset,
                                                       nongit_ok);
                        free(gitfile);
                        return ret;
@@ -773,29 +829,31 @@ static const char *setup_git_directory_gently_1(int *nongit_ok)
                free(gitfile);
 
                if (is_git_directory("."))
-                       return setup_bare_git_dir(cwd, offset, len, nongit_ok);
+                       return setup_bare_git_dir(&cwd, offset, nongit_ok);
 
                offset_parent = offset;
-               while (--offset_parent > ceil_offset && cwd[offset_parent] != '/');
+               while (--offset_parent > ceil_offset && cwd.buf[offset_parent] != '/');
                if (offset_parent <= ceil_offset)
-                       return setup_nongit(cwd, nongit_ok);
+                       return setup_nongit(cwd.buf, nongit_ok);
                if (one_filesystem) {
-                       dev_t parent_device = get_device_or_die("..", cwd, offset);
+                       dev_t parent_device = get_device_or_die("..", cwd.buf,
+                                                               offset);
                        if (parent_device != current_device) {
                                if (nongit_ok) {
-                                       if (chdir(cwd))
+                                       if (chdir(cwd.buf))
                                                die_errno("Cannot come back to cwd");
                                        *nongit_ok = 1;
                                        return NULL;
                                }
-                               cwd[offset] = '\0';
+                               strbuf_setlen(&cwd, offset);
                                die("Not a git repository (or any parent up to mount point %s)\n"
-                               "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).", cwd);
+                               "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).",
+                                   cwd.buf);
                        }
                }
                if (chdir("..")) {
-                       cwd[offset] = '\0';
-                       die_errno("Cannot change to '%s/..'", cwd);
+                       strbuf_setlen(&cwd, offset);
+                       die_errno("Cannot change to '%s/..'", cwd.buf);
                }
                offset = offset_parent;
        }
@@ -871,11 +929,10 @@ int git_config_perm(const char *var, const char *value)
 
 int check_repository_format_version(const char *var, const char *value, void *cb)
 {
-       if (strcmp(var, "core.repositoryformatversion") == 0)
-               repository_format_version = git_config_int(var, value);
-       else if (strcmp(var, "core.sharedrepository") == 0)
-               shared_repository = git_config_perm(var, value);
-       else if (strcmp(var, "core.bare") == 0) {
+       int ret = check_repo_format(var, value, cb);
+       if (ret)
+               return ret;
+       if (strcmp(var, "core.bare") == 0) {
                is_bare_repository_cfg = git_config_bool(var, value);
                if (is_bare_repository_cfg == 1)
                        inside_work_tree = -1;
@@ -923,3 +980,27 @@ void sanitize_stdfds(void)
        if (fd > 2)
                close(fd);
 }
+
+int daemonize(void)
+{
+#ifdef NO_POSIX_GOODIES
+       errno = ENOSYS;
+       return -1;
+#else
+       switch (fork()) {
+               case 0:
+                       break;
+               case -1:
+                       die_errno("fork failed");
+               default:
+                       exit(0);
+       }
+       if (setsid() == -1)
+               die_errno("setsid failed");
+       close(0);
+       close(1);
+       close(2);
+       sanitize_stdfds();
+       return 0;
+#endif
+}