use crate::diagnostic::Diagnostic;
use crate::report;
use crate::source::SourceDocument;
use enumset::EnumSet;
use roas::validation::{Options, Validate, ValidationError};
use std::fmt;
use thiserror::Error;
pub fn generation_options() -> EnumSet<Options> {
roas::validation::IGNORE_UNUSED
| roas::validation::IGNORE_EMPTY_REQUIRED_FIELDS
| Options::IgnoreUnusedPathItems
| Options::IgnoreMissingTags
| Options::IgnoreNonUniqOperationIDs
| Options::IgnoreInvalidUrls
}
pub fn validate(
document: SourceDocument,
options: EnumSet<Options>,
) -> Result<ValidatedSourceDocument, SourceValidationError> {
let options = options | Options::IgnoreExternalReferences;
match document.spec().validate(options, None) {
Ok(()) => Ok(ValidatedSourceDocument { document }),
Err(error) => Err(SourceValidationError {
document: Box::new(document),
errors: error.errors,
}),
}
}
#[derive(Debug, Clone)]
pub struct ValidatedSourceDocument {
document: SourceDocument,
}
impl ValidatedSourceDocument {
pub fn document(&self) -> &SourceDocument {
&self.document
}
pub fn into_document(self) -> SourceDocument {
self.document
}
pub fn diagnostics(&self) -> Vec<Diagnostic> {
let mut out = self.document.normalization().to_vec();
report::reference_restrictions(self.document.raw(), self.document.uri(), &mut out);
out.sort_by(|a, b| a.pointer.cmp(&b.pointer).then(a.severity.cmp(&b.severity)));
out
}
}
impl std::ops::Deref for ValidatedSourceDocument {
type Target = SourceDocument;
fn deref(&self) -> &SourceDocument {
&self.document
}
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub struct SourceValidationError {
pub document: Box<SourceDocument>,
pub errors: Vec<ValidationError>,
}
impl fmt::Display for SourceValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} is not a valid {} description: {} error(s)",
self.document.uri(),
self.document.version(),
self.errors.len()
)?;
for error in &self.errors {
write!(f, "\n- {error}")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
#[test]
fn unused_path_items_are_exempt_too() {
let options = super::generation_options();
assert!(options.contains(roas::validation::Options::IgnoreUnusedPathItems));
assert!(options.contains(roas::validation::Options::IgnoreEmptyExternalDocumentationUrl));
}
}