Skip to content

Commit af2d399

Browse files
committed
feat: FullName(Ref)::strip_prefix() (#364)
Get a short-hand for any reference name.
1 parent 70a259c commit af2d399

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

git-ref/src/fullname.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,13 @@ impl FullName {
105105
}
106106
self
107107
}
108+
109+
/// Strip well-known prefixes from the name and return it.
110+
///
111+
/// If there is no such prefix, the original name is returned.
112+
pub fn strip_prefix(&self) -> &BStr {
113+
self.to_ref().strip_prefix()
114+
}
108115
}
109116

110117
impl<'a> FullNameRef<'a> {

git-ref/src/name.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,19 @@ impl<'a> FullNameRef<'a> {
2121
pub fn as_bstr(&self) -> &'a BStr {
2222
self.0
2323
}
24+
25+
/// Strip well-known prefixes from the name and return it.
26+
///
27+
/// If there is no such prefix, the original name is returned.
28+
pub fn strip_prefix(&self) -> &'a BStr {
29+
let n = self.as_bstr();
30+
n.strip_prefix(b"refs/tags/")
31+
.or_else(|| n.strip_prefix(b"refs/heads/"))
32+
.or_else(|| n.strip_prefix(b"refs/remotes/"))
33+
.or_else(|| n.strip_prefix(b"refs/"))
34+
.map(|n| n.as_bstr())
35+
.unwrap_or(n)
36+
}
2437
}
2538

2639
impl<'a> PartialNameRef<'a> {

git-ref/tests/fullname/mod.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,28 @@ fn file_name() {
55
let name: git_ref::FullName = "refs/heads/main".try_into().unwrap();
66
assert_eq!(name.to_ref().file_name(), "main");
77
}
8+
#[test]
9+
fn strip_prefix() {
10+
for (input, expected) in vec![
11+
("refs/tags/tag-name", "tag-name"),
12+
("refs/heads/main", "main"),
13+
("refs/remotes/origin/main", "origin/main"),
14+
("refs/notes/note-name", "notes/note-name"),
15+
] {
16+
let name: git_ref::FullName = input.try_into().unwrap();
17+
assert_eq!(name.to_ref().strip_prefix(), expected);
18+
assert_eq!(name.strip_prefix(), expected);
19+
}
20+
21+
let special = "HEAD";
22+
let name: git_ref::FullName = special.try_into().unwrap();
23+
assert_eq!(
24+
name.strip_prefix(),
25+
special,
26+
"the whole name is returned if there is no prefix"
27+
);
28+
assert_eq!(name.strip_prefix(), name.to_ref().strip_prefix());
29+
}
830

931
#[test]
1032
fn prefix_with_namespace_and_stripping() {

0 commit comments

Comments
 (0)