1use std::fs::File;
7use std::io::{BufReader, BufWriter, Write};
8use std::path::{Path, PathBuf};
9
10use crate::dataset::Dataset;
11use crate::error::{Diagnostic, Report, Result, Rule};
12use crate::header::{DifferenceModel, ModelHeader, ModelKind, Statement, StatementValue};
13use crate::mrid::Mrid;
14use crate::object::Object;
15use crate::reader::{Budget, ReadOptions, Strictness, read_header, read_into_within};
16use crate::schema::{AttrKind, Primitive, ProfileId, Schema};
17use crate::value::Value;
18use crate::writer::{WriteOptions, write_profile};
19
20#[derive(Debug, Default)]
22pub struct LoadReport {
23 pub report: Report,
24 pub files: Vec<(PathBuf, Option<ModelHeader>)>,
26 pub failed: Vec<PathBuf>,
30 pub objects_read: usize,
31}
32
33impl LoadReport {
34 pub fn has_errors(&self) -> bool {
35 self.report.has_errors()
36 }
37}
38
39impl Dataset {
40 pub fn load<I, P>(schema: &'static Schema, paths: I) -> Result<Dataset>
45 where
46 I: IntoIterator<Item = P>,
47 P: AsRef<Path>,
48 {
49 let mut ds = Dataset::new(schema);
50 ds.load_files(paths, &ReadOptions::lenient())?;
51 Ok(ds)
52 }
53
54 pub fn load_files<I, P>(&mut self, paths: I, options: &ReadOptions) -> Result<LoadReport>
66 where
67 I: IntoIterator<Item = P>,
68 P: AsRef<Path>,
69 {
70 let budget = Budget::new(options);
71 let mut out = LoadReport::default();
72 for path in paths {
73 let path = path.as_ref();
74 match self.load_file_within(path, options, &budget) {
76 Ok(one) => {
77 out.report.extend(one.report);
78 out.files.extend(one.files);
79 out.objects_read += one.objects_read;
80 }
81 Err(e) if options.strictness == Strictness::Lenient && !budget.tripped() => {
83 out.failed.push(path.to_path_buf());
84 out.report.push(
85 Diagnostic::error(Rule::UnreadableFile, e.to_string()).with_source(
86 path.file_name()
87 .map(|n| n.to_string_lossy().into_owned())
88 .unwrap_or_else(|| path.display().to_string()),
89 ),
90 );
91 }
92 Err(e) => return Err(e),
93 }
94 }
95 self.shrink_to_fit();
96 Ok(out)
97 }
98
99 pub fn load_file(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
101 self.load_file_within(path, options, &Budget::new(options))
102 }
103
104 fn load_file_within(
105 &mut self,
106 path: &Path,
107 options: &ReadOptions,
108 budget: &Budget,
109 ) -> Result<LoadReport> {
110 if path
111 .extension()
112 .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
113 {
114 #[cfg(feature = "zip")]
115 {
116 return self.load_zip_within(path, options, budget);
117 }
118 #[cfg(not(feature = "zip"))]
119 {
120 return Err(crate::error::Error::NotCimXml(format!(
121 "{} is a zip archive; enable the `zip` feature to read it",
122 path.display()
123 )));
124 }
125 }
126
127 let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
128 let file = File::open(path)?;
129 let outcome = read_into_within(
130 self,
131 BufReader::with_capacity(1 << 16, file),
132 name.as_deref(),
133 options,
134 budget,
135 )?;
136
137 let mut report = LoadReport {
138 report: outcome.report,
139 objects_read: outcome.objects_read,
140 files: vec![(path.to_path_buf(), outcome.header.clone())],
141 failed: Vec::new(),
142 };
143 if outcome.header.is_none() {
145 report.report.push(
146 Diagnostic::warning(Rule::MalformedHeader, "file has no md:FullModel header")
147 .with_source(name.unwrap_or_default()),
148 );
149 }
150 Ok(report)
151 }
152
153 pub fn load_dir(schema: &'static Schema, dir: impl AsRef<Path>) -> Result<Dataset> {
158 let mut ds = Dataset::new(schema);
159 ds.load_files(instance_files(dir.as_ref()), &ReadOptions::lenient())?;
160 Ok(ds)
161 }
162
163 pub fn open(path: impl AsRef<Path>) -> Result<Dataset> {
182 let path = path.as_ref();
183 let files = instance_files(path);
184 let schema = detect_vintage(&files).ok_or_else(|| crate::error::Error::UnknownVintage {
185 path: path.display().to_string(),
186 known: crate::VINTAGES.iter().map(|s| s.vintage).collect(),
187 })?;
188 let mut ds = Dataset::new(schema);
189 ds.load_files(&files, &ReadOptions::lenient())?;
190 Ok(ds)
191 }
192
193 pub fn peek_headers<I, P>(
197 schema: &'static Schema,
198 paths: I,
199 ) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
200 where
201 I: IntoIterator<Item = P>,
202 P: AsRef<Path>,
203 {
204 let mut out = Vec::new();
205 for path in paths {
206 let path = path.as_ref();
207 let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
208 let file = File::open(path)?;
209 let header = read_header(schema, BufReader::new(file), name.as_deref())?;
210 out.push((path.to_path_buf(), header));
211 }
212 Ok(out)
213 }
214
215 pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report {
227 let schema = self.schema();
228 let mut report = Report::default();
229 if let Some(refusal) = self.refusal(diff) {
230 report.push(refusal);
231 return report;
232 }
233 let profiles = diff
236 .header
237 .profiles
238 .iter()
239 .filter_map(|iri| schema.profile_by_iri(iri))
240 .fold(0, |acc, p| acc | p.mask());
241
242 for s in &diff.reverse {
246 self.apply_statement(s, false, profiles, &mut report);
247 }
248 self.apply_reclassifications(diff, &mut report);
249 for s in &diff.forward {
250 self.apply_statement(s, true, profiles, &mut report);
251 }
252 self.record_applied(diff.header.id.clone(), &diff.header.supersedes);
253 report
254 }
255
256 fn refusal(&self, diff: &DifferenceModel) -> Option<Diagnostic> {
258 let loaded: Vec<&Mrid> = self.model_ids().collect();
259 if !loaded.is_empty()
260 && let Some(missing) = diff
261 .header
262 .supersedes
263 .iter()
264 .find(|id| !loaded.contains(id))
265 {
266 let mut held: Vec<String> = loaded.iter().map(|m| m.canonical()).collect();
267 held.sort();
268 return Some(Diagnostic::error(
269 Rule::UnsatisfiedDependency,
270 format!(
271 "change set not applied: it supersedes model {}, which is not loaded \
272 (this dataset holds {}); it was computed against another model",
273 missing.canonical(),
274 held.join(", ")
275 ),
276 ));
277 }
278 for s in &diff.preconditions {
279 let mut scratch = Report::default();
280 let holds = self
281 .statement_value(s, &mut scratch)
282 .is_some_and(|(attr, value)| {
283 self.find(&s.subject)
284 .and_then(|id| self.get(id))
285 .is_some_and(|o| o.values().any(|(a, v)| a == attr && *v == value))
286 });
287 if !holds {
288 return Some(
289 Diagnostic::error(
290 Rule::UnsatisfiedDependency,
291 format!(
292 "change set not applied: its precondition {} {} does not hold",
293 s.predicate,
294 match &s.value {
295 StatementValue::Resource(r) => r.as_str(),
296 StatementValue::Literal(t) => t.as_str(),
297 }
298 ),
299 )
300 .with_object(s.subject.clone()),
301 );
302 }
303 }
304 None
305 }
306
307 fn apply_reclassifications(&mut self, diff: &DifferenceModel, report: &mut Report) {
312 let schema = self.schema();
313 let mut seen: Vec<Mrid> = Vec::new();
314
315 for s in &diff.forward {
316 let Some(qname) = &s.class else { continue };
317 if seen.contains(&s.subject) {
318 continue;
319 }
320 seen.push(s.subject.clone());
321
322 let Some(target) = schema.find_class(&qname.ns, &qname.local) else {
323 report.push(
324 Diagnostic::warning(
325 Rule::UnknownClass,
326 format!("difference names unknown class {}", qname.local),
327 )
328 .with_object(s.subject.clone()),
329 );
330 continue;
331 };
332 let Some(id) = self.find(&s.subject) else {
333 continue;
334 };
335 let Some(current) = self.get(id).map(|o| o.class()) else {
336 continue;
337 };
338 if current == target {
339 continue;
340 }
341 if !schema.is_a(target, current) {
343 report.push(
344 Diagnostic::info(
345 Rule::Structure,
346 format!(
347 "difference reclassifies {} from {} to {}",
348 s.subject.canonical(),
349 schema.class(current).name,
350 schema.class(target).name
351 ),
352 )
353 .with_object(s.subject.clone())
354 .with_class(schema.class(target).name),
355 );
356 }
357 for slot in self.reclassify(id, target) {
359 let def = schema.attr(slot.attr);
360 report.push(
361 Diagnostic::warning(
362 Rule::Structure,
363 format!(
364 "{} was dropped: {} does not have it, and the difference \
365 reclassified this object",
366 def.name,
367 schema.class(target).name
368 ),
369 )
370 .with_class(schema.class(target).name)
371 .with_object(s.subject.clone())
372 .with_attribute(def.name),
373 );
374 }
375 }
376 }
377
378 fn statement_value(
381 &self,
382 s: &Statement,
383 report: &mut Report,
384 ) -> Option<(crate::schema::AttrId, Value)> {
385 let schema = self.schema();
386 let Some(attr) = schema.find_attr(&s.predicate_ns, &s.predicate) else {
387 report.push(
388 Diagnostic::warning(
389 Rule::UnknownAttribute,
390 format!(
391 "difference statement names unknown property {}",
392 s.predicate
393 ),
394 )
395 .with_object(s.subject.clone()),
396 );
397 return None;
398 };
399 let def = schema.attr(attr);
400
401 let value = match &s.value {
402 StatementValue::Resource(iri) => match def.kind {
403 AttrKind::Enumeration(_) => {
404 let Some((ns, local)) = iri.rsplit_once('#') else {
405 report.push(
406 Diagnostic::error(
407 Rule::InvalidValue,
408 format!("enumeration value {iri} is not an IRI"),
409 )
410 .with_attribute(def.name),
411 );
412 return None;
413 };
414 match schema
415 .find_enum_value(&format!("{ns}#"), local)
416 .or_else(|| schema.find_enum_value_any_ns(local))
418 {
419 Some(v) => Value::Enum(v),
420 None => {
421 report.push(
422 Diagnostic::error(
423 Rule::InvalidValue,
424 format!("unknown enumeration literal {iri}"),
425 )
426 .with_attribute(def.name)
427 .with_object(s.subject.clone()),
428 );
429 return None;
430 }
431 }
432 }
433 _ => Value::Reference(Mrid::parse(iri)),
434 },
435 StatementValue::Literal(text) => {
436 let prim = match def.kind {
437 AttrKind::Primitive(p) => p,
438 AttrKind::Datatype(d) => schema.datatype(d).value,
439 _ => Primitive::String,
440 };
441 match Value::parse_primitive(prim, text) {
442 Ok(v) => v,
443 Err(e) => {
444 report.push(
445 Diagnostic::error(Rule::InvalidValue, e.to_string())
446 .with_attribute(def.name)
447 .with_object(s.subject.clone()),
448 );
449 return None;
450 }
451 }
452 }
453 };
454 Some((attr, value))
455 }
456
457 fn apply_statement(
458 &mut self,
459 s: &Statement,
460 assert: bool,
461 profiles: crate::schema::ProfileMask,
462 report: &mut Report,
463 ) {
464 let schema = self.schema();
465 let Some((attr, value)) = self.statement_value(s, report) else {
466 return;
467 };
468 let def = schema.attr(attr);
469
470 let id = match self.find(&s.subject) {
473 Some(id) => id,
474 None if assert => {
475 let class = s
476 .class
477 .as_ref()
478 .and_then(|c| schema.find_class(&c.ns, &c.local))
479 .unwrap_or(def.owner);
480 self.insert(Object::new(class, s.subject.clone()))
481 }
482 None => {
483 report.push(
484 Diagnostic::warning(
485 Rule::DanglingReference,
486 format!(
487 "difference removes from {} which is not in the dataset",
488 s.subject.canonical()
489 ),
490 )
491 .with_attribute(def.name),
492 );
493 return;
494 }
495 };
496
497 let class = self.get(id).map(|o| o.class());
501 if assert
502 && let Some(class) = class
503 && !schema.is_a(class, def.owner)
504 {
505 report.push(
506 Diagnostic::warning(
507 Rule::UnknownAttribute,
508 format!(
509 "difference statement sets {} on {}, which does not have it",
510 def.name,
511 schema.class(class).name
512 ),
513 )
514 .with_class(schema.class(class).name)
515 .with_object(s.subject.clone())
516 .with_attribute(def.name),
517 );
518 return;
519 }
520
521 let Some(obj) = self.get_mut(id) else { return };
522 if assert {
523 if def.mult.is_many() {
524 obj.push_in(profiles, attr, value);
525 } else {
526 obj.set_in(profiles, attr, value);
527 }
528 obj.mark_profile(profiles);
529 } else if !obj.remove_value(attr, &value) {
530 report.push(
531 Diagnostic::info(
532 Rule::Structure,
533 format!("difference removes {} which was not present", def.name),
534 )
535 .with_object(s.subject.clone()),
536 );
537 }
538 }
539
540 pub fn save_profile(
542 &self,
543 path: &Path,
544 profile: ProfileId,
545 header: Option<ModelHeader>,
546 ) -> Result<()> {
547 let options = match header {
549 Some(h) => WriteOptions::default().with_header(h),
550 None => WriteOptions::default(),
551 };
552 let file = File::create(path)?;
553 write_profile(
554 self,
555 profile,
556 BufWriter::with_capacity(1 << 16, file),
557 &options,
558 )
559 }
560
561 pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>> {
566 std::fs::create_dir_all(dir)?;
567 let mut written = Vec::new();
568 let content = self.content_id();
570 for cov in crate::validate::profile_coverage(self) {
571 if cov.objects == 0 {
572 continue;
573 }
574 let path = dir.join(format!("{stem}_{}.xml", cov.keyword));
575 let header =
576 crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
577 self.save_profile(&path, cov.profile, Some(header))?;
578 written.push(path);
579 }
580 Ok(written)
581 }
582
583 pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport> {
594 std::fs::create_dir_all(dir)?;
595 let schema = self.schema();
596 let mut out = SaveReport::default();
597
598 let unsourced: Vec<crate::dataset::ObjectId> = self
600 .iter()
601 .filter(|(_, o)| !o.from_file())
602 .map(|(id, _)| id)
603 .collect();
604 let mut unsourced_placed = false;
605 let mut used_names: Vec<String> = Vec::new();
606 let mut covered = vec![false; self.len()];
608 let mark = |ids: &[crate::dataset::ObjectId], covered: &mut Vec<bool>| {
609 for id in ids {
610 if let Some(slot) = covered.get_mut(id.index()) {
611 *slot = true;
612 }
613 }
614 };
615
616 for (i, header) in self.headers().iter().enumerate() {
617 let profiles = header
618 .profiles
619 .iter()
620 .filter_map(|iri| schema.profile_by_iri(iri))
621 .fold(0, |acc, p| acc | p.mask());
622 if profiles == 0 {
623 out.skipped.push(
624 header
625 .source
626 .clone()
627 .unwrap_or_else(|| format!("header {i}")),
628 );
629 continue;
630 }
631
632 let name = unique_name(
635 header
636 .source
637 .as_deref()
638 .and_then(output_file_name)
639 .unwrap_or_else(|| format!("model_{i}.xml")),
640 &mut used_names,
641 );
642 let path = dir.join(&name);
643 let file = File::create(&path)?;
644 let sink = BufWriter::with_capacity(1 << 16, file);
645 let options = WriteOptions {
646 profiles,
647 header: crate::writer::HeaderSource::Given(Box::new(header.clone())),
648 ..Default::default()
649 };
650
651 if header.kind == ModelKind::Difference {
652 let diff = self
655 .differences()
656 .iter()
657 .find(|d| d.header.id.is_some() && d.header.id == header.id)
658 .or_else(|| {
659 self.differences()
660 .iter()
661 .find(|d| d.header.source.is_some() && d.header.source == header.source)
662 });
663 match diff {
664 Some(d) => crate::writer::write_difference(schema, d, sink, &options)?,
665 None => {
666 out.skipped
667 .push(format!("{name}: difference statements were not retained"));
668 continue;
669 }
670 }
671 out.written.push(path);
672 continue;
673 }
674
675 let mut ids: Vec<_> = self.objects_from(i).collect();
678 if !unsourced_placed && !unsourced.is_empty() {
679 let before = ids.len();
680 ids.extend(unsourced.iter().copied().filter(|&id| {
681 self.get(id)
682 .is_some_and(|o| crate::writer::object_has_content_in(schema, o, profiles))
683 }));
684 unsourced_placed = ids.len() > before;
685 }
686
687 mark(&ids, &mut covered);
688 crate::writer::write_objects(self, ids.into_iter(), sink, &options)?;
689 out.written.push(path);
690 }
691
692 out.unwritten = self
693 .iter()
694 .filter(|(id, _)| !covered.get(id.index()).copied().unwrap_or(false))
695 .count();
696 Ok(out)
697 }
698}
699
700pub fn detect_vintage<I, P>(paths: I) -> Option<&'static Schema>
705where
706 I: IntoIterator<Item = P>,
707 P: AsRef<Path>,
708{
709 paths.into_iter().find_map(|p| detect_file(p.as_ref()))
710}
711
712pub fn detect_file(path: &Path) -> Option<&'static Schema> {
717 #[cfg(feature = "zip")]
718 if path
719 .extension()
720 .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
721 {
722 let file = File::open(path).ok()?;
723 let mut zip = zip::ZipArchive::new(BufReader::new(file)).ok()?;
724 let mut names: Vec<String> = zip
727 .file_names()
728 .filter_map(|n| n.ok())
729 .filter(|n| n.to_ascii_lowercase().ends_with(".xml"))
730 .map(|n| n.into_owned())
731 .collect();
732 names.sort();
733 let entry = zip.by_name(names.first()?).ok()?;
734 return crate::reader::sniff(BufReader::new(entry)).ok().flatten();
735 }
736 let file = File::open(path).ok()?;
737 crate::reader::sniff(BufReader::new(file)).ok().flatten()
738}
739
740pub fn instance_files(path: impl AsRef<Path>) -> Vec<PathBuf> {
745 let path = path.as_ref();
746 fn looks_like_input(path: &Path) -> bool {
747 let Some(ext) = path.extension() else {
748 return false;
749 };
750 ext.eq_ignore_ascii_case("xml")
751 || (cfg!(feature = "zip") && ext.eq_ignore_ascii_case("zip"))
752 }
753 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
754 let Ok(entries) = std::fs::read_dir(dir) else {
755 return;
756 };
757 for e in entries.flatten() {
758 let p = e.path();
759 if p.is_dir() {
760 walk(&p, out);
761 } else if looks_like_input(&p) {
762 out.push(p);
763 }
764 }
765 }
766
767 let mut out = Vec::new();
768 if path.is_dir() {
769 walk(path, &mut out);
770 out.sort();
771 } else if path.is_file() {
772 out.push(path.to_path_buf());
773 }
774 out
775}
776
777#[derive(Debug, Default)]
779pub struct SaveReport {
780 pub written: Vec<PathBuf>,
781 pub skipped: Vec<String>,
783 pub unwritten: usize,
788}
789
790fn output_file_name(source: &str) -> Option<String> {
795 let candidate = Path::new(source).file_name()?.to_str()?;
796 let plain = !candidate.is_empty()
797 && candidate != "."
798 && candidate != ".."
799 && !candidate.contains(['/', '\\', '\0']);
800 plain.then(|| candidate.to_owned())
801}
802
803fn unique_name(name: String, used: &mut Vec<String>) -> String {
806 let mut candidate = name.clone();
807 let (stem, ext) = match name.rsplit_once('.') {
808 Some((s, e)) if !s.is_empty() => (s, format!(".{e}")),
809 _ => (name.as_str(), String::new()),
810 };
811 let mut n = 1;
812 while used.contains(&candidate) {
813 n += 1;
814 candidate = format!("{stem}_{n}{ext}");
815 }
816 used.push(candidate.clone());
817 candidate
818}
819
820pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
822 crate::writer::write(dataset, out, options)
823}
824
825#[cfg(feature = "zip")]
830impl Dataset {
831 pub fn load_zip(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
835 self.load_zip_within(path, options, &Budget::new(options))
836 }
837
838 fn load_zip_within(
839 &mut self,
840 path: &Path,
841 options: &ReadOptions,
842 budget: &Budget,
843 ) -> Result<LoadReport> {
844 use crate::error::Error;
845
846 let file = File::open(path)?;
847 let mut archive = zip::ZipArchive::new(BufReader::new(file))
848 .map_err(|e| Error::Zip(format!("{}: {e}", path.display())))?;
849
850 let mut out = LoadReport::default();
852 let mut names: Vec<String> = Vec::new();
853 for name in archive.file_names() {
854 match name {
855 Ok(n) if n.to_ascii_lowercase().ends_with(".xml") => names.push(n.into_owned()),
856 Ok(_) => {}
857 Err(e) => out.report.push(
859 Diagnostic::error(
860 Rule::UnreadableFile,
861 format!("an entry name could not be decoded: {e}"),
862 )
863 .with_source(path.display().to_string()),
864 ),
865 }
866 }
867 names.sort();
868
869 for name in names {
870 let entry = archive
871 .by_name(&name)
872 .map_err(|e| Error::Zip(format!("{name}: {e}")))?;
873 let outcome = read_into_within(
876 self,
877 BufReader::with_capacity(1 << 16, entry),
878 Some(&name),
879 options,
880 budget,
881 )
882 .map_err(|e| match e {
883 Error::Io(io) => Error::Zip(format!("{}: {name}: {io}", path.display())),
884 other => other,
885 })?;
886 out.report.extend(outcome.report);
887 out.objects_read += outcome.objects_read;
888 out.files
889 .push((PathBuf::from(&name), outcome.header.clone()));
890 }
891 Ok(out)
892 }
893
894 pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>> {
896 use crate::error::Error;
897 use zip::write::SimpleFileOptions;
898
899 let file = File::create(path)?;
900 let mut zw = zip::ZipWriter::new(BufWriter::new(file));
901 let mut written = Vec::new();
902 let content = self.content_id();
904
905 for cov in crate::validate::profile_coverage(self) {
906 if cov.objects == 0 {
907 continue;
908 }
909 let name = format!("{stem}_{}.xml", cov.keyword);
910 zw.start_file(&name, SimpleFileOptions::default())
911 .map_err(|e| Error::Zip(e.to_string()))?;
912 let header =
913 crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
914 write_profile(
915 self,
916 cov.profile,
917 &mut zw,
918 &WriteOptions::default().with_header(header),
919 )?;
920 written.push(name);
921 }
922 zw.finish().map_err(|e| Error::Zip(e.to_string()))?;
923 Ok(written)
924 }
925}
926
927#[cfg(test)]
928mod tests {
929 use super::{output_file_name, unique_name};
930
931 #[test]
932 fn two_files_wanting_one_name_get_two_files() {
933 let mut used = Vec::new();
936 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ.xml");
937 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_2.xml");
938 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_3.xml");
939 assert_eq!(unique_name("SSH.xml".into(), &mut used), "SSH.xml");
940 assert_eq!(unique_name("model".into(), &mut used), "model");
942 assert_eq!(unique_name("model".into(), &mut used), "model_2");
943 assert_eq!(unique_name("EQ_2.xml".into(), &mut used), "EQ_2_2.xml");
945 }
946
947 #[test]
948 fn an_export_never_escapes_its_output_directory() {
949 assert_eq!(output_file_name("EQ.xml").as_deref(), Some("EQ.xml"));
952 assert_eq!(
953 output_file_name("model/EQ.xml").as_deref(),
954 Some("EQ.xml"),
955 "a nested archive entry keeps only its file name"
956 );
957 assert_eq!(
958 output_file_name("../../../etc/cron.d/pwn").as_deref(),
959 Some("pwn")
960 );
961 assert_eq!(output_file_name("/etc/passwd").as_deref(), Some("passwd"));
962 for hostile in ["..", ".", "", "/", "..\\..\\evil.xml", "a\0b"] {
963 assert_eq!(output_file_name(hostile), None, "{hostile:?}");
964 }
965 }
966}