Skip to main content

norm_spec/
validate.rs

1use std::{
2    fs,
3    path::{Path, PathBuf},
4};
5
6use norm_spec_core::{
7    Diagnostic, ErrorDetail, ParseOptions, ReferenceResolver, ReferenceStatus, SchemaBundle,
8    ValidateResponse, ValidationOptions, ValidationResult, parse_norm, project_path,
9    validate_frontmatter,
10};
11
12use crate::{
13    ApiError,
14    assets::{embedded_schema_bundle, schema_bundle_from_dir},
15    paths::{canonical_root, canonicalize_allow_missing, display_path, path_error, requested_path},
16};
17
18#[derive(Clone, Copy, Debug)]
19enum Selection<'a> {
20    Path(&'a Path),
21    All,
22}
23
24/// Explicit inputs for one filesystem-aware validation operation.
25#[derive(Clone, Copy, Debug)]
26pub struct ValidateRequest<'a> {
27    root: &'a Path,
28    selection: Selection<'a>,
29    schema_dir: Option<&'a Path>,
30    profile: Option<&'a str>,
31    legacy_format: bool,
32    compat_keys: bool,
33}
34
35impl<'a> ValidateRequest<'a> {
36    /// Validate one `.norm` file, or the `.norm` inside one directory.
37    ///
38    /// A relative `input` is resolved from `root`.
39    #[must_use]
40    pub const fn path(root: &'a Path, input: &'a Path) -> Self {
41        Self::new(root, Selection::Path(input))
42    }
43
44    /// Recursively validate every regular `.norm` file below `root`.
45    #[must_use]
46    pub const fn all(root: &'a Path) -> Self {
47        Self::new(root, Selection::All)
48    }
49
50    const fn new(root: &'a Path, selection: Selection<'a>) -> Self {
51        Self {
52            root,
53            selection,
54            schema_dir: None,
55            profile: None,
56            legacy_format: false,
57            compat_keys: false,
58        }
59    }
60
61    /// Use an explicit Schema bundle directory instead of packaged schemas.
62    ///
63    /// A relative path is resolved from the validation root.
64    #[must_use]
65    pub const fn schema_dir(mut self, path: &'a Path) -> Self {
66        self.schema_dir = Some(path);
67        self
68    }
69
70    /// Override metadata-based profile selection.
71    #[must_use]
72    pub const fn profile(mut self, profile: &'a str) -> Self {
73        self.profile = Some(profile);
74        self
75    }
76
77    /// Enable or disable the explicitly supported pre-A1 input format.
78    #[must_use]
79    pub const fn legacy_format(mut self, enabled: bool) -> Self {
80        self.legacy_format = enabled;
81        self
82    }
83
84    /// Downgrade unknown top-level fields to compatibility warnings.
85    #[must_use]
86    pub const fn compat_keys(mut self, enabled: bool) -> Self {
87        self.compat_keys = enabled;
88        self
89    }
90}
91
92struct ResolvedRequest<'a> {
93    root: PathBuf,
94    files: Vec<PathBuf>,
95    schemas: SchemaBundle,
96    profile: Option<&'a str>,
97    legacy_format: bool,
98    compat_keys: bool,
99}
100
101struct FileReferenceResolver<'a> {
102    root: &'a Path,
103    source_directory: &'a Path,
104}
105
106impl ReferenceResolver for FileReferenceResolver<'_> {
107    fn resolve(&self, target: &str) -> ReferenceStatus {
108        let requested = if let Some(relative) = target.strip_prefix('/') {
109            self.root.join(relative)
110        } else {
111            self.source_directory.join(target)
112        };
113        let resolved = canonicalize_allow_missing(&requested).unwrap_or(requested);
114        if !resolved.starts_with(self.root) {
115            ReferenceStatus::OutsideRoot
116        } else if resolved.exists() {
117            ReferenceStatus::Exists
118        } else {
119            ReferenceStatus::Missing
120        }
121    }
122}
123
124/// Validate one explicit input or every convention below an explicit root.
125///
126/// Validation diagnostics are completed results, including when they contain
127/// errors. This function returns [`ApiError`] only when path, Schema, or I/O
128/// failures prevent evaluation.
129///
130/// # Errors
131///
132/// Returns [`ApiError`] for invalid containment or Schema configuration and
133/// for filesystem or Schema-compilation failures that prevent evaluation.
134pub fn validate(request: ValidateRequest<'_>) -> Result<ValidateResponse, ApiError> {
135    let request = resolve_request(request)?;
136    evaluate(&request)
137}
138
139fn resolve_request(request: ValidateRequest<'_>) -> Result<ResolvedRequest<'_>, ApiError> {
140    let root = canonical_root(request.root, "validation root")?;
141    let files = match request.selection {
142        Selection::Path(input) => vec![resolve_input(&root, input)?],
143        Selection::All => discover_norms(&root)?,
144    };
145    let schema_directory = request.schema_dir.map(|path| requested_path(&root, path));
146    let schemas = schema_directory
147        .as_deref()
148        .map_or_else(embedded_schema_bundle, schema_bundle_from_dir)
149        .map_err(|error| {
150            let path = error
151                .path()
152                .map(|path| display_path(Some(&root), path))
153                .or_else(|| {
154                    request
155                        .schema_dir
156                        .map(|path| display_path(Some(&root), path))
157                });
158            let mut detail = ErrorDetail::new(
159                "norm/usage/schema-not-found",
160                format!("The schema bundle is unavailable: {error}"),
161            );
162            if let Some(path) = path {
163                detail = detail.with_path(path);
164            }
165            ApiError::usage(detail)
166        })?;
167    Ok(ResolvedRequest {
168        root,
169        files,
170        schemas,
171        profile: request.profile,
172        legacy_format: request.legacy_format,
173        compat_keys: request.compat_keys,
174    })
175}
176
177fn resolve_input(root: &Path, input: &Path) -> Result<PathBuf, ApiError> {
178    let requested = requested_path(root, input);
179    let metadata = fs::symlink_metadata(&requested).map_err(|error| {
180        ApiError::operation(path_error(
181            Some(root),
182            input,
183            error.kind(),
184            "validation input",
185            &error.to_string(),
186        ))
187    })?;
188    let candidate = if metadata.is_dir() {
189        requested.join(".norm")
190    } else {
191        requested
192    };
193    reject_norm_symlink(root, &candidate)?;
194    let canonical = fs::canonicalize(&candidate).map_err(|error| {
195        ApiError::operation(path_error(
196            Some(root),
197            &candidate,
198            error.kind(),
199            "validation input",
200            &error.to_string(),
201        ))
202    })?;
203    if !canonical.starts_with(root) {
204        return Err(ApiError::usage(
205            ErrorDetail::new(
206                "norm/path/outside-root",
207                "The validation input resolves outside the project root.",
208            )
209            .with_path(display_path(Some(root), &canonical)),
210        ));
211    }
212    Ok(canonical)
213}
214
215fn reject_norm_symlink(root: &Path, path: &Path) -> Result<(), ApiError> {
216    let metadata = fs::symlink_metadata(path).map_err(|error| {
217        ApiError::operation(path_error(
218            Some(root),
219            path,
220            error.kind(),
221            "validation input",
222            &error.to_string(),
223        ))
224    })?;
225    if metadata.file_type().is_symlink() {
226        let path = path
227            .strip_prefix(root)
228            .map_or_else(|_| display_path(Some(root), path), project_path);
229        return Err(ApiError::operation(
230            ErrorDetail::new(
231                "norm/path/symlink-norm",
232                "A .norm convention file must not be a symbolic link.",
233            )
234            .with_path(path),
235        ));
236    }
237    Ok(())
238}
239
240fn discover_norms(root: &Path) -> Result<Vec<PathBuf>, ApiError> {
241    let mut files = Vec::new();
242    discover_directory(root, root, &mut files)?;
243    files.sort();
244    Ok(files)
245}
246
247fn discover_directory(
248    root: &Path,
249    directory: &Path,
250    files: &mut Vec<PathBuf>,
251) -> Result<(), ApiError> {
252    let mut entries = fs::read_dir(directory)
253        .map_err(|error| {
254            ApiError::operation(path_error(
255                Some(root),
256                directory,
257                error.kind(),
258                "directory",
259                &error.to_string(),
260            ))
261        })?
262        .collect::<Result<Vec<_>, _>>()
263        .map_err(|error| {
264            ApiError::operation(path_error(
265                Some(root),
266                directory,
267                error.kind(),
268                "directory entry",
269                &error.to_string(),
270            ))
271        })?;
272    entries.sort_by_key(fs::DirEntry::file_name);
273    for entry in entries {
274        let path = entry.path();
275        let file_type = entry.file_type().map_err(|error| {
276            ApiError::operation(path_error(
277                Some(root),
278                &path,
279                error.kind(),
280                "directory entry",
281                &error.to_string(),
282            ))
283        })?;
284        if file_type.is_symlink() {
285            if entry.file_name() == ".norm" {
286                reject_norm_symlink(root, &path)?;
287            }
288            continue;
289        }
290        if file_type.is_dir() {
291            discover_directory(root, &path, files)?;
292        } else if file_type.is_file() && entry.file_name() == ".norm" {
293            files.push(path);
294        }
295    }
296    Ok(())
297}
298
299fn evaluate(request: &ResolvedRequest<'_>) -> Result<ValidateResponse, ApiError> {
300    let mut results = Vec::with_capacity(request.files.len());
301    for file in &request.files {
302        let relative = file.strip_prefix(&request.root).map_err(|error| {
303            ApiError::usage(
304                ErrorDetail::new(
305                    "norm/path/outside-root",
306                    format!("The validation file is not relative to its root: {error}"),
307                )
308                .with_path(display_path(Some(&request.root), file)),
309            )
310        })?;
311        let contents = fs::read_to_string(file).map_err(|error| {
312            ApiError::operation(path_error(
313                Some(&request.root),
314                relative,
315                error.kind(),
316                "convention file",
317                &error.to_string(),
318            ))
319        })?;
320        let parsed = match parse_norm(
321            &contents,
322            ParseOptions {
323                legacy_format: request.legacy_format,
324            },
325        ) {
326            Ok(parsed) => parsed,
327            Err(error) => {
328                results.push(ValidationResult::new(
329                    project_path(relative),
330                    vec![Diagnostic::new(error.code(), error.message())],
331                    Vec::new(),
332                ));
333                continue;
334            }
335        };
336        let source_directory = file.parent().unwrap_or(&request.root);
337        let resolver = FileReferenceResolver {
338            root: &request.root,
339            source_directory,
340        };
341        let diagnostics = validate_frontmatter(
342            &parsed.frontmatter,
343            &request.schemas,
344            ValidationOptions {
345                compat_keys: request.compat_keys,
346                profile: request.profile,
347            },
348            &resolver,
349        )
350        .map_err(|error| {
351            ApiError::usage(ErrorDetail::new(
352                "norm/usage/schema-not-found",
353                format!("The selected schema could not be compiled: {error}"),
354            ))
355        })?;
356        results.push(ValidationResult::new(
357            project_path(relative),
358            diagnostics.errors,
359            diagnostics.warnings,
360        ));
361    }
362    Ok(ValidateResponse::new(results))
363}