packaging: Add contrib installation
[platform/upstream/git.git] / setup.c
diff --git a/setup.c b/setup.c
index 860507e..c04cd25 100644 (file)
--- a/setup.c
+++ b/setup.c
@@ -3,6 +3,8 @@
 #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;
@@ -30,6 +32,7 @@ static int abspath_part_inside_repo(char *path)
        char *path0;
        int off;
        const char *work_tree = get_git_work_tree();
+       struct strbuf realpath = STRBUF_INIT;
 
        if (!work_tree)
                return -1;
@@ -38,7 +41,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;
@@ -58,8 +61,10 @@ static int abspath_part_inside_repo(char *path)
                path++;
                if (*path == '/') {
                        *path = '\0';
-                       if (strcmp(real_path(path0), work_tree) == 0) {
+                       strbuf_realpath(&realpath, path0, 1);
+                       if (fspathcmp(realpath.buf, work_tree) == 0) {
                                memmove(path0, path + 1, len - (path - path0));
+                               strbuf_release(&realpath);
                                return 0;
                        }
                        *path = '/';
@@ -67,11 +72,14 @@ static int abspath_part_inside_repo(char *path)
        }
 
        /* check whole path */
-       if (strcmp(real_path(path0), work_tree) == 0) {
+       strbuf_realpath(&realpath, path0, 1);
+       if (fspathcmp(realpath.buf, work_tree) == 0) {
                *path0 = '\0';
+               strbuf_release(&realpath);
                return 0;
        }
 
+       strbuf_release(&realpath);
        return -1;
 }
 
@@ -118,8 +126,13 @@ char *prefix_path_gently(const char *prefix, int len,
 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);
+       if (!r) {
+               const char *hint_path = get_git_work_tree();
+               if (!hint_path)
+                       hint_path = get_git_dir();
+               die(_("'%s' is outside repository at '%s'"), path,
+                   absolute_path(hint_path));
+       }
        return r;
 }
 
