use std::sync::OnceLock;
pub use crate::GldfSchemaVersion;
pub const DEFAULT_VALIDATION_SCHEMA: GldfSchemaVersion = GldfSchemaVersion::Rc3;
const RC3_XSD: &str = include_str!("../../schemas/gldf-1.0.0-rc-3.xsd");
const RC4_XSD: &str = include_str!("../../schemas/gldf-1.0.0-rc-4.xsd");
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct XsdFinding {
pub message: String,
pub line: Option<usize>,
pub column: Option<usize>,
}
impl std::fmt::Display for XsdFinding {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match (self.line, self.column) {
(Some(l), Some(c)) => write!(f, "[line {l}, col {c}] {}", self.message),
(Some(l), None) => write!(f, "[line {l}] {}", self.message),
_ => f.write_str(&self.message),
}
}
}
#[derive(Debug)]
pub enum XsdError {
Schema(String),
BadXml(String),
Archive(String),
}
impl std::fmt::Display for XsdError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
XsdError::Schema(s) => write!(f, "XSD schema error: {s}"),
XsdError::BadXml(s) => write!(f, "Bad product.xml: {s}"),
XsdError::Archive(s) => write!(f, "GLDF archive error: {s}"),
}
}
}
impl std::error::Error for XsdError {}
pub type XsdResult<T> = Result<T, XsdError>;
fn validator(version: GldfSchemaVersion) -> XsdResult<&'static uppsala::XsdValidator> {
static RC3: OnceLock<Result<uppsala::XsdValidator, String>> = OnceLock::new();
static RC4: OnceLock<Result<uppsala::XsdValidator, String>> = OnceLock::new();
let compile = |xsd: &str| -> Result<uppsala::XsdValidator, String> {
let doc = uppsala::parse(xsd).map_err(|e| format!("parse xsd: {e:?}"))?;
uppsala::XsdValidator::from_schema(&doc).map_err(|e| format!("compile xsd: {e:?}"))
};
let cached = match version {
GldfSchemaVersion::Rc3 => RC3.get_or_init(|| compile(RC3_XSD)),
GldfSchemaVersion::Rc4 => RC4.get_or_init(|| compile(RC4_XSD)),
};
cached.as_ref().map_err(|e| XsdError::Schema(e.clone()))
}
pub fn validate_product_xml(xml: &str) -> XsdResult<Vec<XsdFinding>> {
validate_product_xml_with_schema(xml, DEFAULT_VALIDATION_SCHEMA)
}
pub fn validate_product_xml_with_schema(
xml: &str,
version: GldfSchemaVersion,
) -> XsdResult<Vec<XsdFinding>> {
let v = validator(version)?;
let doc = uppsala::parse(xml).map_err(|e| XsdError::BadXml(format!("{e:?}")))?;
Ok(v.validate(&doc).into_iter().map(into_finding).collect())
}
pub fn validate_gldf_archive(bytes: &[u8]) -> XsdResult<Vec<XsdFinding>> {
validate_gldf_archive_with_schema(bytes, DEFAULT_VALIDATION_SCHEMA)
}
pub fn validate_gldf_archive_with_schema(
bytes: &[u8],
version: GldfSchemaVersion,
) -> XsdResult<Vec<XsdFinding>> {
use std::io::Read;
let reader = std::io::Cursor::new(bytes);
let mut zip =
zip::ZipArchive::new(reader).map_err(|e| XsdError::Archive(format!("open zip: {e}")))?;
let mut entry = zip
.by_name("product.xml")
.map_err(|e| XsdError::Archive(format!("no product.xml: {e}")))?;
let mut xml = String::new();
entry
.read_to_string(&mut xml)
.map_err(|e| XsdError::Archive(format!("read product.xml: {e}")))?;
validate_product_xml_with_schema(&xml, version)
}
fn into_finding(e: uppsala::ValidationError) -> XsdFinding {
XsdFinding {
message: e.message,
line: e.line,
column: e.column,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_schemas_compile() {
assert!(
validator(GldfSchemaVersion::Rc3).is_ok(),
"rc-3 XSD should compile cleanly"
);
assert!(
validator(GldfSchemaVersion::Rc4).is_ok(),
"rc-4 XSD should compile cleanly"
);
}
#[test]
fn default_is_latest_published_rc() {
assert_eq!(
DEFAULT_VALIDATION_SCHEMA,
GldfSchemaVersion::Rc3,
"version-less validation defaults to the latest PUBLISHED rc"
);
}
#[test]
fn empty_xml_is_an_error() {
let r = validate_product_xml("");
assert!(matches!(r, Err(XsdError::BadXml(_))));
}
}
#[cfg(test)]
mod schema_copies {
#[test]
fn embedded_schemas_match_tests_data() {
let data = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data");
if !data.is_dir() {
return;
}
for (name, embedded) in [
("gldf-1.0.0-rc-3.xsd", super::RC3_XSD),
("gldf-1.0.0-rc-4.xsd", super::RC4_XSD),
] {
let original = std::fs::read_to_string(data.join(name)).unwrap();
assert!(
original == embedded,
"schemas/{name} differs from tests/data/{name}"
);
}
}
}