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`; an archive entry
27    /// appears as `archive.zip/entry.xml`.
28    ///
29    /// Non-empty means the dataset lacks whatever those files held: a read applies a
30    /// whole document or nothing.
31    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    /// Load a set of instance files into a new dataset.
43    ///
44    /// Files may be given in any order: objects are merged by mRID, so an SSH file read
45    /// before its EQ file produces the same result.
46    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    /// Load files into an existing dataset.
57    ///
58    /// All files and archive entries share one input budget
59    /// ([`ReadOptions::max_input_bytes`]).
60    ///
61    /// # Errors
62    ///
63    /// [`Error::InputTooLarge`](crate::Error::InputTooLarge) under either strictness once
64    /// the budget is spent; the dataset is then partial and must be discarded. Under
65    /// [`Strictness::Strict`], the first file that cannot be read. Otherwise an unreadable
66    /// file or archive entry is reported as `CIM0022`, listed in [`LoadReport::failed`],
67    /// and contributes nothing: each document is applied whole or not at all.
68    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            // Lenient: one unreadable file is recorded and named, and the rest still load.
78            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                // Except the budget: a partial model must not pass as a success.
86                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    /// Load one instance file, or every instance file inside a zip archive.
103    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        // The reader registers the header itself, so objects record their source file.
147        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    /// Load every instance file under a directory, in sorted order.
157    ///
158    /// Model sets usually ship as directories; to name files individually use
159    /// [`Dataset::load`].
160    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    /// Load a model set, reading its vintage out of the files themselves.
167    ///
168    /// `path` is a directory, a zip archive or a single instance file; the schema comes
169    /// from the namespace declarations (see [`detect_vintage`]). Use [`Dataset::load_dir`]
170    /// or [`Dataset::load`] to state the vintage explicitly.
171    ///
172    /// # Errors
173    ///
174    /// [`Error::UnknownVintage`](crate::Error::UnknownVintage) when no file under `path`
175    /// declares a vocabulary this build has a feature for, including when `path` holds no
176    /// CIM input at all.
177    ///
178    /// ```no_run
179    /// # fn main() -> cim_kit::Result<()> {
180    /// let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
181    /// println!("{} objects", grid.len());
182    /// # Ok(()) }
183    /// ```
184    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    /// Read only the headers of a set of files, without loading their objects.
197    ///
198    /// Useful for deciding what to load: headers declare profiles and dependencies.
199    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    /// Apply a difference model (IEC 61970-552): check it applies to this model, remove
219    /// reverse statements, then assert forward statements.
220    ///
221    /// Refused, with one `CIM0014` error and the dataset unchanged, when a model named in
222    /// `md:Model.Supersedes` is neither loaded nor an earlier applied change set (compared
223    /// as identifiers), or when a `dm:preconditions` statement does not hold. Nothing is
224    /// checked if the dataset has no header identifiers or the change set names no base;
225    /// to skip the check, clear `diff.header.supersedes` or `diff.preconditions`.
226    ///
227    /// Otherwise, statements naming unknown classes or properties are reported and
228    /// skipped, and a retraction that does not hold is a warning, not a refusal.
229    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        // Asserted values belong to the profiles the change set's header declares, as if
237        // read from an instance file.
238        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        // Retract, re-type, assert: reverse statements describe the object as it was,
246        // forward ones what it becomes (e.g. a `LinearShuntCompensator` turned
247        // `NonlinearShuntCompensator`, then given attributes only the new class has).
248        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    /// Why `diff` must not be applied to this dataset, if it must not.
260    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    /// Apply class changes named by a difference's forward statements.
311    ///
312    /// IEC 61970-552 treats an object's type as a statement, so a difference may replace
313    /// an object's class under the same identifier.
314    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            // Narrowing to a subclass is a refinement; anything else is reported.
345            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            // Attributes the new class lacks are shed; report each one.
361            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    /// The attribute and value a difference statement names, resolved against the schema
382    /// — one implementation for applying a statement and for checking a precondition.
383    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                        // As in the reader: a misplaced namespace is recoverable.
420                        .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        // Asserting into an absent object creates it, which a forward difference may
474        // legitimately do when it introduces a new object.
475        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        // As in the reader: never assert an attribute the object's class lacks, since
501        // writer and validation would never see it. Retractions are exempt, because
502        // retracting such a value is how a change set removes it.
503        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    /// Write one profile of this dataset to a file.
544    pub fn save_profile(
545        &self,
546        path: &Path,
547        profile: ProfileId,
548        header: Option<ModelHeader>,
549    ) -> Result<()> {
550        // A caller's header wins; without one the writer derives a conforming one.
551        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    /// Write every profile the dataset carries data for, into `dir`, one file each.
565    ///
566    /// Files are named `<stem>_<KEYWORD>.xml`. Use [`Dataset::save_as_loaded`] instead
567    /// when the goal is to reproduce the file set the model was read from.
568    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        // Once per export, not per profile: it walks the whole model.
572        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    /// Write the model back out as the file set it was read from.
587    ///
588    /// One output file per loaded header, carrying that header, its profiles and the
589    /// objects read from that file ([`Dataset::objects_from`]), so a merged model with two
590    /// Equipment files writes two. Objects built programmatically go with the first header
591    /// whose profiles can carry them.
592    ///
593    /// A header without a resolvable profile is skipped and named in
594    /// [`SaveReport::skipped`]; objects only it held are counted in
595    /// [`SaveReport::unwritten`]. [`Dataset::save_all_profiles`] always writes something.
596    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        // Objects built programmatically go with the first file that can carry them.
602        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        // Which objects reached a file, for `SaveReport::unwritten`.
610        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            // Reuse the source file name, made unique: only the final component is kept,
636            // so `BE/EQ.xml` and `NL/EQ.xml` would otherwise collide.
637            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                // Match the statements to this header by identifier, else by source
656                // document (a `dm:DifferenceModel` may lack `rdf:about`).
657                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            // Everything the file carried, including property-less objects such as
679            // `<cim:ConnectivityNode rdf:ID="_x"/>` in boundary sets (D55).
680            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
703/// The schema vintage a set of inputs declares, taken from the first file that answers.
704///
705/// Files that cannot be read or are unrecognised are skipped, so one broken file does not
706/// decide the vintage of the rest.
707pub 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
715/// The schema vintage a file declares, or `None` if it cannot be read or is unrecognised.
716///
717/// A zip archive is opened for its first CIM/XML entry, since a model set often arrives as
718/// one. Unreadable is not an error here: [`Dataset::open`] moves on to the next file.
719pub 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        // Only looking for one readable document here; an undecodable name is reported
728        // by the load that reads the archive.
729        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
743/// Every CIM input under `path`, sorted so that a load is reproducible.
744///
745/// A plain file is returned as itself whatever its name; a directory is walked recursively
746/// for `.xml` files, and `.zip` files when the `zip` feature is on.
747pub 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/// Outcome of writing a model back to disk.
781#[derive(Debug, Default)]
782pub struct SaveReport {
783    pub written: Vec<PathBuf>,
784    /// Headers that declared no profile this schema recognises.
785    pub skipped: Vec<String>,
786    /// Objects no output file covers.
787    ///
788    /// Non-zero means the export is incomplete: those objects came from a file whose
789    /// header declares no recognised profile (e.g. one with no `md:FullModel`).
790    pub unwritten: usize,
791}
792
793/// The file name to write a header's model back to, confined to the output directory.
794///
795/// A zip entry name is chosen by the archive's author and may contain separators or `..`
796/// (zip-slip), so only the final component is kept, and only when it is an ordinary name.
797fn 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
806/// Give `name` a suffix if `used` already holds it, and record the result, so no output
807/// file overwrites another.
808fn 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
823/// Write a dataset to any sink, as a single document.
824pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
825    crate::writer::write(dataset, out, options)
826}
827
828// ---------------------------------------------------------------------------
829// Zip archives
830// ---------------------------------------------------------------------------
831
832#[cfg(feature = "zip")]
833impl Dataset {
834    /// Load every CIM/XML entry in a zip archive.
835    ///
836    /// Entries are read in name order and share one input budget.
837    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        // Read entries in name order so a load is reproducible.
854        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                // An undecodable entry name is not read; report it.
861                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            // 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 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                // An entry is a file of the set: lenient reports it and reads the rest.
894                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    /// Write every populated profile into one zip archive.
910    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        // Once for the archive, not once per profile: see `save_all_profiles`.
918        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
942/// The `CIM0022` finding for a file a lenient load could not read.
943fn 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        // A merged common grid model assembled from `BE/EQ.xml` and `NL/EQ.xml`: only the
958        // final component survives the traversal guard, so both headers ask for `EQ.xml`.
959        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        // A name without an extension still gets a distinct one.
965        assert_eq!(unique_name("model".into(), &mut used), "model");
966        assert_eq!(unique_name("model".into(), &mut used), "model_2");
967        // And a collision with an already-suffixed name keeps counting rather than looping.
968        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        // A header's source is the name of the document it was read from, and for a zip
974        // archive that name is chosen by whoever built the archive.
975        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}