From 47556f6815148ed960a727fd122f7162345544c3 Mon Sep 17 00:00:00 2001 From: Sebastian Thiel Date: Tue, 5 Apr 2022 18:06:09 +0800 Subject: [PATCH] feat: auto-calculation of a good hex-len, like what git does (#298) If the `core.abbrev` value isn't set or is set to `auto`. --- git-repository/src/id.rs | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/git-repository/src/id.rs b/git-repository/src/id.rs index 2b5d15d53f6..f609d0e0186 100644 --- a/git-repository/src/id.rs +++ b/git-repository/src/id.rs @@ -27,11 +27,16 @@ impl<'repo> Id<'repo> { /// Turn this object id into a shortened id with a length in hex as configured by `core.abbrev`. pub fn shorten(&self) -> Result { - let hex_len = self.repo.config.hex_len.unwrap_or( - // TODO: obtain calculated value - 7, - ); - // NOTE: this error shouldn't be possible + let hex_len = self + .repo + .config + .hex_len + .map_or_else( + || self.repo.objects.packed_object_count().map(calculate_auto_hex_len), + Ok, + ) + .map_err(|err| shorten::Error::Find(err))?; + let prefix = git_odb::find::PotentialPrefix::new(self.inner, hex_len) .expect("BUG: internal hex-len must always be valid"); Ok(self @@ -43,6 +48,12 @@ impl<'repo> Id<'repo> { } } +fn calculate_auto_hex_len(num_packed_objects: u64) -> usize { + let mut len = 64 - num_packed_objects.leading_zeros() + 1; + len = (len + 2 - 1) / 2; + len.max(7) as usize +} + /// pub mod shorten { /// Returned by [`Id::prefix()`][super::Id::shorten()].