Skip to content

Commit f58a043

Browse files
committed
feat: add is_absolute() for git-style absolute checks (#450)
This essentially means that starting slashes are always absolute, even on windows.
1 parent f4bc860 commit f58a043

File tree

4 files changed

+54
-0
lines changed

4 files changed

+54
-0
lines changed

git-path/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,9 @@ pub struct Spec(bstr::BString);
5858
mod convert;
5959
pub use convert::*;
6060

61+
mod util;
62+
pub use util::is_absolute;
63+
6164
mod spec;
6265

6366
///

git-path/src/util.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use std::path::Path;
2+
3+
/// return true if `path` is absolute, which depends on the platform but is always true if it starts with a `slash`, hence looks like
4+
/// a linux path.
5+
pub fn is_absolute(path: impl AsRef<Path>) -> bool {
6+
let path = path.as_ref();
7+
path.is_absolute() || path.to_str().and_then(|s| s.chars().next()) == Some('/')
8+
}

git-path/tests/path.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@ pub type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;
22

33
mod convert;
44
mod realpath;
5+
mod util;

git-path/tests/util/mod.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
mod is_absolute {
2+
#[test]
3+
fn absolute_linux_path_is_true() {
4+
assert!(git_path::is_absolute("/"));
5+
assert!(git_path::is_absolute("/abs/path"));
6+
}
7+
8+
#[test]
9+
fn relative_linux_path_is_false() {
10+
assert!(!git_path::is_absolute("./relative/path"));
11+
assert!(!git_path::is_absolute("relative/path"));
12+
}
13+
14+
#[cfg(not(windows))]
15+
mod not_on_windows {
16+
#[test]
17+
fn drive_prefixes_are_false() {
18+
assert!(!git_path::is_absolute("c:\\abs/path"));
19+
assert!(!git_path::is_absolute("c:\\abs\\path"));
20+
}
21+
}
22+
23+
#[cfg(windows)]
24+
mod on_windows {
25+
#[test]
26+
fn drive_prefixes_are_true() {
27+
assert!(git_path::is_absolute("c:\\abs/path"));
28+
assert!(git_path::is_absolute("c:\\abs\\path"));
29+
}
30+
31+
#[test]
32+
fn relative_paths_with_backslashes_are_false() {
33+
assert!(!git_path::is_absolute(".\\rel/path"));
34+
assert!(!git_path::is_absolute("rel\\path"));
35+
}
36+
37+
#[test]
38+
fn path_starting_with_backslash_is_false() {
39+
assert!(!git_path::is_absolute("\\rel\\path"));
40+
}
41+
}
42+
}

0 commit comments

Comments
 (0)