Skip to main content

norm_spec_core/
collector.rs

1//! Deterministic collection path rules independent of filesystem I/O.
2
3use std::{
4    error::Error,
5    fmt,
6    path::{Component, Path, PathBuf},
7};
8
9/// Failure to express a collection target relative to its project root.
10#[derive(Clone, Copy, Debug, Eq, PartialEq)]
11pub enum CollectPathError {
12    /// The supplied path is absolute or contains a parent traversal.
13    OutsideRoot,
14}
15
16impl fmt::Display for CollectPathError {
17    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
18        formatter.write_str("the collection target is not a contained relative path")
19    }
20}
21
22impl Error for CollectPathError {}
23
24/// Return candidate `.norm` paths from the most-specific directory to root.
25///
26/// A file target begins at its parent directory. A directory target begins at
27/// the directory itself. The returned paths are relative to the project root.
28///
29/// # Errors
30///
31/// Returns [`CollectPathError::OutsideRoot`] when `target` is absolute or
32/// contains a parent-directory component.
33pub fn collect_candidate_paths(
34    target: &Path,
35    target_is_file: bool,
36) -> Result<Vec<PathBuf>, CollectPathError> {
37    let target = contained_relative_path(target)?;
38    let mut directory = if target_is_file {
39        target
40            .parent()
41            .unwrap_or_else(|| Path::new(""))
42            .to_path_buf()
43    } else {
44        target
45    };
46    let mut candidates = Vec::new();
47
48    loop {
49        candidates.push(if directory.as_os_str().is_empty() {
50            PathBuf::from(".norm")
51        } else {
52            directory.join(".norm")
53        });
54        if !directory.pop() {
55            break;
56        }
57    }
58
59    Ok(candidates)
60}
61
62/// Render a root-relative project path with portable separators.
63#[must_use]
64pub fn project_path(path: &Path) -> String {
65    let rendered = path.to_string_lossy().replace('\\', "/");
66    if rendered.is_empty() {
67        ".".to_owned()
68    } else {
69        rendered
70    }
71}
72
73fn contained_relative_path(path: &Path) -> Result<PathBuf, CollectPathError> {
74    let mut normalized = PathBuf::new();
75    for component in path.components() {
76        match component {
77            Component::Normal(component) => normalized.push(component),
78            Component::CurDir => {}
79            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
80                return Err(CollectPathError::OutsideRoot);
81            }
82        }
83    }
84    Ok(normalized)
85}
86
87#[cfg(test)]
88mod tests {
89    use std::path::{Path, PathBuf};
90
91    use super::{CollectPathError, collect_candidate_paths, project_path};
92
93    #[test]
94    fn directory_candidates_are_most_specific_first() {
95        assert_eq!(
96            collect_candidate_paths(Path::new("docs/module"), false),
97            Ok(vec![
98                PathBuf::from("docs/module/.norm"),
99                PathBuf::from("docs/.norm"),
100                PathBuf::from(".norm"),
101            ])
102        );
103    }
104
105    #[test]
106    fn file_candidates_begin_at_the_parent() {
107        assert_eq!(
108            collect_candidate_paths(Path::new("docs/module/file.txt"), true),
109            Ok(vec![
110                PathBuf::from("docs/module/.norm"),
111                PathBuf::from("docs/.norm"),
112                PathBuf::from(".norm"),
113            ])
114        );
115    }
116
117    #[test]
118    fn root_target_has_one_candidate() {
119        assert_eq!(
120            collect_candidate_paths(Path::new(""), false),
121            Ok(vec![PathBuf::from(".norm")])
122        );
123    }
124
125    #[test]
126    fn escaping_or_absolute_targets_are_rejected() {
127        assert_eq!(
128            collect_candidate_paths(Path::new("../outside"), false),
129            Err(CollectPathError::OutsideRoot)
130        );
131        assert_eq!(
132            collect_candidate_paths(Path::new("/outside"), false),
133            Err(CollectPathError::OutsideRoot)
134        );
135    }
136
137    #[test]
138    fn project_paths_use_root_marker_and_portable_separators() {
139        assert_eq!(project_path(Path::new("")), ".");
140        assert_eq!(
141            project_path(Path::new("docs/module/.norm")),
142            "docs/module/.norm"
143        );
144    }
145}