Skip to main content

rattler_conda_types/utils/
path.rs

1use itertools::Itertools;
2
3/// Returns true if the specified string is considered to be an absolute path
4pub(crate) fn is_absolute_path(path: &str) -> bool {
5    if path.contains("://") {
6        return false;
7    }
8
9    // Check if the path starts with a common absolute path prefix
10    if path.starts_with('/') || path.starts_with("\\\\") {
11        return true;
12    }
13
14    // A drive letter followed by a colon and a (backward or forward) slash
15    matches!(path.chars().take(3).collect_tuple(),
16        Some((letter, ':', '/' | '\\')) if letter.is_alphabetic())
17}
18
19/// Returns true if the specified string is considered to be a path
20pub(crate) fn is_path(path: &str) -> bool {
21    if path.contains("://") {
22        return false;
23    }
24
25    // Check if the path starts with a common path prefix
26    if path.starts_with("./")
27        || path.starts_with("..")
28        || path.starts_with("~/")
29        || path.starts_with('/')
30        || path.starts_with("\\\\")
31        || path.starts_with("//")
32    {
33        return true;
34    }
35
36    // A drive letter followed by a colon and a (backward or forward) slash
37    matches!(path.chars().take(3).collect_tuple(),
38        Some((letter, ':', '/' | '\\')) if letter.is_alphabetic())
39}
40
41mod tests {
42    #[test]
43    fn test_is_absolute_path() {
44        use super::is_absolute_path;
45        assert!(is_absolute_path("/foo"));
46        assert!(is_absolute_path("/C:/foo"));
47        assert!(is_absolute_path("C:/foo"));
48        assert!(is_absolute_path("\\\\foo"));
49        assert!(is_absolute_path("\\\\server\\foo"));
50
51        assert!(!is_absolute_path("conda-forge/label/rust_dev"));
52        assert!(!is_absolute_path("~/foo"));
53        assert!(!is_absolute_path("./foo"));
54        assert!(!is_absolute_path("../foo"));
55        assert!(!is_absolute_path("foo"));
56        assert!(!is_absolute_path("~\\foo"));
57    }
58
59    #[test]
60    fn test_is_path() {
61        use super::is_path;
62        assert!(is_path("/foo"));
63        assert!(is_path("/C:/foo"));
64        assert!(is_path("C:/foo"));
65        assert!(is_path("\\\\foo"));
66        assert!(is_path("\\\\server\\foo"));
67
68        assert!(is_path("./conda-forge/label/rust_dev"));
69        assert!(is_path("~/foo"));
70        assert!(is_path("./foo"));
71        assert!(is_path("../foo"));
72
73        assert!(!is_path("~\\foo"));
74    }
75}