@@ -160,10 +173,11 @@ int check_filename(const char *prefix, const char *arg)
                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)
 {
@@ -178,7 +192,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"
@@ -194,9 +208,26 @@ static void NORETURN die_verify_filename(const char *prefix,
  */
 static int looks_like_pathspec(const char *arg)
 {
-       /* anything with a wildcard character */
-       if (!no_wildcard(arg))
-               return 1;
+       const char *p;
+       int escaped = 0;
+
+       /*
+        * Wildcard characters imply the user is looking to match pathspecs
+        * that aren't in the filesystem. Note that this doesn't include
+        * backslash even though it's a glob special; by itself it doesn't
+        * cause any increase in the match. Likewise ignore backslash-escaped
+        * wildcard characters.
+        */
+       for (p = arg; *p; p++) {
+               if (escaped) {
+                       escaped = 0;
+               } else if (is_glob_special(*p)) {
+                       if (*p == '\\')
+                               escaped = 1;
+                       else
+                               return 1;
+               }
+       }
 
        /* long-form pathspec magic */
        if (starts_with(arg, ":("))
@@ -230,10 +261,10 @@ void verify_filename(const char *prefix,
                     int diagnose_misspelt_rev)
 {
        if (*arg == '-')
-               die("bad flag '%s' used after filename", 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);
 }
 
 /*
@@ -312,7 +343,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;
 
@@ -376,21 +409,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
@@ -399,54 +429,122 @@ void setup_work_tree(void)
        if (getenv(GIT_WORK_TREE_ENVIRONMENT))
                setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
 
-       /*
-        * NEEDSWORK: this call can essentially be set_git_dir(get_git_dir())
-        * which can cause some problems when trying to free the old value of
-        * gitdir.
-        */
-       set_git_dir(remove_leading_path(git_dir, work_tree));
        initialized = 1;
 }
 
-static int check_repo_format(const char *var, const char *value, void *vdata)
+static int read_worktree_config(const char *var, const char *value, void *vdata)
 {
        struct repository_format *data = vdata;
-       const char *ext;
 
-       if (strcmp(var, "core.repositoryformatversion") == 0)
-               data->version = git_config_int(var, value);
-       else if (skip_prefix(var, "extensions.", &ext)) {
-               /*
-                * record any known extensions here; otherwise,
-                * we fall through to recording it as unknown, and
-                * check_repository_format will complain
-                */
-               if (!strcmp(ext, "noop"))
-                       ;
-               else if (!strcmp(ext, "preciousobjects"))
-                       data->precious_objects = git_config_bool(var, value);
-               else
-                       string_list_append(&data->unknown_extensions, ext);
-       } else if (strcmp(var, "core.bare") == 0) {
+       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_repository_format_gently(const char *gitdir, int *nongit_ok)
+enum extension_result {
+       EXTENSION_ERROR = -1, /* compatible with error(), etc */
+       EXTENSION_UNKNOWN = 0,
+       EXTENSION_OK = 1
+};
+
+/*
+ * Do not add new extensions to this function. It handles extensions which are
+ * respected even in v0-format repositories for historical compatibility.
+ */
+static enum extension_result handle_extension_v0(const char *var,
+                                                const char *value,
+                                                const char *ext,
+                                                struct repository_format *data)
+{
+               if (!strcmp(ext, "noop")) {
+                       return EXTENSION_OK;
+               } else if (!strcmp(ext, "preciousobjects")) {
+                       data->precious_objects = git_config_bool(var, value);
+                       return EXTENSION_OK;
+               } else if (!strcmp(ext, "partialclone")) {
+                       if (!value)
+                               return config_error_nonbool(var);
+                       data->partial_clone = xstrdup(value);
+                       return EXTENSION_OK;
+               } else if (!strcmp(ext, "worktreeconfig")) {
+                       data->worktree_config = git_config_bool(var, value);
+                       return EXTENSION_OK;
+               }
+
+               return EXTENSION_UNKNOWN;
+}
+
+/*
+ * Record any new extensions in this function.
+ */
+static enum extension_result handle_extension(const char *var,
+                                             const char *value,
+                                             const char *ext,
+                                             struct repository_format *data)
+{
+       if (!strcmp(ext, "noop-v1")) {
+               return EXTENSION_OK;
+       } else if (!strcmp(ext, "objectformat")) {
+               int format;
+
+               if (!value)
+                       return config_error_nonbool(var);
+               format = hash_algo_by_name(value);
+               if (format == GIT_HASH_UNKNOWN)
+                       return error("invalid value for 'extensions.objectformat'");
+               data->hash_algo = format;
+               return EXTENSION_OK;
+       }
+       return EXTENSION_UNKNOWN;
+}
+
+static int check_repo_format(const char *var, const char *value, void *vdata)
+{
+       struct repository_format *data = vdata;
+       const char *ext;
+
+       if (strcmp(var, "core.repositoryformatversion") == 0)
+               data->version = git_config_int(var, value);
+       else if (skip_prefix(var, "extensions.", &ext)) {
+               switch (handle_extension_v0(var, value, ext, data)) {
+               case EXTENSION_ERROR:
+                       return -1;
+               case EXTENSION_OK:
+                       return 0;
+               case EXTENSION_UNKNOWN:
+                       break;
+               }
+
+               switch (handle_extension(var, value, ext, data)) {
+               case EXTENSION_ERROR:
+                       return -1;
+               case EXTENSION_OK:
+                       string_list_append(&data->v1_only_extensions, ext);
+                       return 0;
+               case EXTENSION_UNKNOWN:
+                       string_list_append(&data->unknown_extensions, ext);
+                       return 0;
+               }
+       }
+
+       return read_worktree_config(var, value, vdata);
+}
+
+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);
 
        /*
@@ -454,10 +552,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);
@@ -467,36 +565,95 @@ 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);
+       string_list_clear(&candidate->v1_only_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;
 }
 
+int upgrade_repository_format(int target_version)
+{
+       struct strbuf sb = STRBUF_INIT;
+       struct strbuf err = STRBUF_INIT;
+       struct strbuf repo_version = STRBUF_INIT;
+       struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
+
+       strbuf_git_common_path(&sb, the_repository, "config");
+       read_repository_format(&repo_fmt, sb.buf);
+       strbuf_release(&sb);
+
+       if (repo_fmt.version >= target_version)
+               return 0;
+
+       if (verify_repository_format(&repo_fmt, &err) < 0) {
+               error("cannot upgrade repository format from %d to %d: %s",
+                     repo_fmt.version, target_version, err.buf);
+               strbuf_release(&err);
+               return -1;
+       }
+       if (!repo_fmt.version && repo_fmt.unknown_extensions.nr)
+               return error("cannot upgrade repository format: "
+                            "unknown extension %s",
+                            repo_fmt.unknown_extensions.items[0].string);
+
+       strbuf_addf(&repo_version, "%d", target_version);
+       git_config_set("core.repositoryformatversion", repo_version.buf);
+       strbuf_release(&repo_version);
+       return 1;
+}
+
+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);
+       string_list_clear(&format->v1_only_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)
 {
@@ -517,6 +674,18 @@ int verify_repository_format(const struct repository_format *format,
                return -1;
        }
 
+       if (format->version == 0 && format->v1_only_extensions.nr) {
+               int i;
+
+               strbuf_addstr(err,
+                             _("repo version is 0, but v1-only extensions found:"));
+
+               for (i = 0; i < format->v1_only_extensions.nr; i++)
+                       strbuf_addf(err, "\n\t%s",
+                                   format->v1_only_extensions.items[i].string);
+               return -1;
+       }
+
        return 0;
 }
 
@@ -528,25 +697,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
@@ -563,6 +733,7 @@ const char *read_gitfile_gently(const char *path, int *return_error_code)
        struct stat st;
        int fd;
        ssize_t len;
+       static struct strbuf realpath = STRBUF_INIT;
 
        if (stat(path, &st)) {
                /* NEEDSWORK: discern between ENOENT vs other errors */
@@ -613,7 +784,9 @@ const char *read_gitfile_gently(const char *path, int *return_error_code)
                error_code = READ_GITFILE_ERR_NOT_A_REPO;
                goto cleanup_return;
        }
-       path = real_path(dir);
+
+       strbuf_realpath(&realpath, dir, 1);
+       path = realpath.buf;
 
 cleanup_return:
        if (return_error_code)
@@ -627,6 +800,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);
@@ -635,7 +809,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) {
@@ -649,10 +823,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;
        }
