cim_kit/load.rs
1//! Loading and saving whole models.
2//!
3//! A CGMES model is a set of profile files, so the convenient unit of work is "load
4//! these files into one dataset" rather than "parse this document". This module provides
5//! that, plus difference-model application and per-profile export.
6
7use std::fs::File;
8use std::io::{BufReader, BufWriter, Write};
9use std::path::{Path, PathBuf};
10
11use crate::dataset::Dataset;
12use crate::error::{Diagnostic, Report, Result, Rule};
13use crate::header::{DifferenceModel, ModelHeader, ModelKind, Statement, StatementValue};
14use crate::mrid::Mrid;
15use crate::object::Object;
16use crate::reader::{Budget, ReadOptions, Strictness, read_header, read_into_within};
17use crate::schema::{AttrKind, Primitive, ProfileId, Schema};
18use crate::value::Value;
19use crate::writer::{WriteOptions, write_profile};
20
21/// Outcome of loading one or more files.
22#[derive(Debug, Default)]
23pub struct LoadReport {
24 pub report: Report,
25 /// Files loaded, in order, with the header each carried.
26 pub files: Vec<(PathBuf, Option<ModelHeader>)>,
27 /// Files that could not be read, each also reported as `CIM0022`.
28 ///
29 /// Non-empty means the model is missing whatever they held: it is assembled from what
30 /// could be read, which is the useful answer, but it is not the model the caller named.
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 /// The files share one input budget ([`ReadOptions::max_input_bytes`]): a model set is
59 /// one load, however many files and archive entries it arrives as.
60 ///
61 /// # Errors
62 ///
63 /// [`Error::InputTooLarge`](crate::Error::InputTooLarge) under either strictness once
64 /// the budget is spent — the dataset then holds part of the model and must be
65 /// discarded. Under [`Strictness::Strict`], the first file that cannot be read.
66 pub fn load_files<I, P>(&mut self, paths: I, options: &ReadOptions) -> Result<LoadReport>
67 where
68 I: IntoIterator<Item = P>,
69 P: AsRef<Path>,
70 {
71 let budget = Budget::new(options);
72 let mut out = LoadReport::default();
73 for path in paths {
74 let path = path.as_ref();
75 // A model set is several files and one of them being unreadable says nothing
76 // about the rest. ENTSO-E's own quality-check corpus contains exactly that
77 // case — a six-file set whose Equipment archive holds the text `nonxmlfile` —
78 // and aborting the load answered it with a single message that did not even
79 // name the file, while the other five were never looked at. Reading is
80 // tolerant by default and this is the same rule one level up: record it, name
81 // it, carry on. `Strictness::Strict` still refuses.
82 match self.load_file_within(path, options, &budget) {
83 Ok(one) => {
84 out.report.extend(one.report);
85 out.files.extend(one.files);
86 out.objects_read += one.objects_read;
87 }
88 // Not the budget, though: a load that stopped there holds part of the model,
89 // and recording it as one more unreadable file would hand that part back
90 // as a success.
91 Err(e) if options.strictness == Strictness::Lenient && !budget.tripped() => {
92 out.failed.push(path.to_path_buf());
93 out.report.push(
94 Diagnostic::error(Rule::UnreadableFile, e.to_string()).with_source(
95 path.file_name()
96 .map(|n| n.to_string_lossy().into_owned())
97 .unwrap_or_else(|| path.display().to_string()),
98 ),
99 );
100 }
101 Err(e) => return Err(e),
102 }
103 }
104 self.shrink_to_fit();
105 Ok(out)
106 }
107
108 /// Load one instance file, or every instance file inside a zip archive.
109 pub fn load_file(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
110 self.load_file_within(path, options, &Budget::new(options))
111 }
112
113 fn load_file_within(
114 &mut self,
115 path: &Path,
116 options: &ReadOptions,
117 budget: &Budget,
118 ) -> Result<LoadReport> {
119 if path
120 .extension()
121 .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
122 {
123 #[cfg(feature = "zip")]
124 {
125 return self.load_zip_within(path, options, budget);
126 }
127 #[cfg(not(feature = "zip"))]
128 {
129 return Err(crate::error::Error::NotCimXml(format!(
130 "{} is a zip archive; enable the `zip` feature to read it",
131 path.display()
132 )));
133 }
134 }
135
136 let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
137 let file = File::open(path)?;
138 let outcome = read_into_within(
139 self,
140 BufReader::with_capacity(1 << 16, file),
141 name.as_deref(),
142 options,
143 budget,
144 )?;
145
146 let mut report = LoadReport {
147 report: outcome.report,
148 objects_read: outcome.objects_read,
149 files: vec![(path.to_path_buf(), outcome.header.clone())],
150 failed: Vec::new(),
151 };
152 // The reader registers the header itself, so that each object records the file it
153 // came from while it is being read.
154 if outcome.header.is_none() {
155 report.report.push(
156 Diagnostic::warning(Rule::MalformedHeader, "file has no md:FullModel header")
157 .with_source(name.unwrap_or_default()),
158 );
159 }
160 Ok(report)
161 }
162
163 /// Load every instance file under a directory, in sorted order.
164 ///
165 /// A CGMES model set is a directory, not a list — that is how the conformity models,
166 /// the QoCDC models and every real exchange are shipped — so this is the call most
167 /// programs actually want. Naming the files individually is [`Dataset::load`].
168 pub fn load_dir(schema: &'static Schema, dir: impl AsRef<Path>) -> Result<Dataset> {
169 let mut ds = Dataset::new(schema);
170 ds.load_files(instance_files(dir.as_ref()), &ReadOptions::lenient())?;
171 Ok(ds)
172 }
173
174 /// Load a model set, reading its vintage out of the files themselves.
175 ///
176 /// The call most programs want. `path` is a directory, a zip archive or a single
177 /// instance file; the schema comes from the first document's namespace declarations, so
178 /// the caller does not have to know — or hard-code — whether a model is CGMES 3.0 or
179 /// 2.4.15.
180 ///
181 /// Use [`Dataset::load_dir`] or [`Dataset::load`] to state the vintage explicitly, which
182 /// is what a program that only ever handles one of them should do.
183 ///
184 /// # Errors
185 ///
186 /// [`Error::UnknownVintage`](crate::Error::UnknownVintage) when no file under `path`
187 /// declares a vocabulary this build
188 /// has a feature for — including when `path` holds no CIM input at all.
189 ///
190 // An example has to name a vintage only when it names a schema; this one does not, so
191 // it compiles under any feature set.
192 /// ```no_run
193 /// # fn main() -> cim_kit::Result<()> {
194 /// let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
195 /// println!("{} objects", grid.len());
196 /// # Ok(()) }
197 /// ```
198 pub fn open(path: impl AsRef<Path>) -> Result<Dataset> {
199 let path = path.as_ref();
200 let files = instance_files(path);
201 let schema = detect_vintage(&files).ok_or_else(|| crate::error::Error::UnknownVintage {
202 path: path.display().to_string(),
203 known: crate::VINTAGES.iter().map(|s| s.vintage).collect(),
204 })?;
205 let mut ds = Dataset::new(schema);
206 ds.load_files(&files, &ReadOptions::lenient())?;
207 Ok(ds)
208 }
209
210 /// Read only the headers of a set of files, without loading their objects.
211 ///
212 /// Useful for deciding what to load: headers declare profiles and dependencies.
213 pub fn peek_headers<I, P>(
214 schema: &'static Schema,
215 paths: I,
216 ) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
217 where
218 I: IntoIterator<Item = P>,
219 P: AsRef<Path>,
220 {
221 let mut out = Vec::new();
222 for path in paths {
223 let path = path.as_ref();
224 let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
225 let file = File::open(path)?;
226 let header = read_header(schema, BufReader::new(file), name.as_deref())?;
227 out.push((path.to_path_buf(), header));
228 }
229 Ok(out)
230 }
231
232 /// Apply a difference model (IEC 61970-552): check it applies to this model, remove
233 /// reverse statements, then assert forward statements.
234 ///
235 /// A change set is a statement about one model state, so it is refused — the report
236 /// holds one `CIM0014` error and the dataset is left unchanged — when a model its
237 /// `md:Model.Supersedes` names is neither loaded here nor an earlier change set applied
238 /// here (compared as identifiers, so spelling does not matter), or when one of its
239 /// `dm:preconditions` does not hold. A dataset with no header identifiers, or a change
240 /// set naming no base, has nothing to compare and is not checked. A caller who knows
241 /// better clears `diff.header.supersedes` or `diff.preconditions`.
242 ///
243 /// Past that gate, statements naming objects or properties the schema does not know are
244 /// reported and skipped rather than aborting the whole application, and a retraction
245 /// that does not hold is a warning: published change sets reconcile files that
246 /// disagree, so it is evidence rather than grounds to refuse.
247 pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report {
248 let schema = self.schema();
249 let mut report = Report::default();
250 if let Some(refusal) = self.refusal(diff) {
251 report.push(refusal);
252 return report;
253 }
254 // Values a difference asserts belong to the profiles its own header declares,
255 // exactly as if they had arrived in an instance file. Without that, an export
256 // would fall back to the attribute's declaration and could file the change under
257 // a profile the change set never claimed.
258 let profiles = diff
259 .header
260 .profiles
261 .iter()
262 .filter_map(|iri| schema.profile_by_iri(iri))
263 .fold(0, |acc, p| acc | p.mask());
264
265 // Retract, then re-type, then assert. The order matters and is the standard's own:
266 // a reverse statement talks about the object as it *was*, so it has to be applied
267 // while the object still has its old class, and a forward statement talks about
268 // what it becomes. The published conformity change sets replace a
269 // `LinearShuntCompensator` with a `NonlinearShuntCompensator` under one identifier
270 // and then set attributes only the new class has — which is exactly the case that
271 // re-typing last would get wrong.
272 for s in &diff.reverse {
273 self.apply_statement(s, false, profiles, &mut report);
274 }
275 self.apply_reclassifications(diff, &mut report);
276 for s in &diff.forward {
277 self.apply_statement(s, true, profiles, &mut report);
278 }
279 self.record_applied(diff.header.id.clone(), &diff.header.supersedes);
280 report
281 }
282
283 /// Why `diff` must not be applied to this dataset, if it must not.
284 fn refusal(&self, diff: &DifferenceModel) -> Option<Diagnostic> {
285 let loaded: Vec<&Mrid> = self.model_ids().collect();
286 if !loaded.is_empty()
287 && let Some(missing) = diff
288 .header
289 .supersedes
290 .iter()
291 .find(|id| !loaded.contains(id))
292 {
293 let mut held: Vec<String> = loaded.iter().map(|m| m.canonical()).collect();
294 held.sort();
295 return Some(Diagnostic::error(
296 Rule::UnsatisfiedDependency,
297 format!(
298 "change set not applied: it supersedes model {}, which is not loaded \
299 (this dataset holds {}); it was computed against another model",
300 missing.canonical(),
301 held.join(", ")
302 ),
303 ));
304 }
305 for s in &diff.preconditions {
306 let mut scratch = Report::default();
307 let holds = self
308 .statement_value(s, &mut scratch)
309 .is_some_and(|(attr, value)| {
310 self.find(&s.subject)
311 .and_then(|id| self.get(id))
312 .is_some_and(|o| o.values().any(|(a, v)| a == attr && *v == value))
313 });
314 if !holds {
315 return Some(
316 Diagnostic::error(
317 Rule::UnsatisfiedDependency,
318 format!(
319 "change set not applied: its precondition {} {} does not hold",
320 s.predicate,
321 match &s.value {
322 StatementValue::Resource(r) => r.as_str(),
323 StatementValue::Literal(t) => t.as_str(),
324 }
325 ),
326 )
327 .with_object(s.subject.clone()),
328 );
329 }
330 }
331 None
332 }
333
334 /// Apply class changes named by a difference's forward statements.
335 ///
336 /// IEC 61970-552 treats an object's type as a statement like any other, so a
337 /// difference may replace an object's class. The published CGMES conformity tests do
338 /// exactly this, turning a `LinearShuntCompensator` into a `NonlinearShuntCompensator`
339 /// under the same identifier; the reverse statements retract the old class's
340 /// attributes and the forward ones assert the new class's.
341 fn apply_reclassifications(&mut self, diff: &DifferenceModel, report: &mut Report) {
342 let schema = self.schema();
343 let mut seen: Vec<Mrid> = Vec::new();
344
345 for s in &diff.forward {
346 let Some(qname) = &s.class else { continue };
347 if seen.contains(&s.subject) {
348 continue;
349 }
350 seen.push(s.subject.clone());
351
352 let Some(target) = schema.find_class(&qname.ns, &qname.local) else {
353 report.push(
354 Diagnostic::warning(
355 Rule::UnknownClass,
356 format!("difference names unknown class {}", qname.local),
357 )
358 .with_object(s.subject.clone()),
359 );
360 continue;
361 };
362 let Some(id) = self.find(&s.subject) else {
363 continue;
364 };
365 let Some(current) = self.get(id).map(|o| o.class()) else {
366 continue;
367 };
368 if current == target {
369 continue;
370 }
371 // Only a genuine change is applied. Narrowing to a subclass is a refinement
372 // and is accepted; anything else is a reclassification worth recording.
373 if !schema.is_a(target, current) {
374 report.push(
375 Diagnostic::info(
376 Rule::Structure,
377 format!(
378 "difference reclassifies {} from {} to {}",
379 s.subject.canonical(),
380 schema.class(current).name,
381 schema.class(target).name
382 ),
383 )
384 .with_object(s.subject.clone())
385 .with_class(schema.class(target).name),
386 );
387 }
388 // A sideways reclassification leaves the old class's own attributes with
389 // nowhere to live. The dataset sheds them so the model stays consistent; what
390 // went is reported here, because it is data the change set's author chose to
391 // discard and a consumer should be able to see that it happened.
392 for slot in self.reclassify(id, target) {
393 let def = schema.attr(slot.attr);
394 report.push(
395 Diagnostic::warning(
396 Rule::Structure,
397 format!(
398 "{} was dropped: {} does not have it, and the difference \
399 reclassified this object",
400 def.name,
401 schema.class(target).name
402 ),
403 )
404 .with_class(schema.class(target).name)
405 .with_object(s.subject.clone())
406 .with_attribute(def.name),
407 );
408 }
409 }
410 }
411
412 /// The attribute and value a difference statement names, resolved against the schema
413 /// — one implementation for applying a statement and for checking a precondition.
414 fn statement_value(
415 &self,
416 s: &Statement,
417 report: &mut Report,
418 ) -> Option<(crate::schema::AttrId, Value)> {
419 let schema = self.schema();
420 let Some(attr) = schema.find_attr(&s.predicate_ns, &s.predicate) else {
421 report.push(
422 Diagnostic::warning(
423 Rule::UnknownAttribute,
424 format!(
425 "difference statement names unknown property {}",
426 s.predicate
427 ),
428 )
429 .with_object(s.subject.clone()),
430 );
431 return None;
432 };
433 let def = schema.attr(attr);
434
435 let value = match &s.value {
436 StatementValue::Resource(iri) => match def.kind {
437 AttrKind::Enumeration(_) => {
438 let Some((ns, local)) = iri.rsplit_once('#') else {
439 report.push(
440 Diagnostic::error(
441 Rule::InvalidValue,
442 format!("enumeration value {iri} is not an IRI"),
443 )
444 .with_attribute(def.name),
445 );
446 return None;
447 };
448 match schema
449 .find_enum_value(&format!("{ns}#"), local)
450 // As in the reader: a misplaced namespace is recoverable.
451 .or_else(|| schema.find_enum_value_any_ns(local))
452 {
453 Some(v) => Value::Enum(v),
454 None => {
455 report.push(
456 Diagnostic::error(
457 Rule::InvalidValue,
458 format!("unknown enumeration literal {iri}"),
459 )
460 .with_attribute(def.name)
461 .with_object(s.subject.clone()),
462 );
463 return None;
464 }
465 }
466 }
467 _ => Value::Reference(Mrid::parse(iri)),
468 },
469 StatementValue::Literal(text) => {
470 let prim = match def.kind {
471 AttrKind::Primitive(p) => p,
472 AttrKind::Datatype(d) => schema.datatype(d).value,
473 _ => Primitive::String,
474 };
475 match Value::parse_primitive(prim, text) {
476 Ok(v) => v,
477 Err(e) => {
478 report.push(
479 Diagnostic::error(Rule::InvalidValue, e.to_string())
480 .with_attribute(def.name)
481 .with_object(s.subject.clone()),
482 );
483 return None;
484 }
485 }
486 }
487 };
488 Some((attr, value))
489 }
490
491 fn apply_statement(
492 &mut self,
493 s: &Statement,
494 assert: bool,
495 profiles: crate::schema::ProfileMask,
496 report: &mut Report,
497 ) {
498 let schema = self.schema();
499 let Some((attr, value)) = self.statement_value(s, report) else {
500 return;
501 };
502 let def = schema.attr(attr);
503
504 // Asserting into an absent object creates it, which a forward difference may
505 // legitimately do when it introduces a new object.
506 let id = match self.find(&s.subject) {
507 Some(id) => id,
508 None if assert => {
509 let class = s
510 .class
511 .as_ref()
512 .and_then(|c| schema.find_class(&c.ns, &c.local))
513 .unwrap_or(def.owner);
514 self.insert(Object::new(class, s.subject.clone()))
515 }
516 None => {
517 report.push(
518 Diagnostic::warning(
519 Rule::DanglingReference,
520 format!(
521 "difference removes from {} which is not in the dataset",
522 s.subject.canonical()
523 ),
524 )
525 .with_attribute(def.name),
526 );
527 return;
528 }
529 };
530
531 // The same guard the reader applies to a property element, for the same reason: a
532 // value stored under an attribute the object's class does not have is invisible
533 // afterwards — the writer emits a class's own attributes and validation checks
534 // them, so neither would ever look at it — and it would be dropped without a word
535 // on the next export. A difference statement is not more trustworthy than a
536 // document just because it arrived as a change set.
537 //
538 // Assertions only. A *retraction* of such a value is exactly how the model gets
539 // rid of one, and refusing it would strand the value it was sent to remove: the
540 // published CGMES 2.4.15 Type 4 archive has an object its Equipment file calls a
541 // `LinearShuntCompensator` and its Steady State Hypothesis file a
542 // `NonlinearShuntCompensator`, and the change set that reconciles them opens by
543 // retracting the linear attributes from what is, by then, a nonlinear object.
544 let class = self.get(id).map(|o| o.class());
545 if assert
546 && let Some(class) = class
547 && !schema.is_a(class, def.owner)
548 {
549 report.push(
550 Diagnostic::warning(
551 Rule::UnknownAttribute,
552 format!(
553 "difference statement sets {} on {}, which does not have it",
554 def.name,
555 schema.class(class).name
556 ),
557 )
558 .with_class(schema.class(class).name)
559 .with_object(s.subject.clone())
560 .with_attribute(def.name),
561 );
562 return;
563 }
564
565 let Some(obj) = self.get_mut(id) else { return };
566 if assert {
567 if def.mult.is_many() {
568 obj.push_in(profiles, attr, value);
569 } else {
570 obj.set_in(profiles, attr, value);
571 }
572 obj.mark_profile(profiles);
573 } else if !obj.remove_value(attr, &value) {
574 report.push(
575 Diagnostic::info(
576 Rule::Structure,
577 format!("difference removes {} which was not present", def.name),
578 )
579 .with_object(s.subject.clone()),
580 );
581 }
582 }
583
584 /// Write one profile of this dataset to a file.
585 pub fn save_profile(
586 &self,
587 path: &Path,
588 profile: ProfileId,
589 header: Option<ModelHeader>,
590 ) -> Result<()> {
591 // `IdStyle::Auto` decides per class whether this profile defines the object or
592 // only adds to it, which is what IEC 61970-552 means by rdf:ID versus rdf:about.
593 // A caller's header wins; without one the writer derives a conforming one.
594 let options = match header {
595 Some(h) => WriteOptions::default().with_header(h),
596 None => WriteOptions::default(),
597 };
598 let file = File::create(path)?;
599 write_profile(
600 self,
601 profile,
602 BufWriter::with_capacity(1 << 16, file),
603 &options,
604 )
605 }
606
607 /// Write every profile the dataset carries data for, into `dir`, one file each.
608 ///
609 /// Files are named `<stem>_<KEYWORD>.xml`. Use [`Dataset::save_as_loaded`] instead
610 /// when the goal is to reproduce the file set the model was read from.
611 pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>> {
612 std::fs::create_dir_all(dir)?;
613 let mut written = Vec::new();
614 // Once for the export, not once per profile: deriving a header needs the model's
615 // content identifier, and computing that walks the whole model.
616 let content = self.content_id();
617 for cov in crate::validate::profile_coverage(self) {
618 if cov.objects == 0 {
619 continue;
620 }
621 let path = dir.join(format!("{stem}_{}.xml", cov.keyword));
622 let header =
623 crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
624 self.save_profile(&path, cov.profile, Some(header))?;
625 written.push(path);
626 }
627 Ok(written)
628 }
629
630 /// Write the model back out as the file set it was read from.
631 ///
632 /// One output file per loaded header, carrying that header, the profiles it declared
633 /// and the objects that came from it. CGMES normally exchanges Equipment, Operation
634 /// and ShortCircuit in a single file; splitting them apart would be legal but would
635 /// not reproduce the input, so this is the faithful export.
636 ///
637 /// Selecting by profile alone is not enough for a merged common grid model, where two
638 /// modelling authorities each contribute an Equipment file: every object would then
639 /// land in both. The dataset therefore records which file contributed each object —
640 /// see [`Dataset::objects_from`] — and each header writes its own. Objects built
641 /// programmatically belong to no file and go with the first header whose profiles can
642 /// carry them, rather than being dropped.
643 ///
644 /// Returns the paths written. A header without a resolvable profile is skipped and
645 /// named in the report, and the objects that came only from it are counted in
646 /// [`SaveReport::unwritten`] — this is a faithful reproduction of a file set, so where
647 /// there is no file to reproduce, nothing is invented. [`Dataset::save_all_profiles`]
648 /// is the export that always writes something.
649 pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport> {
650 std::fs::create_dir_all(dir)?;
651 let schema = self.schema();
652 let mut out = SaveReport::default();
653
654 // Objects built programmatically belong to no file; they go with the first file
655 // whose profiles can carry them, rather than being dropped.
656 let unsourced: Vec<crate::dataset::ObjectId> = self
657 .iter()
658 .filter(|(_, o)| !o.from_file())
659 .map(|(id, _)| id)
660 .collect();
661 let mut unsourced_placed = false;
662 let mut used_names: Vec<String> = Vec::new();
663 // Which objects reached a file. A header this schema cannot resolve a profile for
664 // writes nothing, and its objects would otherwise leave in silence — the failure
665 // this counts is a whole model exporting as an empty directory and a success.
666 let mut covered = vec![false; self.len()];
667 let mark = |ids: &[crate::dataset::ObjectId], covered: &mut Vec<bool>| {
668 for id in ids {
669 if let Some(slot) = covered.get_mut(id.index()) {
670 *slot = true;
671 }
672 }
673 };
674
675 for (i, header) in self.headers().iter().enumerate() {
676 let profiles = header
677 .profiles
678 .iter()
679 .filter_map(|iri| schema.profile_by_iri(iri))
680 .fold(0, |acc, p| acc | p.mask());
681 if profiles == 0 {
682 out.skipped.push(
683 header
684 .source
685 .clone()
686 .unwrap_or_else(|| format!("header {i}")),
687 );
688 continue;
689 }
690
691 // Reuse the source file name so a directory can be regenerated in place —
692 // unless another header already claimed it. Two headers can want the same
693 // name: `save_as_loaded` keeps only the final path component (a zip entry
694 // name is chosen by whoever built the archive), so a merged model assembled
695 // from `BE/EQ.xml` and `NL/EQ.xml` would otherwise write one file, silently
696 // lose an authority's equipment, and report the same path twice as written.
697 let name = unique_name(
698 header
699 .source
700 .as_deref()
701 .and_then(output_file_name)
702 .unwrap_or_else(|| format!("model_{i}.xml")),
703 &mut used_names,
704 );
705 let path = dir.join(&name);
706 let file = File::create(&path)?;
707 let sink = BufWriter::with_capacity(1 << 16, file);
708 let options = WriteOptions {
709 profiles,
710 header: crate::writer::HeaderSource::Given(Box::new(header.clone())),
711 ..Default::default()
712 };
713
714 if header.kind == ModelKind::Difference {
715 // A change file holds statements, not objects, so the statements have to be
716 // matched to the header: by identifier, or failing that by the document both
717 // were read from — a `dm:DifferenceModel` with no `rdf:about` has no
718 // identifier to match on.
719 let diff = self
720 .differences()
721 .iter()
722 .find(|d| d.header.id.is_some() && d.header.id == header.id)
723 .or_else(|| {
724 self.differences()
725 .iter()
726 .find(|d| d.header.source.is_some() && d.header.source == header.source)
727 });
728 match diff {
729 Some(d) => crate::writer::write_difference(schema, d, sink, &options)?,
730 None => {
731 out.skipped
732 .push(format!("{name}: difference statements were not retained"));
733 continue;
734 }
735 }
736 out.written.push(path);
737 continue;
738 }
739
740 // Everything the file carried, whether or not it said anything about it.
741 // Membership is recorded when the element is read; whether the object has a
742 // value in this file's profiles is an inference, and it is wrong for a shape
743 // boundary sets use constantly — `<cim:ConnectivityNode rdf:ID="_x"/>` with no
744 // property children, introduced here and described by Topology Boundary (D55).
745 let mut ids: Vec<_> = self.objects_from(i).collect();
746 if !unsourced_placed && !unsourced.is_empty() {
747 let before = ids.len();
748 ids.extend(unsourced.iter().copied().filter(|&id| {
749 self.get(id)
750 .is_some_and(|o| crate::writer::object_has_content_in(schema, o, profiles))
751 }));
752 unsourced_placed = ids.len() > before;
753 }
754
755 mark(&ids, &mut covered);
756 crate::writer::write_objects(self, ids.into_iter(), sink, &options)?;
757 out.written.push(path);
758 }
759
760 out.unwritten = self
761 .iter()
762 .filter(|(id, _)| !covered.get(id.index()).copied().unwrap_or(false))
763 .count();
764 Ok(out)
765 }
766}
767
768/// The schema vintage a set of inputs declares, taken from the first file that answers.
769///
770/// The first file is not necessarily the one that can be read: ENTSO-E's quality-check
771/// corpus has a six-file set whose *Equipment* archive is deliberately not XML, and taking
772/// only the first answer there means reading five CGMES 2.4.15 files as CGMES 3.0 — 211
773/// unknown-class warnings and an empty model, which is what `CIM0021` exists to prevent.
774///
775/// One function rather than one per caller, because [`Dataset::open`] walked the whole list
776/// and the `cim` tool looked at exactly one, and the difference was invisible until a file
777/// that could not be read happened to come first.
778pub fn detect_vintage<I, P>(paths: I) -> Option<&'static Schema>
779where
780 I: IntoIterator<Item = P>,
781 P: AsRef<Path>,
782{
783 paths.into_iter().find_map(|p| detect_file(p.as_ref()))
784}
785
786/// The schema vintage a file declares, or `None` if it cannot be read or is unrecognised.
787///
788/// A zip archive is opened for its first CIM/XML entry, since a model set often arrives as
789/// one. Unreadable is not an error here: [`Dataset::open`] moves on to the next file.
790pub fn detect_file(path: &Path) -> Option<&'static Schema> {
791 #[cfg(feature = "zip")]
792 if path
793 .extension()
794 .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
795 {
796 let file = File::open(path).ok()?;
797 let mut zip = zip::ZipArchive::new(BufReader::new(file)).ok()?;
798 // Only looking for one readable document here; an undecodable name is reported
799 // by the load that reads the archive.
800 let mut names: Vec<String> = zip
801 .file_names()
802 .filter_map(|n| n.ok())
803 .filter(|n| n.to_ascii_lowercase().ends_with(".xml"))
804 .map(|n| n.into_owned())
805 .collect();
806 names.sort();
807 let entry = zip.by_name(names.first()?).ok()?;
808 return crate::reader::sniff(BufReader::new(entry)).ok().flatten();
809 }
810 let file = File::open(path).ok()?;
811 crate::reader::sniff(BufReader::new(file)).ok().flatten()
812}
813
814/// Every CIM input under `path`, sorted so that a load is reproducible.
815///
816/// A plain file is returned as itself whatever its name; a directory is walked recursively
817/// and the files that look like CIM inputs are kept — `.xml`, and `.zip` when the `zip`
818/// feature is on, since without it an archive can only produce an error.
819///
820/// Exposed because every program that touches a model set needs it and the answer is not
821/// quite obvious: models arrive as directories, the directories nest, and the order files
822/// are read in has to be fixed for a load to be reproducible even though merging makes it
823/// otherwise immaterial.
824pub fn instance_files(path: impl AsRef<Path>) -> Vec<PathBuf> {
825 let path = path.as_ref();
826 fn looks_like_input(path: &Path) -> bool {
827 let Some(ext) = path.extension() else {
828 return false;
829 };
830 ext.eq_ignore_ascii_case("xml")
831 || (cfg!(feature = "zip") && ext.eq_ignore_ascii_case("zip"))
832 }
833 fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
834 let Ok(entries) = std::fs::read_dir(dir) else {
835 return;
836 };
837 for e in entries.flatten() {
838 let p = e.path();
839 if p.is_dir() {
840 walk(&p, out);
841 } else if looks_like_input(&p) {
842 out.push(p);
843 }
844 }
845 }
846
847 let mut out = Vec::new();
848 if path.is_dir() {
849 walk(path, &mut out);
850 out.sort();
851 } else if path.is_file() {
852 out.push(path.to_path_buf());
853 }
854 out
855}
856
857/// Outcome of writing a model back to disk.
858#[derive(Debug, Default)]
859pub struct SaveReport {
860 pub written: Vec<PathBuf>,
861 /// Headers that declared no profile this schema recognises.
862 pub skipped: Vec<String>,
863 /// Objects no output file covers.
864 ///
865 /// Non-zero means the export is not the model: an object belongs to a file whose
866 /// header declares no profile — a document with no `md:FullModel` at all, for
867 /// instance — and there is nothing to reproduce it into. Reported as a number rather
868 /// than left to be inferred from an empty `written`, because a *partly* exported model
869 /// is the case that looks like success.
870 pub unwritten: usize,
871}
872
873/// The file name to write a header's model back to, confined to the output directory.
874///
875/// A header's `source` is whatever named the document it was read from, and that is not
876/// always a plain file name: reading a zip archive records the *entry* name, which the
877/// archive's author chose and which may contain directory separators or `..`. Joining that
878/// onto an output directory would let an archive decide where this process writes — the
879/// classic zip-slip. Only the final component is kept, and only when it is an ordinary
880/// name.
881fn output_file_name(source: &str) -> Option<String> {
882 let candidate = Path::new(source).file_name()?.to_str()?;
883 let plain = !candidate.is_empty()
884 && candidate != "."
885 && candidate != ".."
886 && !candidate.contains(['/', '\\', '\0']);
887 plain.then(|| candidate.to_owned())
888}
889
890/// Give `name` a suffix if `used` already holds it, and record the result.
891///
892/// Not a nicety: without it a second file wanting the same name overwrites the first, and
893/// the caller is told both were written.
894fn unique_name(name: String, used: &mut Vec<String>) -> String {
895 let mut candidate = name.clone();
896 let (stem, ext) = match name.rsplit_once('.') {
897 Some((s, e)) if !s.is_empty() => (s, format!(".{e}")),
898 _ => (name.as_str(), String::new()),
899 };
900 let mut n = 1;
901 while used.contains(&candidate) {
902 n += 1;
903 candidate = format!("{stem}_{n}{ext}");
904 }
905 used.push(candidate.clone());
906 candidate
907}
908
909/// Write a dataset to any sink, as a single document.
910pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
911 crate::writer::write(dataset, out, options)
912}
913
914// ---------------------------------------------------------------------------
915// Zip archives
916// ---------------------------------------------------------------------------
917
918#[cfg(feature = "zip")]
919impl Dataset {
920 /// Load every CIM/XML entry in a zip archive.
921 ///
922 /// CGMES model sets are routinely distributed as archives, sometimes with one
923 /// instance file per archive and sometimes with a whole model set inside one.
924 pub fn load_zip(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
925 self.load_zip_within(path, options, &Budget::new(options))
926 }
927
928 fn load_zip_within(
929 &mut self,
930 path: &Path,
931 options: &ReadOptions,
932 budget: &Budget,
933 ) -> Result<LoadReport> {
934 use crate::error::Error;
935
936 let file = File::open(path)?;
937 let mut archive = zip::ZipArchive::new(BufReader::new(file))
938 .map_err(|e| Error::Zip(format!("{}: {e}", path.display())))?;
939
940 // Read entries in name order so a load is reproducible.
941 let mut out = LoadReport::default();
942 let mut names: Vec<String> = Vec::new();
943 for name in archive.file_names() {
944 match name {
945 Ok(n) if n.to_ascii_lowercase().ends_with(".xml") => names.push(n.into_owned()),
946 Ok(_) => {}
947 // An entry whose name the archive cannot decode is an entry this load does
948 // not read, and that is said rather than skipped.
949 Err(e) => out.report.push(
950 Diagnostic::error(
951 Rule::UnreadableFile,
952 format!("an entry name could not be decoded: {e}"),
953 )
954 .with_source(path.display().to_string()),
955 ),
956 }
957 }
958 names.sort();
959
960 for name in names {
961 let entry = archive
962 .by_name(&name)
963 .map_err(|e| Error::Zip(format!("{name}: {e}")))?;
964 // The entry's decompressed bytes, counted as the parser takes them: the
965 // archive's own size fields are the attacker's to write.
966 // A read failure inside an entry is the archive's — zip refuses an entry that
967 // inflates past the size it declares — so it is reported as one, named.
968 let outcome = read_into_within(
969 self,
970 BufReader::with_capacity(1 << 16, entry),
971 Some(&name),
972 options,
973 budget,
974 )
975 .map_err(|e| match e {
976 Error::Io(io) => Error::Zip(format!("{}: {name}: {io}", path.display())),
977 other => other,
978 })?;
979 out.report.extend(outcome.report);
980 out.objects_read += outcome.objects_read;
981 out.files
982 .push((PathBuf::from(&name), outcome.header.clone()));
983 }
984 Ok(out)
985 }
986
987 /// Write every populated profile into one zip archive.
988 pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>> {
989 use crate::error::Error;
990 use zip::write::SimpleFileOptions;
991
992 let file = File::create(path)?;
993 let mut zw = zip::ZipWriter::new(BufWriter::new(file));
994 let mut written = Vec::new();
995 // Once for the archive, not once per profile: see `save_all_profiles`.
996 let content = self.content_id();
997
998 for cov in crate::validate::profile_coverage(self) {
999 if cov.objects == 0 {
1000 continue;
1001 }
1002 let name = format!("{stem}_{}.xml", cov.keyword);
1003 zw.start_file(&name, SimpleFileOptions::default())
1004 .map_err(|e| Error::Zip(e.to_string()))?;
1005 let header =
1006 crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
1007 write_profile(
1008 self,
1009 cov.profile,
1010 &mut zw,
1011 &WriteOptions::default().with_header(header),
1012 )?;
1013 written.push(name);
1014 }
1015 zw.finish().map_err(|e| Error::Zip(e.to_string()))?;
1016 Ok(written)
1017 }
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022 use super::{output_file_name, unique_name};
1023
1024 #[test]
1025 fn two_files_wanting_one_name_get_two_files() {
1026 // A merged common grid model assembled from `BE/EQ.xml` and `NL/EQ.xml`: only the
1027 // final component survives the traversal guard, so both headers ask for `EQ.xml`.
1028 let mut used = Vec::new();
1029 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ.xml");
1030 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_2.xml");
1031 assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_3.xml");
1032 assert_eq!(unique_name("SSH.xml".into(), &mut used), "SSH.xml");
1033 // A name without an extension still gets a distinct one.
1034 assert_eq!(unique_name("model".into(), &mut used), "model");
1035 assert_eq!(unique_name("model".into(), &mut used), "model_2");
1036 // And a collision with an already-suffixed name keeps counting rather than looping.
1037 assert_eq!(unique_name("EQ_2.xml".into(), &mut used), "EQ_2_2.xml");
1038 }
1039
1040 #[test]
1041 fn an_export_never_escapes_its_output_directory() {
1042 // A header's source is the name of the document it was read from, and for a zip
1043 // archive that name is chosen by whoever built the archive.
1044 assert_eq!(output_file_name("EQ.xml").as_deref(), Some("EQ.xml"));
1045 assert_eq!(
1046 output_file_name("model/EQ.xml").as_deref(),
1047 Some("EQ.xml"),
1048 "a nested archive entry keeps only its file name"
1049 );
1050 assert_eq!(
1051 output_file_name("../../../etc/cron.d/pwn").as_deref(),
1052 Some("pwn")
1053 );
1054 assert_eq!(output_file_name("/etc/passwd").as_deref(), Some("passwd"));
1055 for hostile in ["..", ".", "", "/", "..\\..\\evil.xml", "a\0b"] {
1056 assert_eq!(output_file_name(hostile), None, "{hostile:?}");
1057 }
1058 }
1059}