use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};
use crate::dataset::Dataset;
use crate::error::{Diagnostic, Report, Result, Rule};
use crate::header::{DifferenceModel, ModelHeader, ModelKind, Statement, StatementValue};
use crate::mrid::Mrid;
use crate::object::Object;
use crate::reader::{Budget, ReadOptions, Strictness, read_header, read_into_within};
use crate::schema::{AttrKind, Primitive, ProfileId, Schema};
use crate::value::Value;
use crate::writer::{WriteOptions, write_profile};
#[derive(Debug, Default)]
pub struct LoadReport {
pub report: Report,
pub files: Vec<(PathBuf, Option<ModelHeader>)>,
pub failed: Vec<PathBuf>,
pub objects_read: usize,
}
impl LoadReport {
pub fn has_errors(&self) -> bool {
self.report.has_errors()
}
}
impl Dataset {
pub fn load<I, P>(schema: &'static Schema, paths: I) -> Result<Dataset>
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
let mut ds = Dataset::new(schema);
ds.load_files(paths, &ReadOptions::lenient())?;
Ok(ds)
}
pub fn load_files<I, P>(&mut self, paths: I, options: &ReadOptions) -> Result<LoadReport>
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
let budget = Budget::new(options);
let mut out = LoadReport::default();
for path in paths {
let path = path.as_ref();
match self.load_file_within(path, options, &budget) {
Ok(one) => {
out.report.extend(one.report);
out.files.extend(one.files);
out.objects_read += one.objects_read;
}
Err(e) if options.strictness == Strictness::Lenient && !budget.tripped() => {
out.failed.push(path.to_path_buf());
out.report.push(
Diagnostic::error(Rule::UnreadableFile, e.to_string()).with_source(
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.display().to_string()),
),
);
}
Err(e) => return Err(e),
}
}
self.shrink_to_fit();
Ok(out)
}
pub fn load_file(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
self.load_file_within(path, options, &Budget::new(options))
}
fn load_file_within(
&mut self,
path: &Path,
options: &ReadOptions,
budget: &Budget,
) -> Result<LoadReport> {
if path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
{
#[cfg(feature = "zip")]
{
return self.load_zip_within(path, options, budget);
}
#[cfg(not(feature = "zip"))]
{
return Err(crate::error::Error::NotCimXml(format!(
"{} is a zip archive; enable the `zip` feature to read it",
path.display()
)));
}
}
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
let file = File::open(path)?;
let outcome = read_into_within(
self,
BufReader::with_capacity(1 << 16, file),
name.as_deref(),
options,
budget,
)?;
let mut report = LoadReport {
report: outcome.report,
objects_read: outcome.objects_read,
files: vec![(path.to_path_buf(), outcome.header.clone())],
failed: Vec::new(),
};
if outcome.header.is_none() {
report.report.push(
Diagnostic::warning(Rule::MalformedHeader, "file has no md:FullModel header")
.with_source(name.unwrap_or_default()),
);
}
Ok(report)
}
pub fn load_dir(schema: &'static Schema, dir: impl AsRef<Path>) -> Result<Dataset> {
let mut ds = Dataset::new(schema);
ds.load_files(instance_files(dir.as_ref()), &ReadOptions::lenient())?;
Ok(ds)
}
pub fn open(path: impl AsRef<Path>) -> Result<Dataset> {
let path = path.as_ref();
let files = instance_files(path);
let schema = detect_vintage(&files).ok_or_else(|| crate::error::Error::UnknownVintage {
path: path.display().to_string(),
known: crate::VINTAGES.iter().map(|s| s.vintage).collect(),
})?;
let mut ds = Dataset::new(schema);
ds.load_files(&files, &ReadOptions::lenient())?;
Ok(ds)
}
pub fn peek_headers<I, P>(
schema: &'static Schema,
paths: I,
) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
let mut out = Vec::new();
for path in paths {
let path = path.as_ref();
let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
let file = File::open(path)?;
let header = read_header(schema, BufReader::new(file), name.as_deref())?;
out.push((path.to_path_buf(), header));
}
Ok(out)
}
pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report {
let schema = self.schema();
let mut report = Report::default();
if let Some(refusal) = self.refusal(diff) {
report.push(refusal);
return report;
}
let profiles = diff
.header
.profiles
.iter()
.filter_map(|iri| schema.profile_by_iri(iri))
.fold(0, |acc, p| acc | p.mask());
for s in &diff.reverse {
self.apply_statement(s, false, profiles, &mut report);
}
self.apply_reclassifications(diff, &mut report);
for s in &diff.forward {
self.apply_statement(s, true, profiles, &mut report);
}
self.record_applied(diff.header.id.clone(), &diff.header.supersedes);
report
}
fn refusal(&self, diff: &DifferenceModel) -> Option<Diagnostic> {
let loaded: Vec<&Mrid> = self.model_ids().collect();
if !loaded.is_empty()
&& let Some(missing) = diff
.header
.supersedes
.iter()
.find(|id| !loaded.contains(id))
{
let mut held: Vec<String> = loaded.iter().map(|m| m.canonical()).collect();
held.sort();
return Some(Diagnostic::error(
Rule::UnsatisfiedDependency,
format!(
"change set not applied: it supersedes model {}, which is not loaded \
(this dataset holds {}); it was computed against another model",
missing.canonical(),
held.join(", ")
),
));
}
for s in &diff.preconditions {
let mut scratch = Report::default();
let holds = self
.statement_value(s, &mut scratch)
.is_some_and(|(attr, value)| {
self.find(&s.subject)
.and_then(|id| self.get(id))
.is_some_and(|o| o.values().any(|(a, v)| a == attr && *v == value))
});
if !holds {
return Some(
Diagnostic::error(
Rule::UnsatisfiedDependency,
format!(
"change set not applied: its precondition {} {} does not hold",
s.predicate,
match &s.value {
StatementValue::Resource(r) => r.as_str(),
StatementValue::Literal(t) => t.as_str(),
}
),
)
.with_object(s.subject.clone()),
);
}
}
None
}
fn apply_reclassifications(&mut self, diff: &DifferenceModel, report: &mut Report) {
let schema = self.schema();
let mut seen: Vec<Mrid> = Vec::new();
for s in &diff.forward {
let Some(qname) = &s.class else { continue };
if seen.contains(&s.subject) {
continue;
}
seen.push(s.subject.clone());
let Some(target) = schema.find_class(&qname.ns, &qname.local) else {
report.push(
Diagnostic::warning(
Rule::UnknownClass,
format!("difference names unknown class {}", qname.local),
)
.with_object(s.subject.clone()),
);
continue;
};
let Some(id) = self.find(&s.subject) else {
continue;
};
let Some(current) = self.get(id).map(|o| o.class()) else {
continue;
};
if current == target {
continue;
}
if !schema.is_a(target, current) {
report.push(
Diagnostic::info(
Rule::Structure,
format!(
"difference reclassifies {} from {} to {}",
s.subject.canonical(),
schema.class(current).name,
schema.class(target).name
),
)
.with_object(s.subject.clone())
.with_class(schema.class(target).name),
);
}
for slot in self.reclassify(id, target) {
let def = schema.attr(slot.attr);
report.push(
Diagnostic::warning(
Rule::Structure,
format!(
"{} was dropped: {} does not have it, and the difference \
reclassified this object",
def.name,
schema.class(target).name
),
)
.with_class(schema.class(target).name)
.with_object(s.subject.clone())
.with_attribute(def.name),
);
}
}
}
fn statement_value(
&self,
s: &Statement,
report: &mut Report,
) -> Option<(crate::schema::AttrId, Value)> {
let schema = self.schema();
let Some(attr) = schema.find_attr(&s.predicate_ns, &s.predicate) else {
report.push(
Diagnostic::warning(
Rule::UnknownAttribute,
format!(
"difference statement names unknown property {}",
s.predicate
),
)
.with_object(s.subject.clone()),
);
return None;
};
let def = schema.attr(attr);
let value = match &s.value {
StatementValue::Resource(iri) => match def.kind {
AttrKind::Enumeration(_) => {
let Some((ns, local)) = iri.rsplit_once('#') else {
report.push(
Diagnostic::error(
Rule::InvalidValue,
format!("enumeration value {iri} is not an IRI"),
)
.with_attribute(def.name),
);
return None;
};
match schema
.find_enum_value(&format!("{ns}#"), local)
.or_else(|| schema.find_enum_value_any_ns(local))
{
Some(v) => Value::Enum(v),
None => {
report.push(
Diagnostic::error(
Rule::InvalidValue,
format!("unknown enumeration literal {iri}"),
)
.with_attribute(def.name)
.with_object(s.subject.clone()),
);
return None;
}
}
}
_ => Value::Reference(Mrid::parse(iri)),
},
StatementValue::Literal(text) => {
let prim = match def.kind {
AttrKind::Primitive(p) => p,
AttrKind::Datatype(d) => schema.datatype(d).value,
_ => Primitive::String,
};
match Value::parse_primitive(prim, text) {
Ok(v) => v,
Err(e) => {
report.push(
Diagnostic::error(Rule::InvalidValue, e.to_string())
.with_attribute(def.name)
.with_object(s.subject.clone()),
);
return None;
}
}
}
};
Some((attr, value))
}
fn apply_statement(
&mut self,
s: &Statement,
assert: bool,
profiles: crate::schema::ProfileMask,
report: &mut Report,
) {
let schema = self.schema();
let Some((attr, value)) = self.statement_value(s, report) else {
return;
};
let def = schema.attr(attr);
let id = match self.find(&s.subject) {
Some(id) => id,
None if assert => {
let class = s
.class
.as_ref()
.and_then(|c| schema.find_class(&c.ns, &c.local))
.unwrap_or(def.owner);
self.insert(Object::new(class, s.subject.clone()))
}
None => {
report.push(
Diagnostic::warning(
Rule::DanglingReference,
format!(
"difference removes from {} which is not in the dataset",
s.subject.canonical()
),
)
.with_attribute(def.name),
);
return;
}
};
let class = self.get(id).map(|o| o.class());
if assert
&& let Some(class) = class
&& !schema.is_a(class, def.owner)
{
report.push(
Diagnostic::warning(
Rule::UnknownAttribute,
format!(
"difference statement sets {} on {}, which does not have it",
def.name,
schema.class(class).name
),
)
.with_class(schema.class(class).name)
.with_object(s.subject.clone())
.with_attribute(def.name),
);
return;
}
let Some(obj) = self.get_mut(id) else { return };
if assert {
if def.mult.is_many() {
obj.push_in(profiles, attr, value);
} else {
obj.set_in(profiles, attr, value);
}
obj.mark_profile(profiles);
} else if !obj.remove_value(attr, &value) {
report.push(
Diagnostic::info(
Rule::Structure,
format!("difference removes {} which was not present", def.name),
)
.with_object(s.subject.clone()),
);
}
}
pub fn save_profile(
&self,
path: &Path,
profile: ProfileId,
header: Option<ModelHeader>,
) -> Result<()> {
let options = match header {
Some(h) => WriteOptions::default().with_header(h),
None => WriteOptions::default(),
};
let file = File::create(path)?;
write_profile(
self,
profile,
BufWriter::with_capacity(1 << 16, file),
&options,
)
}
pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>> {
std::fs::create_dir_all(dir)?;
let mut written = Vec::new();
let content = self.content_id();
for cov in crate::validate::profile_coverage(self) {
if cov.objects == 0 {
continue;
}
let path = dir.join(format!("{stem}_{}.xml", cov.keyword));
let header =
crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
self.save_profile(&path, cov.profile, Some(header))?;
written.push(path);
}
Ok(written)
}
pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport> {
std::fs::create_dir_all(dir)?;
let schema = self.schema();
let mut out = SaveReport::default();
let unsourced: Vec<crate::dataset::ObjectId> = self
.iter()
.filter(|(_, o)| !o.from_file())
.map(|(id, _)| id)
.collect();
let mut unsourced_placed = false;
let mut used_names: Vec<String> = Vec::new();
let mut covered = vec![false; self.len()];
let mark = |ids: &[crate::dataset::ObjectId], covered: &mut Vec<bool>| {
for id in ids {
if let Some(slot) = covered.get_mut(id.index()) {
*slot = true;
}
}
};
for (i, header) in self.headers().iter().enumerate() {
let profiles = header
.profiles
.iter()
.filter_map(|iri| schema.profile_by_iri(iri))
.fold(0, |acc, p| acc | p.mask());
if profiles == 0 {
out.skipped.push(
header
.source
.clone()
.unwrap_or_else(|| format!("header {i}")),
);
continue;
}
let name = unique_name(
header
.source
.as_deref()
.and_then(output_file_name)
.unwrap_or_else(|| format!("model_{i}.xml")),
&mut used_names,
);
let path = dir.join(&name);
let file = File::create(&path)?;
let sink = BufWriter::with_capacity(1 << 16, file);
let options = WriteOptions {
profiles,
header: crate::writer::HeaderSource::Given(Box::new(header.clone())),
..Default::default()
};
if header.kind == ModelKind::Difference {
let diff = self
.differences()
.iter()
.find(|d| d.header.id.is_some() && d.header.id == header.id)
.or_else(|| {
self.differences()
.iter()
.find(|d| d.header.source.is_some() && d.header.source == header.source)
});
match diff {
Some(d) => crate::writer::write_difference(schema, d, sink, &options)?,
None => {
out.skipped
.push(format!("{name}: difference statements were not retained"));
continue;
}
}
out.written.push(path);
continue;
}
let mut ids: Vec<_> = self.objects_from(i).collect();
if !unsourced_placed && !unsourced.is_empty() {
let before = ids.len();
ids.extend(unsourced.iter().copied().filter(|&id| {
self.get(id)
.is_some_and(|o| crate::writer::object_has_content_in(schema, o, profiles))
}));
unsourced_placed = ids.len() > before;
}
mark(&ids, &mut covered);
crate::writer::write_objects(self, ids.into_iter(), sink, &options)?;
out.written.push(path);
}
out.unwritten = self
.iter()
.filter(|(id, _)| !covered.get(id.index()).copied().unwrap_or(false))
.count();
Ok(out)
}
}
pub fn detect_vintage<I, P>(paths: I) -> Option<&'static Schema>
where
I: IntoIterator<Item = P>,
P: AsRef<Path>,
{
paths.into_iter().find_map(|p| detect_file(p.as_ref()))
}
pub fn detect_file(path: &Path) -> Option<&'static Schema> {
#[cfg(feature = "zip")]
if path
.extension()
.is_some_and(|e| e.eq_ignore_ascii_case("zip"))
{
let file = File::open(path).ok()?;
let mut zip = zip::ZipArchive::new(BufReader::new(file)).ok()?;
let mut names: Vec<String> = zip
.file_names()
.filter_map(|n| n.ok())
.filter(|n| n.to_ascii_lowercase().ends_with(".xml"))
.map(|n| n.into_owned())
.collect();
names.sort();
let entry = zip.by_name(names.first()?).ok()?;
return crate::reader::sniff(BufReader::new(entry)).ok().flatten();
}
let file = File::open(path).ok()?;
crate::reader::sniff(BufReader::new(file)).ok().flatten()
}
pub fn instance_files(path: impl AsRef<Path>) -> Vec<PathBuf> {
let path = path.as_ref();
fn looks_like_input(path: &Path) -> bool {
let Some(ext) = path.extension() else {
return false;
};
ext.eq_ignore_ascii_case("xml")
|| (cfg!(feature = "zip") && ext.eq_ignore_ascii_case("zip"))
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for e in entries.flatten() {
let p = e.path();
if p.is_dir() {
walk(&p, out);
} else if looks_like_input(&p) {
out.push(p);
}
}
}
let mut out = Vec::new();
if path.is_dir() {
walk(path, &mut out);
out.sort();
} else if path.is_file() {
out.push(path.to_path_buf());
}
out
}
#[derive(Debug, Default)]
pub struct SaveReport {
pub written: Vec<PathBuf>,
pub skipped: Vec<String>,
pub unwritten: usize,
}
fn output_file_name(source: &str) -> Option<String> {
let candidate = Path::new(source).file_name()?.to_str()?;
let plain = !candidate.is_empty()
&& candidate != "."
&& candidate != ".."
&& !candidate.contains(['/', '\\', '\0']);
plain.then(|| candidate.to_owned())
}
fn unique_name(name: String, used: &mut Vec<String>) -> String {
let mut candidate = name.clone();
let (stem, ext) = match name.rsplit_once('.') {
Some((s, e)) if !s.is_empty() => (s, format!(".{e}")),
_ => (name.as_str(), String::new()),
};
let mut n = 1;
while used.contains(&candidate) {
n += 1;
candidate = format!("{stem}_{n}{ext}");
}
used.push(candidate.clone());
candidate
}
pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
crate::writer::write(dataset, out, options)
}
#[cfg(feature = "zip")]
impl Dataset {
pub fn load_zip(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
self.load_zip_within(path, options, &Budget::new(options))
}
fn load_zip_within(
&mut self,
path: &Path,
options: &ReadOptions,
budget: &Budget,
) -> Result<LoadReport> {
use crate::error::Error;
let file = File::open(path)?;
let mut archive = zip::ZipArchive::new(BufReader::new(file))
.map_err(|e| Error::Zip(format!("{}: {e}", path.display())))?;
let mut out = LoadReport::default();
let mut names: Vec<String> = Vec::new();
for name in archive.file_names() {
match name {
Ok(n) if n.to_ascii_lowercase().ends_with(".xml") => names.push(n.into_owned()),
Ok(_) => {}
Err(e) => out.report.push(
Diagnostic::error(
Rule::UnreadableFile,
format!("an entry name could not be decoded: {e}"),
)
.with_source(path.display().to_string()),
),
}
}
names.sort();
for name in names {
let entry = archive
.by_name(&name)
.map_err(|e| Error::Zip(format!("{name}: {e}")))?;
let outcome = read_into_within(
self,
BufReader::with_capacity(1 << 16, entry),
Some(&name),
options,
budget,
)
.map_err(|e| match e {
Error::Io(io) => Error::Zip(format!("{}: {name}: {io}", path.display())),
other => other,
})?;
out.report.extend(outcome.report);
out.objects_read += outcome.objects_read;
out.files
.push((PathBuf::from(&name), outcome.header.clone()));
}
Ok(out)
}
pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>> {
use crate::error::Error;
use zip::write::SimpleFileOptions;
let file = File::create(path)?;
let mut zw = zip::ZipWriter::new(BufWriter::new(file));
let mut written = Vec::new();
let content = self.content_id();
for cov in crate::validate::profile_coverage(self) {
if cov.objects == 0 {
continue;
}
let name = format!("{stem}_{}.xml", cov.keyword);
zw.start_file(&name, SimpleFileOptions::default())
.map_err(|e| Error::Zip(e.to_string()))?;
let header =
crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
write_profile(
self,
cov.profile,
&mut zw,
&WriteOptions::default().with_header(header),
)?;
written.push(name);
}
zw.finish().map_err(|e| Error::Zip(e.to_string()))?;
Ok(written)
}
}
#[cfg(test)]
mod tests {
use super::{output_file_name, unique_name};
#[test]
fn two_files_wanting_one_name_get_two_files() {
let mut used = Vec::new();
assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ.xml");
assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_2.xml");
assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_3.xml");
assert_eq!(unique_name("SSH.xml".into(), &mut used), "SSH.xml");
assert_eq!(unique_name("model".into(), &mut used), "model");
assert_eq!(unique_name("model".into(), &mut used), "model_2");
assert_eq!(unique_name("EQ_2.xml".into(), &mut used), "EQ_2_2.xml");
}
#[test]
fn an_export_never_escapes_its_output_directory() {
assert_eq!(output_file_name("EQ.xml").as_deref(), Some("EQ.xml"));
assert_eq!(
output_file_name("model/EQ.xml").as_deref(),
Some("EQ.xml"),
"a nested archive entry keeps only its file name"
);
assert_eq!(
output_file_name("../../../etc/cron.d/pwn").as_deref(),
Some("pwn")
);
assert_eq!(output_file_name("/etc/passwd").as_deref(), Some("passwd"));
for hostile in ["..", ".", "", "/", "..\\..\\evil.xml", "a\0b"] {
assert_eq!(output_file_name(hostile), None, "{hostile:?}");
}
}
}