@@ -668,7 +842,7 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
                }
 
                /* #18, #26 */
-               set_git_dir(gitdirenv);
+               set_git_dir(gitdirenv, 0);
                free(gitfile);
                return NULL;
        }
@@ -678,19 +852,19 @@ 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);
                }
        }
        else if (!git_env_bool(GIT_IMPLICIT_WORK_TREE_ENVIRONMENT, 1)) {
                /* #16d */
-               set_git_dir(gitdirenv);
+               set_git_dir(gitdirenv, 0);
                free(gitfile);
                return NULL;
        }
@@ -702,32 +876,33 @@ static const char *setup_explicit_git_dir(const char *gitdirenv,
 
        /* both get_git_work_tree() and cwd are already normalized */
        if (!strcmp(cwd->buf, worktree)) { /* cwd == worktree */
-               set_git_dir(gitdirenv);
+               set_git_dir(gitdirenv, 0);
                free(gitfile);
                return NULL;
        }
 
        offset = dir_inside_of(cwd->buf, worktree);
        if (offset >= 0) {      /* cwd inside worktree? */
-               set_git_dir(real_path(gitdirenv));
+               set_git_dir(gitdirenv, 1);
                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;
        }
 
        /* cwd outside worktree */
-       set_git_dir(gitdirenv);
+       set_git_dir(gitdirenv, 0);
        free(gitfile);
        return NULL;
 }
 
 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 */
@@ -738,27 +913,27 @@ static const char *setup_discovered_git_dir(const char *gitdir,
                if (offset != cwd->len && !is_absolute_path(gitdir))
                        gitdir = to_free = real_pathdup(gitdir, 1);
                if (chdir(cwd->buf))
-                       die_errno("Could not come back to cwd");
-               ret = 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));
+               set_git_dir(gitdir, (offset != cwd->len));
                if (chdir(cwd->buf))
-                       die_errno("Could not come back to cwd");
+                       die_errno(_("cannot come back to cwd"));
                return NULL;
        }
 
        /* #0, #1, #5, #8, #9, #12, #13 */
        set_git_work_tree(".");
        if (strcmp(gitdir, DEFAULT_GIT_DIR_ENVIRONMENT))
-               set_git_dir(gitdir);
+               set_git_dir(gitdir, 0);
        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) */
@@ -771,11 +946,12 @@ 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);
@@ -786,31 +962,21 @@ static const char *setup_bare_git_dir(struct strbuf *cwd, int offset,
 
                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);
