diff mbox series

[v4,07/13] builtin/rev-parse: allow shortening to more than 40 hex characters

Message ID 61160303108133f0225aae0f0776fa15c7ee07ec.1715057362.git.ps@pks.im (mailing list archive)
State New, archived
Headers show
Series Stop relying on SHA1 fallback for `the_hash_algo` | expand

Commit Message

Patrick Steinhardt May 7, 2024, 4:53 a.m. UTC
The `--short=` option for git-rev-parse(1) allows the user to specify
to how many characters object IDs should be shortened to. The option is
broken though for SHA256 repositories because we set the maximum allowed
hash size to `the_hash_algo->hexsz` before we have even set up the repo.
Consequently, `the_hash_algo` will always be SHA1 and thus we truncate
every hash after at most 40 characters.

Fix this by accessing `the_hash_algo` only after we have set up the
repo.

Signed-off-by: Patrick Steinhardt <ps@pks.im>
---
 builtin/rev-parse.c  | 5 ++---
 t/t1500-rev-parse.sh | 6 ++++++
 2 files changed, 8 insertions(+), 3 deletions(-)
diff mbox series

Patch

diff --git a/builtin/rev-parse.c b/builtin/rev-parse.c
index af79538632..7d10ee33c4 100644
--- a/builtin/rev-parse.c
+++ b/builtin/rev-parse.c
@@ -686,9 +686,8 @@  int cmd_rev_parse(int argc, const char **argv, const char *prefix)
 	unsigned int flags = 0;
 	const char *name = NULL;
 	struct object_context unused;
 	struct strbuf buf = STRBUF_INIT;
-	const int hexsz = the_hash_algo->hexsz;
 	int seen_end_of_options = 0;
 	enum format_type format = FORMAT_DEFAULT;
 
 	if (argc > 1 && !strcmp("--parseopt", argv[1]))
@@ -862,10 +861,10 @@  int cmd_rev_parse(int argc, const char **argv, const char *prefix)
 					continue;
 				abbrev = strtoul(arg, NULL, 10);
 				if (abbrev < MINIMUM_ABBREV)
 					abbrev = MINIMUM_ABBREV;
-				else if (hexsz <= abbrev)
-					abbrev = hexsz;
+				else if ((int)the_hash_algo->hexsz <= abbrev)
+					abbrev = the_hash_algo->hexsz;
 				continue;
 			}
 			if (!strcmp(arg, "--sq")) {
 				output_sq = 1;
diff --git a/t/t1500-rev-parse.sh b/t/t1500-rev-parse.sh
index a669e592f1..30c31918fd 100755
--- a/t/t1500-rev-parse.sh
+++ b/t/t1500-rev-parse.sh
@@ -303,5 +303,11 @@  test_expect_success 'rev-parse --bisect includes bad, excludes good' '
 	git rev-parse --symbolic-full-name --bisect >actual &&
 	test_cmp expect actual
 '
 
+test_expect_success '--short= truncates to the actual hash length' '
+	git rev-parse HEAD >expect &&
+	git rev-parse --short=100 HEAD >actual &&
+	test_cmp expect actual
+'
+
 test_done