Skip to main content

source_mesh_core/graph/
source_path.rs

1use std::path::Component;
2use std::path::PathBuf;
3
4use anyhow::Result;
5use anyhow::ensure;
6
7/**
8Validation is lexical only, not a guarantee of existence, file type, or accessibility.
9The supplied path spelling is preserved.
10*/
11pub struct SourcePath {
12    path: PathBuf,
13}
14
15impl SourcePath {
16    pub fn new(path: PathBuf) -> Result<Self> {
17        ensure!(
18            !path.as_os_str().is_empty() && path.components().all(|component| matches!(component, Component::Normal(_))),
19            "Source path must be nonempty and relative, with only normal path components: {}",
20            path.display()
21        );
22        Ok(Self { path })
23    }
24
25    #[must_use]
26    pub(crate) fn into_path(self) -> PathBuf {
27        self.path
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use std::path::Path;
34    use std::path::PathBuf;
35
36    use claims::assert_ok;
37    use pretty_assertions::assert_eq;
38    use rstest::rstest;
39
40    use super::SourcePath;
41
42    #[rstest]
43    #[case("")]
44    #[case(".")]
45    #[case("..")]
46    #[case("../outside.rs")]
47    #[case("./source.rs")]
48    #[case("src/../source.rs")]
49    #[case("src/..")]
50    #[case("/absolute.rs")]
51    #[case("/")]
52    fn test_source_path_preconditions(#[case] source_path: &str) {
53        let path = PathBuf::from(source_path);
54
55        let system_under_test = SourcePath::new(path);
56
57        assert!(system_under_test.is_err(), "Invalid source path was accepted: {source_path}");
58    }
59
60    #[cfg(windows)]
61    #[rstest]
62    #[case("C:source.rs")]
63    #[case("C:\\source.rs")]
64    #[case("\\source.rs")]
65    #[case("\\\\server\\share\\source.rs")]
66    #[case("\\\\?\\C:\\source.rs")]
67    fn test_windows_source_path_prefixes(#[case] source_path: &str) {
68        let path = PathBuf::from(source_path);
69
70        let system_under_test = SourcePath::new(path);
71
72        assert!(system_under_test.is_err(), "Prefixed or rooted source path was accepted: {source_path}");
73    }
74
75    #[rstest]
76    #[case("source.rs")]
77    #[case("src/module.rs")]
78    #[case("src/")]
79    #[case("src/./source.rs")]
80    #[case("src//source.rs/")]
81    #[case("file\0.rs")]
82    #[case("file:name.rs")]
83    #[case("CON")]
84    #[case("file?.rs")]
85    #[case("file*.rs")]
86    #[case("file. ")]
87    #[case("..hidden.rs")]
88    fn test_source_path_spelling(#[case] source_path: &str) {
89        let path = PathBuf::from(source_path);
90
91        let system_under_test = SourcePath::new(path);
92        let system_under_test = assert_ok!(system_under_test, "Valid relative source path must be accepted: {source_path:?}");
93
94        assert_eq!(Path::new(source_path).as_os_str(), system_under_test.path.as_os_str(), "Validation changed path spelling");
95    }
96}