use std::fmt;
use std::path::PathBuf;
#[derive(Debug)]
pub(crate) enum SchemaError {
ReadManifest {
path: PathBuf,
source: std::io::Error,
},
ParseManifest {
path: PathBuf,
source: serde_json::Error,
},
IncompatibleSchema { found: u32, expected: u32 },
RunMetadata(String),
}
impl fmt::Display for SchemaError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ReadManifest { path, .. } => {
write!(f, "cannot read UAG manifest at {}", path.display())
}
Self::ParseManifest { path, .. } => {
write!(
f,
"UAG manifest at {} is not valid UAG JSON",
path.display()
)
}
Self::IncompatibleSchema { found, expected } => write!(
f,
"UAG manifest schema version {found} is incompatible with this CLI (expected {expected})"
),
Self::RunMetadata(summary) => {
write!(f, "cannot produce a fresh UAG: {summary}")
}
}
}
}
impl std::error::Error for SchemaError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::ReadManifest { source, .. } => Some(source),
Self::ParseManifest { source, .. } => Some(source),
Self::IncompatibleSchema { .. } | Self::RunMetadata(_) => None,
}
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub(crate) fn assert_display_stable() {
let read = SchemaError::ReadManifest {
path: PathBuf::from("/x/app-manifest.json"),
source: std::io::Error::new(std::io::ErrorKind::NotFound, "missing"),
};
assert!(
read.to_string().contains("cannot read UAG manifest"),
"{}",
read
);
let parse = SchemaError::ParseManifest {
path: PathBuf::from("/x/app-manifest.json"),
source: serde_json::from_str::<serde_json::Value>("bad").unwrap_err(),
};
assert!(
parse.to_string().contains("not valid UAG JSON"),
"{}",
parse
);
let incompat = SchemaError::IncompatibleSchema {
found: 99,
expected: 1,
};
assert!(
incompat.to_string().contains("incompatible"),
"{}",
incompat
);
let run = SchemaError::RunMetadata("boom".to_owned());
assert!(run.to_string().contains("fresh UAG"), "{}", run);
}
#[test]
fn display_covers_all_variants() {
assert_display_stable();
}
#[test]
fn parse_manifest_preserves_source_chain() {
let err = SchemaError::ParseManifest {
path: PathBuf::from("/x/m.json"),
source: serde_json::from_str::<serde_json::Value>("bad").unwrap_err(),
};
assert!(std::error::Error::source(&err).is_some());
}
}