Skip to content

Commit

Permalink
feat: auto-calculation of a good hex-len, like what git does (#298)
Browse files Browse the repository at this point in the history
If the `core.abbrev` value isn't set or is set to `auto`.
  • Loading branch information
Byron committed Apr 5, 2022
1 parent 84ec54e commit 47556f6
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions git-repository/src/id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<git_hash::Prefix, shorten::Error> {
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
Expand All @@ -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()].
Expand Down

0 comments on commit 47556f6

Please sign in to comment.