use std::path::PathBuf;
use crate::diagnostics::ValidationReport;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("failed to read `{path}`: {source}")]
Io {
path: PathBuf,
source: std::io::Error,
},
#[error("{}", format_invalid_document(report))]
InvalidDocument {
report: ValidationReport,
},
#[error("unsupported document format for `{path}` (expected .yaml, .yml, or .json)")]
UnsupportedFormat {
path: PathBuf,
},
#[error("{0}")]
Serialization(String),
}
impl Error {
pub fn invalid_document_report(&self) -> Option<&ValidationReport> {
match self {
Self::InvalidDocument { report } => Some(report),
_ => None,
}
}
}
fn format_invalid_document(report: &ValidationReport) -> String {
match report.diagnostics.as_slice() {
[] => "invalid document".to_owned(),
[only] => format!("invalid document: {} — {}", only.id, only.message),
[first, rest @ ..] => format!(
"invalid document: {} — {} (+{} more)",
first.id,
first.message,
rest.len()
),
}
}