Skip to content

Commit

Permalink
feat: add FullName(Ref)::category_and_shortname() (#364)
Browse files Browse the repository at this point in the history
It's a combination of `shorten()` and `category()` for convenience.
  • Loading branch information
Byron committed Apr 3, 2022
1 parent 60f950d commit ecd60d7
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 8 deletions.
6 changes: 6 additions & 0 deletions git-ref/src/fullname.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ impl FullName {
pub fn category(&self) -> Option<crate::Category> {
self.to_ref().category()
}

/// Classify this name, or return `None` if it's unclassified. If `Some`,
/// the shortened name is returned as well.
pub fn category_and_short_name(&self) -> Option<(crate::Category, &BStr)> {
self.to_ref().category_and_short_name()
}
}

impl<'a> FullNameRef<'a> {
Expand Down
27 changes: 19 additions & 8 deletions git-ref/src/name.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,27 @@ impl<'a> FullNameRef<'a> {

/// Classify this name, or return `None` if it's unclassified.
pub fn category(&self) -> Option<Category> {
for kind in &[
Category::Tag,
Category::LocalBranch,
Category::RemoteBranch,
Category::Note,
] {
if self.0.starts_with(kind.prefix()) {
return (*kind).into();
self.category_and_short_name().map(|(cat, _)| cat)
}

/// Classify this name, or return `None` if it's unclassified. If `Some`,
/// the shortened name is returned as well.
pub fn category_and_short_name(&self) -> Option<(Category, &'a BStr)> {
for category in &[Category::Tag, Category::LocalBranch, Category::RemoteBranch] {
if let Some(shortened) = self.0.strip_prefix(category.prefix().as_ref()) {
return Some((*category, shortened.as_bstr()));
}
}

if self.0.starts_with(Category::Note.prefix()) {
return Some((
Category::Note,
self.0
.strip_prefix(b"refs/")
.expect("we checked for refs/notes above")
.as_bstr(),
));
}
None
}
}
Expand Down
4 changes: 4 additions & 0 deletions git-ref/tests/fullname/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ fn shorten_and_category() {
assert_eq!(name.to_ref().shorten(), expected);
assert_eq!(name.shorten(), expected);
assert_eq!(name.category(), category);
assert_eq!(
name.category_and_short_name(),
category.map(|cat| (cat, expected.into()))
);
assert_eq!(name.to_ref().category(), category);
}

Expand Down

0 comments on commit ecd60d7

Please sign in to comment.