Skip to main content

norm_spec/
collect.rs

1use std::{
2    fs,
3    io::ErrorKind,
4    path::{Path, PathBuf},
5};
6
7use norm_spec_core::{
8    CollectResponse, CollectedNorm, ErrorDetail, ParseOptions, collect_candidate_paths, parse_norm,
9    project_path,
10};
11
12use crate::{
13    ApiError,
14    paths::{canonical_root, display_path, path_error, requested_path},
15};
16
17/// Explicit inputs for one inherited convention collection.
18#[derive(Clone, Copy, Debug)]
19pub struct CollectRequest<'a> {
20    root: &'a Path,
21    target: &'a Path,
22    legacy_format: bool,
23}
24
25impl<'a> CollectRequest<'a> {
26    /// Construct a request whose relative target is resolved from `root`.
27    #[must_use]
28    pub const fn new(root: &'a Path, target: &'a Path) -> Self {
29        Self {
30            root,
31            target,
32            legacy_format: false,
33        }
34    }
35
36    /// Enable or disable the explicitly supported pre-A1 input format.
37    #[must_use]
38    pub const fn legacy_format(mut self, enabled: bool) -> Self {
39        self.legacy_format = enabled;
40        self
41    }
42}
43
44struct ResolvedRequest {
45    root: PathBuf,
46    relative_target: PathBuf,
47    target_is_file: bool,
48    legacy_format: bool,
49}
50
51/// Collect inherited `.norm` files from most-specific target to project root.
52///
53/// # Errors
54///
55/// Returns [`ApiError`] when the explicit paths are unavailable or escape the
56/// root, a convention file is a symbolic link, or a collected file cannot be
57/// read or parsed.
58pub fn collect(request: CollectRequest<'_>) -> Result<CollectResponse, ApiError> {
59    let request = resolve_request(request)?;
60    let candidates = collect_candidate_paths(&request.relative_target, request.target_is_file)
61        .map_err(|error| {
62            ApiError::usage(
63                ErrorDetail::new("norm/path/outside-root", error.to_string())
64                    .with_path(project_path(&request.relative_target)),
65            )
66        })?;
67    let mut norms = Vec::new();
68    for candidate in candidates {
69        if let Some(collected) = read_candidate(&request.root, &candidate, request.legacy_format)? {
70            norms.push(collected);
71        }
72    }
73    Ok(CollectResponse::new(
74        project_path(&request.relative_target),
75        norms,
76    ))
77}
78
79fn resolve_request(request: CollectRequest<'_>) -> Result<ResolvedRequest, ApiError> {
80    let root = canonical_root(request.root, "collection root")?;
81    let requested = requested_path(&root, request.target);
82    let target = fs::canonicalize(&requested).map_err(|error| {
83        ApiError::operation(
84            ErrorDetail::new(
85                if error.kind() == ErrorKind::NotFound {
86                    "norm/path/not-found"
87                } else {
88                    "norm/path/read"
89                },
90                format!("The collection target is unavailable: {error}"),
91            )
92            .with_path(display_path(Some(&root), request.target)),
93        )
94    })?;
95    if !target.starts_with(&root) {
96        return Err(ApiError::usage(
97            ErrorDetail::new(
98                "norm/path/outside-root",
99                "The collection target resolves outside the project root.",
100            )
101            .with_path(display_path(Some(&root), &target)),
102        ));
103    }
104    let relative_target = target.strip_prefix(&root).map_err(|error| {
105        ApiError::usage(
106            ErrorDetail::new(
107                "norm/path/outside-root",
108                format!("The collection target is not relative to its root: {error}"),
109            )
110            .with_path(display_path(Some(&root), &target)),
111        )
112    })?;
113    let target_is_file = target.is_file();
114    if !target_is_file && !target.is_dir() {
115        return Err(ApiError::operation(
116            ErrorDetail::new(
117                "norm/path/not-directory",
118                "The collection target is neither a file nor a directory.",
119            )
120            .with_path(project_path(relative_target)),
121        ));
122    }
123    Ok(ResolvedRequest {
124        root,
125        relative_target: relative_target.to_path_buf(),
126        target_is_file,
127        legacy_format: request.legacy_format,
128    })
129}
130
131fn read_candidate(
132    root: &Path,
133    candidate: &Path,
134    legacy_format: bool,
135) -> Result<Option<CollectedNorm>, ApiError> {
136    let path = root.join(candidate);
137    let metadata = match fs::symlink_metadata(&path) {
138        Ok(metadata) => metadata,
139        Err(error) if error.kind() == ErrorKind::NotFound => return Ok(None),
140        Err(error) => {
141            return Err(ApiError::operation(path_error(
142                Some(root),
143                candidate,
144                error.kind(),
145                "convention file",
146                &error.to_string(),
147            )));
148        }
149    };
150    if metadata.file_type().is_symlink() {
151        return Err(ApiError::operation(
152            ErrorDetail::new(
153                "norm/path/symlink-norm",
154                "A .norm convention file must not be a symbolic link.",
155            )
156            .with_path(project_path(candidate)),
157        ));
158    }
159    let contents = fs::read_to_string(path).map_err(|error| {
160        ApiError::operation(path_error(
161            Some(root),
162            candidate,
163            error.kind(),
164            "convention file",
165            &error.to_string(),
166        ))
167    })?;
168    let parsed = parse_norm(&contents, ParseOptions { legacy_format }).map_err(|error| {
169        ApiError::operation(
170            ErrorDetail::new(error.code(), error.message()).with_path(project_path(candidate)),
171        )
172    })?;
173    Ok(Some(CollectedNorm::new(project_path(candidate), parsed)))
174}