Imported Upstream version 2.25.1
[platform/upstream/git.git] / setup.c
diff --git a/setup.c b/setup.c
index 0309c27..e2a479a 100644 (file)
--- a/setup.c
+++ b/setup.c
@@ -1,6 +1,10 @@
 #include "cache.h"
+#include "repository.h"
+#include "config.h"
 #include "dir.h"
 #include "string-list.h"
+#include "chdir-notify.h"
+#include "promisor-remote.h"
 
 static int inside_git_dir = -1;
 static int inside_work_tree = -1;
@@ -36,7 +40,7 @@ static int abspath_part_inside_repo(char *path)
        off = offset_1st_component(path);
 
        /* check if work tree is already the prefix */
-       if (wtlen <= len && !strncmp(path, work_tree, wtlen)) {
+       if (wtlen <= len && !fspathncmp(path, work_tree, wtlen)) {
                if (path[wtlen] == '/') {
                        memmove(path, path + wtlen + 1, len - wtlen);
                        return 0;
@@ -56,7 +60,7 @@ static int abspath_part_inside_repo(char *path)
                path++;
                if (*path == '/') {
                        *path = '\0';
-                       if (strcmp(real_path(path0), work_tree) == 0) {
+                       if (fspathcmp(real_path(path0), work_tree) == 0) {
                                memmove(path0, path + 1, len - (path - path0));
                                return 0;
                        }
@@ -65,7 +69,7 @@ static int abspath_part_inside_repo(char *path)
        }
 
        /* check whole path */
-       if (strcmp(real_path(path0), work_tree) == 0) {
+       if (fspathcmp(real_path(path0), work_tree) == 0) {
                *path0 = '\0';
                return 0;
        }
@@ -117,7 +121,7 @@ char *prefix_path(const char *prefix, int len, const char *path)
 {
        char *r = prefix_path_gently(prefix, len, NULL, path);
        if (!r)
-               die("'%s' is outside repository", path);
+               die(_("'%s' is outside repository"), path);
        return r;
 }
 
@@ -134,30 +138,35 @@ int path_inside_repo(const char *prefix, const char *path)
 
 int check_filename(const char *prefix, const char *arg)
 {
-       const char *name;
        char *to_free = NULL;
        struct stat st;
 
-       if (starts_with(arg, ":/")) {
-               if (arg[2] == '\0') /* ":/" is root dir, always exists */
+       if (skip_prefix(arg, ":/", &arg)) {
+               if (!*arg) /* ":/" is root dir, always exists */
                        return 1;
-               name = arg + 2;
-       } else if (prefix)
-               name = to_free = prefix_filename(prefix, arg);
-       else
-               name = arg;
-       if (!lstat(name, &st)) {
+               prefix = NULL;
+       } else if (skip_prefix(arg, ":!", &arg) ||
+                  skip_prefix(arg, ":^", &arg)) {
+               if (!*arg) /* excluding everything is silly, but allowed */
+                       return 1;
+       }
+
+       if (prefix)
+               arg = to_free = prefix_filename(prefix, arg);
+
+       if (!lstat(arg, &st)) {
                free(to_free);
                return 1; /* file exists */
        }
-       if (errno == ENOENT || errno == ENOTDIR) {
+       if (is_missing_file_error(errno)) {
                free(to_free);
                return 0; /* file does not exist */
        }
-       die_errno("failed to stat '%s'", arg);
+       die_errno(_("failed to stat '%s'"), arg);
 }
 
-static void NORETURN die_verify_filename(const char *prefix,
+static void NORETURN die_verify_filename(struct repository *r,
+                                        const char *prefix,
                                         const char *arg,
                                         int diagnose_misspelt_rev)
 {
@@ -172,7 +181,7 @@ static void NORETURN die_verify_filename(const char *prefix,
         * let maybe_die_on_misspelt_object_name() even trigger.
         */
        if (!(arg[0] == ':' && !isalnum(arg[1])))
-               maybe_die_on_misspelt_object_name(arg, prefix);
+               maybe_die_on_misspelt_object_name(r, arg, prefix);
 
        /* ... or fall back the most general message. */
        die(_("ambiguous argument '%s': unknown revision or path not in the working tree.\n"
@@ -182,6 +191,24 @@ static void NORETURN die_verify_filename(const char *prefix,
 }
 
 /*
+ * Check for arguments that don't resolve as actual files,
+ * but which look sufficiently like pathspecs that we'll consider
+ * them such for the purposes of rev/pathspec DWIM parsing.
+ */
+static int looks_like_pathspec(const char *arg)
+{
+       /* anything with a wildcard character */
+       if (!no_wildcard(arg))
+               return 1;
+
+       /* long-form pathspec magic */
+       if (starts_with(arg, ":("))
+               return 1;
+
+       return 0;
+}
+
+/*
  * Verify a filename that we got as an argument for a pathspec
  * entry. Note that a filename that begins with "-" never verifies
  * as true, because even if such a filename were to exist, we want
@@ -206,10 +233,10 @@ void verify_filename(const char *prefix,
                     int diagnose_misspelt_rev)
 {
        if (*arg == '-')
-               die("bad flag '%s' used after filename", arg);
-       if (check_filename(prefix, arg) || !no_wildcard(arg))
+               die(_("option '%s' must come before non-option arguments"), arg);
+       if (looks_like_pathspec(arg) || check_filename(prefix, arg))
                return;
-       die_verify_filename(prefix, arg, diagnose_misspelt_rev);
+       die_verify_filename(the_repository, prefix, arg, diagnose_misspelt_rev);
 }
 
 /*
@@ -288,7 +315,9 @@ int is_git_directory(const char *suspect)
        size_t len;
 
        /* Check worktree-related signatures */
-       strbuf_addf(&path, "%s/HEAD", suspect);
+       strbuf_addstr(&path, suspect);
+       strbuf_complete(&path, '/');
+       strbuf_addstr(&path, "HEAD");
        if (validate_headref(path.buf))
                goto done;
 
@@ -352,21 +381,18 @@ int is_inside_work_tree(void)
 
 void setup_work_tree(void)
 {
-       const char *work_tree, *git_dir;
+       const char *work_tree;
        static int initialized = 0;
 
        if (initialized)
                return;
 
        if (work_tree_config_is_bogus)
-               die("unable to set up work tree using invalid config");
+               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))
-               git_dir = real_path(get_git_dir());
-       if (!work_tree || chdir(work_tree))
-               die("This operation must be run in a work tree");
+       if (!work_tree || chdir_notify(work_tree))
+               die(_("this operation must be run in a work tree"));
 
        /*
         * Make sure subsequent git processes find correct worktree
@@ -375,10 +401,24 @@ void setup_work_tree(void)
        if (getenv(GIT_WORK_TREE_ENVIRONMENT))
                setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
 
-       set_git_dir(remove_leading_path(git_dir, work_tree));
        initialized = 1;
 }
 
+static int read_worktree_config(const char *var, const char *value, void *vdata)
+{
+       struct repository_format *data = vdata;
+
+       if (strcmp(var, "core.bare") == 0) {
+               data->is_bare = git_config_bool(var, value);
+       } else if (strcmp(var, "core.worktree") == 0) {
+               if (!value)
+                       return config_error_nonbool(var);
+               free(data->work_tree);
+               data->work_tree = xstrdup(value);
+       }
+       return 0;
+}
+
 static int check_repo_format(const char *var, const char *value, void *vdata)
 {
        struct repository_format *data = vdata;
@@ -396,28 +436,28 @@ static int check_repo_format(const char *var, const char *value, void *vdata)
                        ;
                else if (!strcmp(ext, "preciousobjects"))
                        data->precious_objects = git_config_bool(var, value);
+               else if (!strcmp(ext, "partialclone")) {
+                       if (!value)
+                               return config_error_nonbool(var);
+                       data->partial_clone = xstrdup(value);
+               } else if (!strcmp(ext, "worktreeconfig"))
+                       data->worktree_config = git_config_bool(var, value);
                else
                        string_list_append(&data->unknown_extensions, ext);
-       } else if (strcmp(var, "core.bare") == 0) {
-               data->is_bare = git_config_bool(var, value);
-       } else if (strcmp(var, "core.worktree") == 0) {
-               if (!value)
-                       return config_error_nonbool(var);
-               data->work_tree = xstrdup(value);
        }
-       return 0;
+
+       return read_worktree_config(var, value, vdata);
 }
 
-static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
+static int check_repository_format_gently(const char *gitdir, struct repository_format *candidate, int *nongit_ok)
 {
        struct strbuf sb = STRBUF_INIT;
        struct strbuf err = STRBUF_INIT;
-       struct repository_format candidate;
        int has_common;
 
        has_common = get_common_dir(&sb, gitdir);
        strbuf_addstr(&sb, "/config");
-       read_repository_format(&candidate, sb.buf);
+       read_repository_format(candidate, sb.buf);
        strbuf_release(&sb);
 
        /*
@@ -425,10 +465,10 @@ static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
         * we treat a missing config as a silent "ok", even when nongit_ok
         * is unset.
         */
-       if (candidate.version < 0)
+       if (candidate->version < 0)
                return 0;
 
-       if (verify_repository_format(&candidate, &err) < 0) {
+       if (verify_repository_format(candidate, &err) < 0) {
                if (nongit_ok) {
                        warning("%s", err.buf);
                        strbuf_release(&err);
@@ -438,36 +478,62 @@ static int check_repository_format_gently(const char *gitdir, int *nongit_ok)
                die("%s", err.buf);
        }
 
-       repository_format_precious_objects = candidate.precious_objects;
-       string_list_clear(&candidate.unknown_extensions, 0);
+       repository_format_precious_objects = candidate->precious_objects;
+       set_repository_format_partial_clone(candidate->partial_clone);
+       repository_format_worktree_config = candidate->worktree_config;
+       string_list_clear(&candidate->unknown_extensions, 0);
+
+       if (repository_format_worktree_config) {
+               /*
+                * pick up core.bare and core.worktree from per-worktree
+                * config if present
+                */
+               strbuf_addf(&sb, "%s/config.worktree", gitdir);
+               git_config_from_file(read_worktree_config, sb.buf, candidate);
+               strbuf_release(&sb);
+               has_common = 0;
+       }
+
        if (!has_common) {
-               if (candidate.is_bare != -1) {
-                       is_bare_repository_cfg = candidate.is_bare;
+               if (candidate->is_bare != -1) {
+                       is_bare_repository_cfg = candidate->is_bare;
                        if (is_bare_repository_cfg == 1)
                                inside_work_tree = -1;
                }
-               if (candidate.work_tree) {
+               if (candidate->work_tree) {
                        free(git_work_tree_cfg);
-                       git_work_tree_cfg = candidate.work_tree;
+                       git_work_tree_cfg = xstrdup(candidate->work_tree);
                        inside_work_tree = -1;
                }
-       } else {
-               free(candidate.work_tree);
        }
 
        return 0;
 }
 
+static void init_repository_format(struct repository_format *format)
+{
+       const struct repository_format fresh = REPOSITORY_FORMAT_INIT;
+
+       memcpy(format, &fresh, sizeof(fresh));
+}
+
 int read_repository_format(struct repository_format *format, const char *path)
 {
-       memset(format, 0, sizeof(*format));
-       format->version = -1;
-       format->is_bare = -1;
-       string_list_init(&format->unknown_extensions, 1);
+       clear_repository_format(format);
        git_config_from_file(check_repo_format, path, format);
+       if (format->version == -1)
+               clear_repository_format(format);
        return format->version;
 }
 
+void clear_repository_format(struct repository_format *format)
+{
+       string_list_clear(&format->unknown_extensions, 0);
+       free(format->work_tree);
+       free(format->partial_clone);
+       init_repository_format(format);
+}
+
 int verify_repository_format(const struct repository_format *format,
                             struct strbuf *err)
 {
@@ -499,25 +565,26 @@ void read_gitfile_error_die(int error_code, const char *path, const char *dir)
                /* non-fatal; follow return path */
                break;
        case READ_GITFILE_ERR_OPEN_FAILED:
-               die_errno("Error opening '%s'", path);
+               die_errno(_("error opening '%s'"), path);
        case READ_GITFILE_ERR_TOO_LARGE:
-               die("Too large to be a .git file: '%s'", path);
+               die(_("too large to be a .git file: '%s'"), path);
        case READ_GITFILE_ERR_READ_FAILED:
-               die("Error reading %s", path);
+               die(_("error reading %s"), path);
        case READ_GITFILE_ERR_INVALID_FORMAT:
-               die("Invalid gitfile format: %s", path);
+               die(_("invalid gitfile format: %s"), path);
        case READ_GITFILE_ERR_NO_PATH:
-               die("No path in gitfile: %s", path);
+               die(_("no path in gitfile: %s"), path);
        case READ_GITFILE_ERR_NOT_A_REPO:
-               die("Not a git repository: %s", dir);
+               die(_("not a git repository: %s"), dir);
        default:
-               die("BUG: unknown error code");
+               BUG("unknown error code");
        }
 }
 
 /*
  * Try to read the location of the git directory from the .git file,
- * return path to git directory if found.
+ * return path to git directory if found. The return value comes from
+ * a shared buffer.
  *
  * 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
@@ -598,6 +665,7 @@ cleanup_return:
 
 static const char *setup_explicit_git_dir(const char *gitdirenv,
                                          struct strbuf *cwd,
+                                         struct repository_format *repo_fmt,
                                          int *nongit_ok)
 {
        const char *work_tree_env = getenv(GIT_WORK_TREE_ENVIRONMENT);
@@ -606,7 +674,7 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
        int offset;
 
        if (PATH_MAX - 40 < strlen(gitdirenv))
-               die("'$%s' too big", GIT_DIR_ENVIRONMENT);
+               die(_("'$%s' too big"), GIT_DIR_ENVIRONMENT);
 
        gitfile = (char*)read_gitfile(gitdirenv);
        if (gitfile) {
@@ -620,10 +688,10 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
                        free(gitfile);
                        return NULL;
                }
-               die("Not a git repository: '%s'", gitdirenv);
+               die(_("not a git repository: '%s'"), gitdirenv);
        }
 
-       if (check_repository_format_gently(gitdirenv, nongit_ok)) {
+       if (check_repository_format_gently(gitdirenv, repo_fmt, nongit_ok)) {
                free(gitfile);
                return NULL;
        }
@@ -649,12 +717,12 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
                else {
                        char *core_worktree;
                        if (chdir(gitdirenv))
-                               die_errno("Could not chdir to '%s'", gitdirenv);
+                               die_errno(_("cannot chdir to '%s'"), gitdirenv);
                        if (chdir(git_work_tree_cfg))
-                               die_errno("Could not chdir to '%s'", git_work_tree_cfg);
+                               die_errno(_("cannot chdir to '%s'"), git_work_tree_cfg);
                        core_worktree = xgetcwd();
                        if (chdir(cwd->buf))
-                               die_errno("Could not come back to cwd");
+                               die_errno(_("cannot come back to cwd"));
                        set_git_work_tree(core_worktree);
                        free(core_worktree);
                }
@@ -682,7 +750,7 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
        if (offset >= 0) {      /* cwd inside worktree? */
                set_git_dir(real_path(gitdirenv));
                if (chdir(worktree))
-                       die_errno("Could not chdir to '%s'", worktree);
+                       die_errno(_("cannot chdir to '%s'"), worktree);
                strbuf_addch(cwd, '/');
                free(gitfile);
                return cwd->buf + offset;
@@ -696,25 +764,31 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
 
 static const char *setup_discovered_git_dir(const char *gitdir,
                                            struct strbuf *cwd, int offset,
+                                           struct repository_format *repo_fmt,
                                            int *nongit_ok)
 {
-       if (check_repository_format_gently(gitdir, nongit_ok))
+       if (check_repository_format_gently(gitdir, repo_fmt, nongit_ok))
                return NULL;
 
        /* --work-tree is set without --git-dir; use discovered one */
        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
+               char *to_free = NULL;
+               const char *ret;
+
                if (offset != cwd->len && !is_absolute_path(gitdir))
-                       gitdir = real_pathdup(gitdir, 1);
+                       gitdir = to_free = real_pathdup(gitdir, 1);
                if (chdir(cwd->buf))
-                       die_errno("Could not come back to cwd");
-               return setup_explicit_git_dir(gitdir, cwd, nongit_ok);
+                       die_errno(_("cannot come back to cwd"));
+               ret = setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
+               free(to_free);
+               return ret;
        }
 
        /* #16.2, #17.2, #20.2, #21.2, #24, #25, #28, #29 (see t1510) */
        if (is_bare_repository_cfg > 0) {
                set_git_dir(offset == cwd->len ? gitdir : real_path(gitdir));
                if (chdir(cwd->buf))
-                       die_errno("Could not come back to cwd");
+                       die_errno(_("cannot come back to cwd"));
                return NULL;
        }
 
@@ -724,7 +798,7 @@ static const char *setup_discovered_git_dir(const char *gitdir,
                set_git_dir(gitdir);
        inside_git_dir = 0;
        inside_work_tree = 1;
-       if (offset == cwd->len)
+       if (offset >= cwd->len)
                return NULL;
 
        /* Make "offset" point past the '/' (already the case for root dirs) */
@@ -737,30 +811,31 @@ static const char *setup_discovered_git_dir(const char *gitdir,
 
 /* #16.1, #17.1, #20.1, #21.1, #22.1 (see t1510) */
 static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
+                                     struct repository_format *repo_fmt,
                                      int *nongit_ok)
 {
        int root_len;
 
-       if (check_repository_format_gently(".", nongit_ok))
+       if (check_repository_format_gently(".", repo_fmt, nongit_ok))
                return NULL;
 
        setenv(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, "0", 1);
 
        /* --work-tree is set without --git-dir; use discovered one */
        if (getenv(GIT_WORK_TREE_ENVIRONMENT) || git_work_tree_cfg) {
-               const char *gitdir;
+               static const char *gitdir;
 
                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, nongit_ok);
+                       die_errno(_("cannot come back to cwd"));
+               return setup_explicit_git_dir(gitdir, cwd, repo_fmt, nongit_ok);
        }
 
        inside_git_dir = 1;
        inside_work_tree = 0;
        if (offset != cwd->len) {
                if (chdir(cwd->buf))
-                       die_errno("Cannot come back to cwd");
+                       die_errno(_("cannot come back to cwd"));
                root_len = offset_1st_component(cwd->buf);
                strbuf_setlen(cwd, offset > root_len ? offset : root_len);
                set_git_dir(cwd->buf);
@@ -770,21 +845,11 @@ static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
        return NULL;
 }
 
-static const char *setup_nongit(const char *cwd, int *nongit_ok)
-{
-       if (!nongit_ok)
-               die(_("Not a git repository (or any of the parent directories): %s"), DEFAULT_GIT_DIR_ENVIRONMENT);
-       if (chdir(cwd))
-               die_errno(_("Cannot come back to cwd"));
-       *nongit_ok = 1;
-       return NULL;
-}
-
 static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_len)
 {
        struct stat buf;
        if (stat(path, &buf)) {
-               die_errno("failed to stat '%*s%s%s'",
+               die_errno(_("failed to stat '%*s%s%s'"),
                                prefix_len,
                                prefix ? prefix : "",
                                prefix ? "/" : "", path);
@@ -855,7 +920,7 @@ static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
        const char *env_ceiling_dirs = getenv(CEILING_DIRECTORIES_ENVIRONMENT);
        struct string_list ceiling_dirs = STRING_LIST_INIT_DUP;
        const char *gitdirenv;
-       int ceil_offset = -1, min_offset = has_dos_drive_prefix(dir->buf) ? 3 : 1;
+       int ceil_offset = -1, min_offset = offset_1st_component(dir->buf);
        dev_t current_device = 0;
        int one_filesystem = 1;
 
@@ -883,6 +948,12 @@ static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
        if (ceil_offset < 0)
                ceil_offset = min_offset - 2;
 
+       if (min_offset && min_offset == dir->len &&
+           !is_dir_sep(dir->buf[min_offset - 1])) {
+               strbuf_addch(dir, '/');
+               min_offset++;
+       }
+
        /*
         * Test in the following order (relative to the dir):
         * - .git (file containing "gitdir: <path>")
@@ -891,7 +962,7 @@ static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
         * - ../.git
         * - ../.git/
         * - ../ (bare)
-        * - ../../.git/
+        * - ../../.git
         *   etc.
         */
        one_filesystem = !git_env_bool("GIT_DISCOVERY_ACROSS_FILESYSTEM", 0);
@@ -940,19 +1011,21 @@ static enum discovery_result setup_git_directory_gently_1(struct strbuf *dir,
        }
 }
 
-const char *discover_git_directory(struct strbuf *gitdir)
+int discover_git_directory(struct strbuf *commondir,
+                          struct strbuf *gitdir)
 {
        struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
        size_t gitdir_offset = gitdir->len, cwd_len;
-       struct repository_format candidate;
+       size_t commondir_offset = commondir->len;
+       struct repository_format candidate = REPOSITORY_FORMAT_INIT;
 
        if (strbuf_getcwd(&dir))
-               return NULL;
+               return -1;
 
        cwd_len = dir.len;
        if (setup_git_directory_gently_1(&dir, gitdir, 0) <= 0) {
                strbuf_release(&dir);
-               return NULL;
+               return -1;
        }
 
        /*
@@ -968,8 +1041,10 @@ const char *discover_git_directory(struct strbuf *gitdir)
                strbuf_insert(gitdir, gitdir_offset, dir.buf, dir.len);
        }
 
+       get_common_dir(commondir, gitdir->buf + gitdir_offset);
+
        strbuf_reset(&dir);
-       strbuf_addf(&dir, "%s/config", gitdir->buf + gitdir_offset);
+       strbuf_addf(&dir, "%s/config", commondir->buf + commondir_offset);
        read_repository_format(&candidate, dir.buf);
        strbuf_release(&dir);
 
@@ -977,17 +1052,22 @@ const char *discover_git_directory(struct strbuf *gitdir)
                warning("ignoring git dir '%s': %s",
                        gitdir->buf + gitdir_offset, err.buf);
                strbuf_release(&err);
-               return NULL;
+               strbuf_setlen(commondir, commondir_offset);
+               strbuf_setlen(gitdir, gitdir_offset);
+               clear_repository_format(&candidate);
+               return -1;
        }
 
-       return gitdir->buf + gitdir_offset;
+       clear_repository_format(&candidate);
+       return 0;
 }
 
 const char *setup_git_directory_gently(int *nongit_ok)
 {
        static struct strbuf cwd = STRBUF_INIT;
        struct strbuf dir = STRBUF_INIT, gitdir = STRBUF_INIT;
-       const char *prefix, *env_prefix;
+       const char *prefix = NULL;
+       struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
 
        /*
         * We may have read an incomplete configuration before
@@ -1011,54 +1091,95 @@ const char *setup_git_directory_gently(int *nongit_ok)
        strbuf_addbuf(&dir, &cwd);
 
        switch (setup_git_directory_gently_1(&dir, &gitdir, 1)) {
-       case GIT_DIR_NONE:
-               prefix = NULL;
-               break;
        case GIT_DIR_EXPLICIT:
-               prefix = setup_explicit_git_dir(gitdir.buf, &cwd, nongit_ok);
+               prefix = setup_explicit_git_dir(gitdir.buf, &cwd, &repo_fmt, nongit_ok);
                break;
        case GIT_DIR_DISCOVERED:
                if (dir.len < cwd.len && chdir(dir.buf))
-                       die(_("Cannot change to '%s'"), dir.buf);
+                       die(_("cannot change to '%s'"), dir.buf);
                prefix = setup_discovered_git_dir(gitdir.buf, &cwd, dir.len,
-                                                 nongit_ok);
+                                                 &repo_fmt, nongit_ok);
                break;
        case GIT_DIR_BARE:
                if (dir.len < cwd.len && chdir(dir.buf))
-                       die(_("Cannot change to '%s'"), dir.buf);
-               prefix = setup_bare_git_dir(&cwd, dir.len, nongit_ok);
+                       die(_("cannot change to '%s'"), dir.buf);
+               prefix = setup_bare_git_dir(&cwd, dir.len, &repo_fmt, nongit_ok);
                break;
        case GIT_DIR_HIT_CEILING:
-               prefix = setup_nongit(cwd.buf, nongit_ok);
+               if (!nongit_ok)
+                       die(_("not a git repository (or any of the parent directories): %s"),
+                           DEFAULT_GIT_DIR_ENVIRONMENT);
+               *nongit_ok = 1;
                break;
        case GIT_DIR_HIT_MOUNT_POINT:
-               if (nongit_ok) {
-                       *nongit_ok = 1;
-                       strbuf_release(&cwd);
-                       strbuf_release(&dir);
-                       return NULL;
-               }
-               die(_("Not a git repository (or any parent up to mount point %s)\n"
-                     "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
-                   dir.buf);
+               if (!nongit_ok)
+                       die(_("not a git repository (or any parent up to mount point %s)\n"
+                             "Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
+                           dir.buf);
+               *nongit_ok = 1;
+               break;
+       case GIT_DIR_NONE:
+               /*
+                * As a safeguard against setup_git_directory_gently_1 returning
+                * this value, fallthrough to BUG. Otherwise it is possible to
+                * set startup_info->have_repository to 1 when we did nothing to
+                * find a repository.
+                */
        default:
-               die("BUG: unhandled setup_git_directory_1() result");
+               BUG("unhandled setup_git_directory_1() result");
        }
 
-       env_prefix = getenv(GIT_TOPLEVEL_PREFIX_ENVIRONMENT);
-       if (env_prefix)
-               prefix = env_prefix;
-
-       if (prefix)
-               setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
-       else
+       /*
+        * At this point, nongit_ok is stable. If it is non-NULL and points
+        * to a non-zero value, then this means that we haven't found a
+        * repository and that the caller expects startup_info to reflect
+        * this.
+        *
+        * Regardless of the state of nongit_ok, startup_info->prefix and
+        * the GIT_PREFIX environment variable must always match. For details
+        * see Documentation/config/alias.txt.
+        */
+       if (nongit_ok && *nongit_ok) {
+               startup_info->have_repository = 0;
+               startup_info->prefix = NULL;
                setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
+       } else {
+               startup_info->have_repository = 1;
+               startup_info->prefix = prefix;
+               if (prefix)
+                       setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
+               else
+                       setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
+       }
 
-       startup_info->have_repository = !nongit_ok || !*nongit_ok;
-       startup_info->prefix = prefix;
+       /*
+        * Not all paths through the setup code will call 'set_git_dir()' (which
+        * directly sets up the environment) so in order to guarantee that the
+        * environment is in a consistent state after setup, explicitly setup
+        * the environment if we have a repository.
+        *
+        * NEEDSWORK: currently we allow bogus GIT_DIR values to be set in some
+        * code paths so we also need to explicitly setup the environment if
+        * the user has set GIT_DIR.  It may be beneficial to disallow bogus
+        * GIT_DIR values at some point in the future.
+        */
+       if (/* GIT_DIR_EXPLICIT, GIT_DIR_DISCOVERED, GIT_DIR_BARE */
+           startup_info->have_repository ||
+           /* GIT_DIR_EXPLICIT */
+           getenv(GIT_DIR_ENVIRONMENT)) {
+               if (!the_repository->gitdir) {
+                       const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
+                       if (!gitdir)
+                               gitdir = DEFAULT_GIT_DIR_ENVIRONMENT;
+                       setup_git_env(gitdir);
+               }
+               if (startup_info->have_repository)
+                       repo_set_hash_algo(the_repository, repo_fmt.hash_algo);
+       }
 
        strbuf_release(&dir);
        strbuf_release(&gitdir);
+       clear_repository_format(&repo_fmt);
 
        return prefix;
 }
@@ -1103,7 +1224,7 @@ int git_config_perm(const char *var, const char *value)
        /* A filemode value was given: 0xxx */
 
        if ((i & 0600) != 0600)
-               die(_("Problem with core.sharedRepository filemode value "
+               die(_("problem with core.sharedRepository filemode value "
                    "(0%.3o).\nThe owner of files must always have "
                    "read and write permissions."), i);
 
@@ -1116,8 +1237,10 @@ int git_config_perm(const char *var, const char *value)
 
 void check_repository_format(void)
 {
-       check_repository_format_gently(get_git_dir(), NULL);
+       struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
+       check_repository_format_gently(get_git_dir(), &repo_fmt, NULL);
        startup_info->have_repository = 1;
+       clear_repository_format(&repo_fmt);
 }
 
 /*
@@ -1145,7 +1268,7 @@ void sanitize_stdfds(void)
        while (fd != -1 && fd < 2)
                fd = dup(fd);
        if (fd == -1)
-               die_errno("open /dev/null or dup failed");
+               die_errno(_("open /dev/null or dup failed"));
        if (fd > 2)
                close(fd);
 }
@@ -1160,12 +1283,12 @@ int daemonize(void)
                case 0:
                        break;
                case -1:
-                       die_errno("fork failed");
+                       die_errno(_("fork failed"));
                default:
                        exit(0);
        }
        if (setsid() == -1)
-               die_errno("setsid failed");
+               die_errno(_("setsid failed"));
        close(0);
        close(1);
        close(2);