Skip to content

Commit 1942087

Browse files
committed
Assure short ids are not ambiguous
It's actually quite involved to get proper short-ids, and git even applies some heuristics to calculate good starting values for the abbreviation length, right before validating uniqueness.
1 parent f61761d commit 1942087

File tree

2 files changed

+13
-15
lines changed

2 files changed

+13
-15
lines changed

src/info/head_refs.rs

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,32 @@
1-
use git_repository as git;
21
use serde::ser::SerializeStruct;
32
use serde::Serialize;
43

54
pub struct HeadRefs {
6-
commit: git::hash::ObjectId,
5+
short_commit_id: String,
76
refs: Vec<String>,
87
}
98

109
impl HeadRefs {
11-
pub fn new(commit: git::hash::ObjectId, refs: Vec<String>) -> HeadRefs {
12-
HeadRefs { commit, refs }
10+
pub fn new(short_commit_id: String, refs: Vec<String>) -> HeadRefs {
11+
HeadRefs {
12+
short_commit_id,
13+
refs,
14+
}
1315
}
1416
}
1517

1618
impl std::fmt::Display for HeadRefs {
1719
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
18-
let short_commit = self.commit.to_string().chars().take(7).collect::<String>();
1920
if !self.refs.is_empty() {
2021
let refs_str = self
2122
.refs
2223
.iter()
2324
.map(|ref_name| ref_name.as_str())
2425
.collect::<Vec<&str>>()
2526
.join(", ");
26-
write!(f, "{} ({})", short_commit, refs_str)
27+
write!(f, "{} ({})", self.short_commit_id, refs_str)
2728
} else {
28-
write!(f, "{}", short_commit)
29+
write!(f, "{}", self.short_commit_id)
2930
}
3031
}
3132
}
@@ -37,10 +38,7 @@ impl Serialize for HeadRefs {
3738
{
3839
let mut state = serializer.serialize_struct("HeadRefs", 2)?;
3940
state.serialize_field("refs", &self.refs)?;
40-
state.serialize_field(
41-
"oid",
42-
&self.commit.to_string().chars().take(7).collect::<String>(),
43-
)?;
41+
state.serialize_field("oid", &self.short_commit_id)?;
4442
state.end()
4543
}
4644
}

src/info/repo.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -304,9 +304,9 @@ impl<'a> Repo<'a> {
304304
let head_oid = self
305305
.repo
306306
.head()
307-
.with_context(|| "Could not read HEAD")?
308-
.peel_to_commit_in_place()?
309-
.id;
307+
.context("Could not read HEAD")?
308+
.peel_to_id_in_place()
309+
.context("The repository isn't initialized")??;
310310
let refs_info = self
311311
.repo
312312
.references()?
@@ -319,7 +319,7 @@ impl<'a> Repo<'a> {
319319
.then(|| reference.name().shorten().to_string())
320320
})
321321
.collect();
322-
Ok(HeadRefs::new(head_oid, refs_info))
322+
Ok(HeadRefs::new(head_oid.shorten()?.to_string(), refs_info))
323323
}
324324

325325
fn work_dir(&self) -> Result<&Path> {

0 commit comments

Comments
 (0)