Skip to content

Commit ecd60d7

Browse files
committed
feat: add FullName(Ref)::category_and_shortname() (#364)
It's a combination of `shorten()` and `category()` for convenience.
1 parent 60f950d commit ecd60d7

File tree

3 files changed

+29
-8
lines changed

3 files changed

+29
-8
lines changed

git-ref/src/fullname.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,12 @@ impl FullName {
117117
pub fn category(&self) -> Option<crate::Category> {
118118
self.to_ref().category()
119119
}
120+
121+
/// Classify this name, or return `None` if it's unclassified. If `Some`,
122+
/// the shortened name is returned as well.
123+
pub fn category_and_short_name(&self) -> Option<(crate::Category, &BStr)> {
124+
self.to_ref().category_and_short_name()
125+
}
120126
}
121127

122128
impl<'a> FullNameRef<'a> {

git-ref/src/name.rs

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,27 @@ impl<'a> FullNameRef<'a> {
4949

5050
/// Classify this name, or return `None` if it's unclassified.
5151
pub fn category(&self) -> Option<Category> {
52-
for kind in &[
53-
Category::Tag,
54-
Category::LocalBranch,
55-
Category::RemoteBranch,
56-
Category::Note,
57-
] {
58-
if self.0.starts_with(kind.prefix()) {
59-
return (*kind).into();
52+
self.category_and_short_name().map(|(cat, _)| cat)
53+
}
54+
55+
/// Classify this name, or return `None` if it's unclassified. If `Some`,
56+
/// the shortened name is returned as well.
57+
pub fn category_and_short_name(&self) -> Option<(Category, &'a BStr)> {
58+
for category in &[Category::Tag, Category::LocalBranch, Category::RemoteBranch] {
59+
if let Some(shortened) = self.0.strip_prefix(category.prefix().as_ref()) {
60+
return Some((*category, shortened.as_bstr()));
6061
}
6162
}
63+
64+
if self.0.starts_with(Category::Note.prefix()) {
65+
return Some((
66+
Category::Note,
67+
self.0
68+
.strip_prefix(b"refs/")
69+
.expect("we checked for refs/notes above")
70+
.as_bstr(),
71+
));
72+
}
6273
None
6374
}
6475
}

git-ref/tests/fullname/mod.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ fn shorten_and_category() {
1919
assert_eq!(name.to_ref().shorten(), expected);
2020
assert_eq!(name.shorten(), expected);
2121
assert_eq!(name.category(), category);
22+
assert_eq!(
23+
name.category_and_short_name(),
24+
category.map(|cat| (cat, expected.into()))
25+
);
2226
assert_eq!(name.to_ref().category(), category);
2327
}
2428

0 commit comments

Comments
 (0)