]> git.ipfire.org Git - thirdparty/git.git/commitdiff
setup: fix reinit of repos with incompatible GIT_DEFAULT_HASH
authorPatrick Steinhardt <ps@pks.im>
Thu, 30 Jan 2025 16:24:19 +0000 (17:24 +0100)
committerJunio C Hamano <gitster@pobox.com>
Thu, 30 Jan 2025 22:36:41 +0000 (14:36 -0800)
The exact same issue as described in the preceding commit also exists
for GIT_DEFAULT_HASH. Thus, reinitializing a repository that e.g. uses
SHA1 with `GIT_DEFAULT_HASH=sha256 git init` will cause the object
format of that repository to change to SHA256. This is of course bogus
as any existing objects and refs will not be converted, thus causing
repository corruption:

    $ git init repo
    Initialized empty Git repository in /tmp/repo/.git/
    $ cd repo/
    $ git commit --allow-empty -m message
    [main (root-commit) 35a7344] message
    $ GIT_DEFAULT_HASH=sha256 git init
    Reinitialized existing Git repository in /tmp/repo/.git/
    $ git show
    fatal: your current branch appears to be broken

Fix the issue by ignoring the environment variable in case the repo has
already been initialized with an object hash.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
setup.c
t/t0001-init.sh

diff --git a/setup.c b/setup.c
index 53ffeabc5b44d0214830f8279ec11c870f8d0a79..7da7aa8984b6df3b73e6dbac5bc75184ee073d17 100644 (file)
--- a/setup.c
+++ b/setup.c
@@ -2517,7 +2517,9 @@ static void repository_format_configure(struct repository_format *repo_fmt,
                int env_algo = hash_algo_by_name(env);
                if (env_algo == GIT_HASH_UNKNOWN)
                        die(_("unknown hash algorithm '%s'"), env);
-               repo_fmt->hash_algo = env_algo;
+               if (repo_fmt->version < 0 ||
+                   repo_fmt->hash_algo == GIT_HASH_UNKNOWN)
+                       repo_fmt->hash_algo = env_algo;
        } else if (cfg.hash != GIT_HASH_UNKNOWN) {
                repo_fmt->hash_algo = cfg.hash;
        }
index 6dff8b75f1f991bc7c7d3de2ce47ca26a463b1cc..c49d9e0d382990cc87daec8ba4f03f1bc7f956cd 100755 (executable)
@@ -586,6 +586,18 @@ test_expect_success 'GIT_DEFAULT_HASH overrides init.defaultObjectFormat' '
        echo sha256 >expected
 '
 
+for hash in sha1 sha256
+do
+       test_expect_success "reinit repository with GIT_DEFAULT_HASH=$hash does not change format" '
+               test_when_finished "rm -rf repo" &&
+               git init repo &&
+               git -C repo rev-parse --show-object-format >expect &&
+               GIT_DEFAULT_HASH=$hash git init repo &&
+               git -C repo rev-parse --show-object-format >actual &&
+               test_cmp expect actual
+       '
+done
+
 test_expect_success 'extensions.objectFormat is not allowed with repo version 0' '
        test_when_finished "rm -rf explicit-v0" &&
        git init --object-format=sha256 explicit-v0 &&