1use crate::diagnostic::Diagnostic;
4use crate::report;
5use crate::source::SourceDocument;
6use enumset::EnumSet;
7use roas::validation::{Options, Validate, ValidationError};
8use std::fmt;
9use thiserror::Error;
10
11pub fn generation_options() -> EnumSet<Options> {
17 roas::validation::IGNORE_UNUSED
18 | roas::validation::IGNORE_EMPTY_REQUIRED_FIELDS
19 | Options::IgnoreUnusedPathItems
20 | Options::IgnoreMissingTags
21 | Options::IgnoreNonUniqOperationIDs
22 | Options::IgnoreInvalidUrls
23}
24
25pub fn validate(
38 document: SourceDocument,
39 options: EnumSet<Options>,
40) -> Result<ValidatedSourceDocument, SourceValidationError> {
41 let options = options | Options::IgnoreExternalReferences;
42 match document.spec().validate(options, None) {
43 Ok(()) => Ok(ValidatedSourceDocument { document }),
44 Err(error) => Err(SourceValidationError {
45 document: Box::new(document),
46 errors: error.errors,
47 }),
48 }
49}
50
51#[derive(Debug, Clone)]
53pub struct ValidatedSourceDocument {
54 document: SourceDocument,
55}
56
57impl ValidatedSourceDocument {
58 pub fn document(&self) -> &SourceDocument {
60 &self.document
61 }
62
63 pub fn into_document(self) -> SourceDocument {
65 self.document
66 }
67
68 pub fn diagnostics(&self) -> Vec<Diagnostic> {
72 let mut out = self.document.normalization().to_vec();
73 report::reference_restrictions(self.document.raw(), self.document.uri(), &mut out);
74 out.sort_by(|a, b| a.pointer.cmp(&b.pointer).then(a.severity.cmp(&b.severity)));
75 out
76 }
77}
78
79impl std::ops::Deref for ValidatedSourceDocument {
80 type Target = SourceDocument;
81
82 fn deref(&self) -> &SourceDocument {
83 &self.document
84 }
85}
86
87#[derive(Debug, Error)]
91#[non_exhaustive]
92pub struct SourceValidationError {
93 pub document: Box<SourceDocument>,
94 pub errors: Vec<ValidationError>,
95}
96
97impl fmt::Display for SourceValidationError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 write!(
100 f,
101 "{} is not a valid {} description: {} error(s)",
102 self.document.uri(),
103 self.document.version(),
104 self.errors.len()
105 )?;
106 for error in &self.errors {
107 write!(f, "\n- {error}")?;
108 }
109 Ok(())
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 #[test]
116 fn unused_path_items_are_exempt_too() {
117 let options = super::generation_options();
118 assert!(options.contains(roas::validation::Options::IgnoreUnusedPathItems));
119 assert!(options.contains(roas::validation::Options::IgnoreEmptyExternalDocumentationUrl));
120 }
121}