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