+               set_git_dir(cwd->buf, 0);
        }
        else
-               set_git_dir(".");
-       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;
+               set_git_dir(".", 0);
        return NULL;
 }
 
@@ -818,7 +984,7 @@ static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_
 {
        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);
@@ -828,7 +994,7 @@ static dev_t get_device_or_die(const char *path, const char *prefix, int prefix_
 
 /*
  * A "string_list_each_func_t" function that canonicalizes an entry
- * from GIT_CEILING_DIRECTORIES using real_path_if_valid(), or
+ * from GIT_CEILING_DIRECTORIES using real_pathdup(), or
  * discards it if unusable.  The presence of an empty entry in
  * GIT_CEILING_DIRECTORIES turns off canonicalization for all
  * subsequent entries.
@@ -889,7 +1055,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;
 
@@ -917,6 +1083,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>")
@@ -925,7 +1097,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);
@@ -980,7 +1152,7 @@ int discover_git_directory(struct strbuf *commondir,
        struct strbuf dir = STRBUF_INIT, err = STRBUF_INIT;
        size_t gitdir_offset = gitdir->len, cwd_len;
        size_t commondir_offset = commondir->len;
-       struct repository_format candidate;
+       struct repository_format candidate = REPOSITORY_FORMAT_INIT;
 
        if (strbuf_getcwd(&dir))
                return -1;
@@ -1017,9 +1189,11 @@ int discover_git_directory(struct strbuf *commondir,
                strbuf_release(&err);
                strbuf_setlen(commondir, commondir_offset);
                strbuf_setlen(gitdir, gitdir_offset);
+               clear_repository_format(&candidate);
                return -1;
        }
 
+       clear_repository_format(&candidate);
        return 0;
 }
 
@@ -1027,7 +1201,8 @@ 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
@@ -1051,57 +1226,66 @@ 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");
        }
 
        /*
-        * NEEDSWORK: This was a hack in order to get ls-files and grep to have
-        * properly formated output when recursing submodules.  Once ls-files
-        * and grep have been changed to perform this recursing in-process this
-        * needs to be removed.
+        * 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.
         */
-       env_prefix = getenv(GIT_TOPLEVEL_PREFIX_ENVIRONMENT);
-       if (env_prefix)
-               prefix = env_prefix;
-
-       if (prefix)
-               setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
-       else
+       if (nongit_ok && *nongit_ok) {
+               startup_info->have_repository = 0;
+               startup_info->prefix = NULL;
                setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
-
-       startup_info->have_repository = !nongit_ok || !*nongit_ok;
-       startup_info->prefix = prefix;
+       } else {
+               startup_info->have_repository = 1;
+               startup_info->prefix = prefix;
+               if (prefix)
+                       setenv(GIT_PREFIX_ENVIRONMENT, prefix, 1);
+               else
+                       setenv(GIT_PREFIX_ENVIRONMENT, "", 1);
+       }
 
        /*
         * Not all paths through the setup code will call 'set_git_dir()' (which
@@ -1114,18 +1298,23 @@ const char *setup_git_directory_gently(int *nongit_ok)
         * the user has set GIT_DIR.  It may be beneficial to disallow bogus
         * GIT_DIR values at some point in the future.
         */
-       if (startup_info->have_repository || getenv(GIT_DIR_ENVIRONMENT)) {
+       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;
-                       repo_set_gitdir(the_repository, gitdir);
-                       setup_git_env();
+                       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;
 }
@@ -1170,7 +1359,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);
 
@@ -1181,10 +1370,15 @@ int git_config_perm(const char *var, const char *value)
        return -(i & 0666);
 }
 
-void check_repository_format(void)
+void check_repository_format(struct repository_format *fmt)
 {
-       check_repository_format_gently(get_git_dir(), NULL);
+       struct repository_format repo_fmt = REPOSITORY_FORMAT_INIT;
+       if (!fmt)
+               fmt = &repo_fmt;
+       check_repository_format_gently(get_git_dir(), fmt, NULL);
        startup_info->have_repository = 1;
+       repo_set_hash_algo(the_repository, fmt->hash_algo);
+       clear_repository_format(&repo_fmt);
 }
 
 /*
@@ -1212,7 +1406,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);
 }
@@ -1227,12 +1421,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);