Skip to main content

cim_kit/
load.rs

1//! Loading and saving whole models.
2//!
3//! A CGMES model is a set of profile files; this module loads them into one dataset,
4//! applies difference models, and exports per profile or per source file.
5
6use 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/// Outcome of loading one or more files.
21#[derive(Debug, Default)]
22pub struct LoadReport {
23    pub report: Report,
24    /// Files loaded, in order, with the header each carried.
25    pub files: Vec<(PathBuf, Option<ModelHeader>)>,
26    /// Files that could not be read, each also reported as `CIM0022`.
27    ///
28    /// Non-empty means the dataset lacks whatever those files held.
29    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    /// Load a set of instance files into a new dataset.
41    ///
42    /// Files may be given in any order: objects are merged by mRID, so an SSH file read
43    /// before its EQ file produces the same result.
44    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    /// Load files into an existing dataset.
55    ///
56    /// All files and archive entries share one input budget
57    /// ([`ReadOptions::max_input_bytes`]).
58    ///
59    /// # Errors
60    ///
61    /// [`Error::InputTooLarge`](crate::Error::InputTooLarge) under either strictness once
62    /// the budget is spent; the dataset is then partial and must be discarded. Under
63    /// [`Strictness::Strict`], the first file that cannot be read. Otherwise an unreadable
64    /// file is reported as `CIM0022` and listed in [`LoadReport::failed`].
65    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            // Lenient: one unreadable file is recorded and named, and the rest still load.
75            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                // Except the budget: a partial model must not pass as a success.
82                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    /// Load one instance file, or every instance file inside a zip archive.
100    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        // The reader registers the header itself, so objects record their source file.
144        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    /// Load every instance file under a directory, in sorted order.
154    ///
155    /// Model sets usually ship as directories; to name files individually use
156    /// [`Dataset::load`].
157    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    /// Load a model set, reading its vintage out of the files themselves.
164    ///
165    /// `path` is a directory, a zip archive or a single instance file; the schema comes
166    /// from the namespace declarations (see [`detect_vintage`]). Use [`Dataset::load_dir`]
167    /// or [`Dataset::load`] to state the vintage explicitly.
168    ///
169    /// # Errors
170    ///
171    /// [`Error::UnknownVintage`](crate::Error::UnknownVintage) when no file under `path`
172    /// declares a vocabulary this build has a feature for, including when `path` holds no
173    /// CIM input at all.
174    ///
175    /// ```no_run
176    /// # fn main() -> cim_kit::Result<()> {
177    /// let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
178    /// println!("{} objects", grid.len());
179    /// # Ok(()) }
180    /// ```
181    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    /// Read only the headers of a set of files, without loading their objects.
194    ///
195    /// Useful for deciding what to load: headers declare profiles and dependencies.
196    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    /// Apply a difference model (IEC 61970-552): check it applies to this model, remove
216    /// reverse statements, then assert forward statements.
217    ///
218    /// Refused, with one `CIM0014` error and the dataset unchanged, when a model named in
219    /// `md:Model.Supersedes` is neither loaded nor an earlier applied change set (compared
220    /// as identifiers), or when a `dm:preconditions` statement does not hold. Nothing is
221    /// checked if the dataset has no header identifiers or the change set names no base;
222    /// to skip the check, clear `diff.header.supersedes` or `diff.preconditions`.
223    ///
224    /// Otherwise, statements naming unknown classes or properties are reported and
225    /// skipped, and a retraction that does not hold is a warning, not a refusal.
226    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        // Asserted values belong to the profiles the change set's header declares, as if
234        // read from an instance file.
235        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        // Retract, re-type, assert: reverse statements describe the object as it was,
243        // forward ones what it becomes (e.g. a `LinearShuntCompensator` turned
244        // `NonlinearShuntCompensator`, then given attributes only the new class has).
245        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    /// Why `diff` must not be applied to this dataset, if it must not.
257    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    /// Apply class changes named by a difference's forward statements.
308    ///
309    /// IEC 61970-552 treats an object's type as a statement, so a difference may replace
310    /// an object's class under the same identifier.
311    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            // Narrowing to a subclass is a refinement; anything else is reported.
342            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            // Attributes the new class lacks are shed; report each one.
358            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    /// The attribute and value a difference statement names, resolved against the schema
379    /// — one implementation for applying a statement and for checking a precondition.
380    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                        // As in the reader: a misplaced namespace is recoverable.
417                        .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        // Asserting into an absent object creates it, which a forward difference may
471        // legitimately do when it introduces a new object.
472        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        // As in the reader: never assert an attribute the object's class lacks, since
498        // writer and validation would never see it. Retractions are exempt, because
499        // retracting such a value is how a change set removes it.
500        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    /// Write one profile of this dataset to a file.
541    pub fn save_profile(
542        &self,
543        path: &Path,
544        profile: ProfileId,
545        header: Option<ModelHeader>,
546    ) -> Result<()> {
547        // A caller's header wins; without one the writer derives a conforming one.
548        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    /// Write every profile the dataset carries data for, into `dir`, one file each.
562    ///
563    /// Files are named `<stem>_<KEYWORD>.xml`. Use [`Dataset::save_as_loaded`] instead
564    /// when the goal is to reproduce the file set the model was read from.
565    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        // Once per export, not per profile: it walks the whole model.
569        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    /// Write the model back out as the file set it was read from.
584    ///
585    /// One output file per loaded header, carrying that header, its profiles and the
586    /// objects read from that file ([`Dataset::objects_from`]), so a merged model with two
587    /// Equipment files writes two. Objects built programmatically go with the first header
588    /// whose profiles can carry them.
589    ///
590    /// A header without a resolvable profile is skipped and named in
591    /// [`SaveReport::skipped`]; objects only it held are counted in
592    /// [`SaveReport::unwritten`]. [`Dataset::save_all_profiles`] always writes something.
593    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        // Objects built programmatically go with the first file that can carry them.
599        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        // Which objects reached a file, for `SaveReport::unwritten`.
607        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            // Reuse the source file name, made unique: only the final component is kept,
633            // so `BE/EQ.xml` and `NL/EQ.xml` would otherwise collide.
634            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                // Match the statements to this header by identifier, else by source
653                // document (a `dm:DifferenceModel` may lack `rdf:about`).
654                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            // Everything the file carried, including property-less objects such as
676            // `<cim:ConnectivityNode rdf:ID="_x"/>` in boundary sets (D55).
677            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
700/// The schema vintage a set of inputs declares, taken from the first file that answers.
701///
702/// Files that cannot be read or are unrecognised are skipped, so one broken file does not
703/// decide the vintage of the rest.
704pub 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
712/// The schema vintage a file declares, or `None` if it cannot be read or is unrecognised.
713///
714/// A zip archive is opened for its first CIM/XML entry, since a model set often arrives as
715/// one. Unreadable is not an error here: [`Dataset::open`] moves on to the next file.
716pub 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        // Only looking for one readable document here; an undecodable name is reported
725        // by the load that reads the archive.
726        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
740/// Every CIM input under `path`, sorted so that a load is reproducible.
741///
742/// A plain file is returned as itself whatever its name; a directory is walked recursively
743/// for `.xml` files, and `.zip` files when the `zip` feature is on.
744pub 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/// Outcome of writing a model back to disk.
778#[derive(Debug, Default)]
779pub struct SaveReport {
780    pub written: Vec<PathBuf>,
781    /// Headers that declared no profile this schema recognises.
782    pub skipped: Vec<String>,
783    /// Objects no output file covers.
784    ///
785    /// Non-zero means the export is incomplete: those objects came from a file whose
786    /// header declares no recognised profile (e.g. one with no `md:FullModel`).
787    pub unwritten: usize,
788}
789
790/// The file name to write a header's model back to, confined to the output directory.
791///
792/// A zip entry name is chosen by the archive's author and may contain separators or `..`
793/// (zip-slip), so only the final component is kept, and only when it is an ordinary name.
794fn 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
803/// Give `name` a suffix if `used` already holds it, and record the result, so no output
804/// file overwrites another.
805fn 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
820/// Write a dataset to any sink, as a single document.
821pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
822    crate::writer::write(dataset, out, options)
823}
824
825// ---------------------------------------------------------------------------
826// Zip archives
827// ---------------------------------------------------------------------------
828
829#[cfg(feature = "zip")]
830impl Dataset {
831    /// Load every CIM/XML entry in a zip archive.
832    ///
833    /// Entries are read in name order and share one input budget.
834    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        // Read entries in name order so a load is reproducible.
851        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                // An undecodable entry name is not read; report it.
858                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            // Decompressed bytes are metered as parsed; the archive's size fields are not
874            // trusted. An I/O failure inside an entry is reported as a zip error, named.
875            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    /// Write every populated profile into one zip archive.
895    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        // Once for the archive, not once per profile: see `save_all_profiles`.
903        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        // A merged common grid model assembled from `BE/EQ.xml` and `NL/EQ.xml`: only the
934        // final component survives the traversal guard, so both headers ask for `EQ.xml`.
935        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        // A name without an extension still gets a distinct one.
941        assert_eq!(unique_name("model".into(), &mut used), "model");
942        assert_eq!(unique_name("model".into(), &mut used), "model_2");
943        // And a collision with an already-suffixed name keeps counting rather than looping.
944        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        // A header's source is the name of the document it was read from, and for a zip
950        // archive that name is chosen by whoever built the archive.
951        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}