cim-kit 0.4.1

IEC CIM/CGMES for power systems: CIM/XML I/O that reproduces the file set, profile-aware validation, typed RDF export
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
//! Loading and saving whole models.
//!
//! A CGMES model is a set of profile files; this module loads them into one dataset,
//! applies difference models, and exports per profile or per source file.

use std::fs::File;
use std::io::{BufReader, BufWriter, Write};
use std::path::{Path, PathBuf};

use crate::dataset::Dataset;
use crate::error::{Diagnostic, Report, Result, Rule};
use crate::header::{DifferenceModel, ModelHeader, ModelKind, Statement, StatementValue};
use crate::mrid::Mrid;
use crate::object::Object;
use crate::reader::{Budget, ReadOptions, Strictness, read_header, read_into_within};
use crate::schema::{AttrKind, Primitive, ProfileId, Schema};
use crate::value::Value;
use crate::writer::{WriteOptions, write_profile};

/// Outcome of loading one or more files.
#[derive(Debug, Default)]
pub struct LoadReport {
    pub report: Report,
    /// Files loaded, in order, with the header each carried.
    pub files: Vec<(PathBuf, Option<ModelHeader>)>,
    /// Files that could not be read, each also reported as `CIM0022`.
    ///
    /// Non-empty means the dataset lacks whatever those files held.
    pub failed: Vec<PathBuf>,
    pub objects_read: usize,
}

impl LoadReport {
    pub fn has_errors(&self) -> bool {
        self.report.has_errors()
    }
}

impl Dataset {
    /// Load a set of instance files into a new dataset.
    ///
    /// Files may be given in any order: objects are merged by mRID, so an SSH file read
    /// before its EQ file produces the same result.
    pub fn load<I, P>(schema: &'static Schema, paths: I) -> Result<Dataset>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let mut ds = Dataset::new(schema);
        ds.load_files(paths, &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Load files into an existing dataset.
    ///
    /// All files and archive entries share one input budget
    /// ([`ReadOptions::max_input_bytes`]).
    ///
    /// # Errors
    ///
    /// [`Error::InputTooLarge`](crate::Error::InputTooLarge) under either strictness once
    /// the budget is spent; the dataset is then partial and must be discarded. Under
    /// [`Strictness::Strict`], the first file that cannot be read. Otherwise an unreadable
    /// file is reported as `CIM0022` and listed in [`LoadReport::failed`].
    pub fn load_files<I, P>(&mut self, paths: I, options: &ReadOptions) -> Result<LoadReport>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let budget = Budget::new(options);
        let mut out = LoadReport::default();
        for path in paths {
            let path = path.as_ref();
            // Lenient: one unreadable file is recorded and named, and the rest still load.
            match self.load_file_within(path, options, &budget) {
                Ok(one) => {
                    out.report.extend(one.report);
                    out.files.extend(one.files);
                    out.objects_read += one.objects_read;
                }
                // Except the budget: a partial model must not pass as a success.
                Err(e) if options.strictness == Strictness::Lenient && !budget.tripped() => {
                    out.failed.push(path.to_path_buf());
                    out.report.push(
                        Diagnostic::error(Rule::UnreadableFile, e.to_string()).with_source(
                            path.file_name()
                                .map(|n| n.to_string_lossy().into_owned())
                                .unwrap_or_else(|| path.display().to_string()),
                        ),
                    );
                }
                Err(e) => return Err(e),
            }
        }
        self.shrink_to_fit();
        Ok(out)
    }

    /// Load one instance file, or every instance file inside a zip archive.
    pub fn load_file(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
        self.load_file_within(path, options, &Budget::new(options))
    }

    fn load_file_within(
        &mut self,
        path: &Path,
        options: &ReadOptions,
        budget: &Budget,
    ) -> Result<LoadReport> {
        if path
            .extension()
            .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
        {
            #[cfg(feature = "zip")]
            {
                return self.load_zip_within(path, options, budget);
            }
            #[cfg(not(feature = "zip"))]
            {
                return Err(crate::error::Error::NotCimXml(format!(
                    "{} is a zip archive; enable the `zip` feature to read it",
                    path.display()
                )));
            }
        }

        let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
        let file = File::open(path)?;
        let outcome = read_into_within(
            self,
            BufReader::with_capacity(1 << 16, file),
            name.as_deref(),
            options,
            budget,
        )?;

        let mut report = LoadReport {
            report: outcome.report,
            objects_read: outcome.objects_read,
            files: vec![(path.to_path_buf(), outcome.header.clone())],
            failed: Vec::new(),
        };
        // The reader registers the header itself, so objects record their source file.
        if outcome.header.is_none() {
            report.report.push(
                Diagnostic::warning(Rule::MalformedHeader, "file has no md:FullModel header")
                    .with_source(name.unwrap_or_default()),
            );
        }
        Ok(report)
    }

    /// Load every instance file under a directory, in sorted order.
    ///
    /// Model sets usually ship as directories; to name files individually use
    /// [`Dataset::load`].
    pub fn load_dir(schema: &'static Schema, dir: impl AsRef<Path>) -> Result<Dataset> {
        let mut ds = Dataset::new(schema);
        ds.load_files(instance_files(dir.as_ref()), &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Load a model set, reading its vintage out of the files themselves.
    ///
    /// `path` is a directory, a zip archive or a single instance file; the schema comes
    /// from the namespace declarations (see [`detect_vintage`]). Use [`Dataset::load_dir`]
    /// or [`Dataset::load`] to state the vintage explicitly.
    ///
    /// # Errors
    ///
    /// [`Error::UnknownVintage`](crate::Error::UnknownVintage) when no file under `path`
    /// declares a vocabulary this build has a feature for, including when `path` holds no
    /// CIM input at all.
    ///
    /// ```no_run
    /// # fn main() -> cim_kit::Result<()> {
    /// let grid = cim_kit::Dataset::open("MicroGrid-BE")?;
    /// println!("{} objects", grid.len());
    /// # Ok(()) }
    /// ```
    pub fn open(path: impl AsRef<Path>) -> Result<Dataset> {
        let path = path.as_ref();
        let files = instance_files(path);
        let schema = detect_vintage(&files).ok_or_else(|| crate::error::Error::UnknownVintage {
            path: path.display().to_string(),
            known: crate::VINTAGES.iter().map(|s| s.vintage).collect(),
        })?;
        let mut ds = Dataset::new(schema);
        ds.load_files(&files, &ReadOptions::lenient())?;
        Ok(ds)
    }

    /// Read only the headers of a set of files, without loading their objects.
    ///
    /// Useful for deciding what to load: headers declare profiles and dependencies.
    pub fn peek_headers<I, P>(
        schema: &'static Schema,
        paths: I,
    ) -> Result<Vec<(PathBuf, Option<ModelHeader>)>>
    where
        I: IntoIterator<Item = P>,
        P: AsRef<Path>,
    {
        let mut out = Vec::new();
        for path in paths {
            let path = path.as_ref();
            let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
            let file = File::open(path)?;
            let header = read_header(schema, BufReader::new(file), name.as_deref())?;
            out.push((path.to_path_buf(), header));
        }
        Ok(out)
    }

    /// Apply a difference model (IEC 61970-552): check it applies to this model, remove
    /// reverse statements, then assert forward statements.
    ///
    /// Refused, with one `CIM0014` error and the dataset unchanged, when a model named in
    /// `md:Model.Supersedes` is neither loaded nor an earlier applied change set (compared
    /// as identifiers), or when a `dm:preconditions` statement does not hold. Nothing is
    /// checked if the dataset has no header identifiers or the change set names no base;
    /// to skip the check, clear `diff.header.supersedes` or `diff.preconditions`.
    ///
    /// Otherwise, statements naming unknown classes or properties are reported and
    /// skipped, and a retraction that does not hold is a warning, not a refusal.
    pub fn apply_difference(&mut self, diff: &DifferenceModel) -> Report {
        let schema = self.schema();
        let mut report = Report::default();
        if let Some(refusal) = self.refusal(diff) {
            report.push(refusal);
            return report;
        }
        // Asserted values belong to the profiles the change set's header declares, as if
        // read from an instance file.
        let profiles = diff
            .header
            .profiles
            .iter()
            .filter_map(|iri| schema.profile_by_iri(iri))
            .fold(0, |acc, p| acc | p.mask());

        // Retract, re-type, assert: reverse statements describe the object as it was,
        // forward ones what it becomes (e.g. a `LinearShuntCompensator` turned
        // `NonlinearShuntCompensator`, then given attributes only the new class has).
        for s in &diff.reverse {
            self.apply_statement(s, false, profiles, &mut report);
        }
        self.apply_reclassifications(diff, &mut report);
        for s in &diff.forward {
            self.apply_statement(s, true, profiles, &mut report);
        }
        self.record_applied(diff.header.id.clone(), &diff.header.supersedes);
        report
    }

    /// Why `diff` must not be applied to this dataset, if it must not.
    fn refusal(&self, diff: &DifferenceModel) -> Option<Diagnostic> {
        let loaded: Vec<&Mrid> = self.model_ids().collect();
        if !loaded.is_empty()
            && let Some(missing) = diff
                .header
                .supersedes
                .iter()
                .find(|id| !loaded.contains(id))
        {
            let mut held: Vec<String> = loaded.iter().map(|m| m.canonical()).collect();
            held.sort();
            return Some(Diagnostic::error(
                Rule::UnsatisfiedDependency,
                format!(
                    "change set not applied: it supersedes model {}, which is not loaded \
                     (this dataset holds {}); it was computed against another model",
                    missing.canonical(),
                    held.join(", ")
                ),
            ));
        }
        for s in &diff.preconditions {
            let mut scratch = Report::default();
            let holds = self
                .statement_value(s, &mut scratch)
                .is_some_and(|(attr, value)| {
                    self.find(&s.subject)
                        .and_then(|id| self.get(id))
                        .is_some_and(|o| o.values().any(|(a, v)| a == attr && *v == value))
                });
            if !holds {
                return Some(
                    Diagnostic::error(
                        Rule::UnsatisfiedDependency,
                        format!(
                            "change set not applied: its precondition {} {} does not hold",
                            s.predicate,
                            match &s.value {
                                StatementValue::Resource(r) => r.as_str(),
                                StatementValue::Literal(t) => t.as_str(),
                            }
                        ),
                    )
                    .with_object(s.subject.clone()),
                );
            }
        }
        None
    }

    /// Apply class changes named by a difference's forward statements.
    ///
    /// IEC 61970-552 treats an object's type as a statement, so a difference may replace
    /// an object's class under the same identifier.
    fn apply_reclassifications(&mut self, diff: &DifferenceModel, report: &mut Report) {
        let schema = self.schema();
        let mut seen: Vec<Mrid> = Vec::new();

        for s in &diff.forward {
            let Some(qname) = &s.class else { continue };
            if seen.contains(&s.subject) {
                continue;
            }
            seen.push(s.subject.clone());

            let Some(target) = schema.find_class(&qname.ns, &qname.local) else {
                report.push(
                    Diagnostic::warning(
                        Rule::UnknownClass,
                        format!("difference names unknown class {}", qname.local),
                    )
                    .with_object(s.subject.clone()),
                );
                continue;
            };
            let Some(id) = self.find(&s.subject) else {
                continue;
            };
            let Some(current) = self.get(id).map(|o| o.class()) else {
                continue;
            };
            if current == target {
                continue;
            }
            // Narrowing to a subclass is a refinement; anything else is reported.
            if !schema.is_a(target, current) {
                report.push(
                    Diagnostic::info(
                        Rule::Structure,
                        format!(
                            "difference reclassifies {} from {} to {}",
                            s.subject.canonical(),
                            schema.class(current).name,
                            schema.class(target).name
                        ),
                    )
                    .with_object(s.subject.clone())
                    .with_class(schema.class(target).name),
                );
            }
            // Attributes the new class lacks are shed; report each one.
            for slot in self.reclassify(id, target) {
                let def = schema.attr(slot.attr);
                report.push(
                    Diagnostic::warning(
                        Rule::Structure,
                        format!(
                            "{} was dropped: {} does not have it, and the difference \
                             reclassified this object",
                            def.name,
                            schema.class(target).name
                        ),
                    )
                    .with_class(schema.class(target).name)
                    .with_object(s.subject.clone())
                    .with_attribute(def.name),
                );
            }
        }
    }

    /// The attribute and value a difference statement names, resolved against the schema
    /// — one implementation for applying a statement and for checking a precondition.
    fn statement_value(
        &self,
        s: &Statement,
        report: &mut Report,
    ) -> Option<(crate::schema::AttrId, Value)> {
        let schema = self.schema();
        let Some(attr) = schema.find_attr(&s.predicate_ns, &s.predicate) else {
            report.push(
                Diagnostic::warning(
                    Rule::UnknownAttribute,
                    format!(
                        "difference statement names unknown property {}",
                        s.predicate
                    ),
                )
                .with_object(s.subject.clone()),
            );
            return None;
        };
        let def = schema.attr(attr);

        let value = match &s.value {
            StatementValue::Resource(iri) => match def.kind {
                AttrKind::Enumeration(_) => {
                    let Some((ns, local)) = iri.rsplit_once('#') else {
                        report.push(
                            Diagnostic::error(
                                Rule::InvalidValue,
                                format!("enumeration value {iri} is not an IRI"),
                            )
                            .with_attribute(def.name),
                        );
                        return None;
                    };
                    match schema
                        .find_enum_value(&format!("{ns}#"), local)
                        // As in the reader: a misplaced namespace is recoverable.
                        .or_else(|| schema.find_enum_value_any_ns(local))
                    {
                        Some(v) => Value::Enum(v),
                        None => {
                            report.push(
                                Diagnostic::error(
                                    Rule::InvalidValue,
                                    format!("unknown enumeration literal {iri}"),
                                )
                                .with_attribute(def.name)
                                .with_object(s.subject.clone()),
                            );
                            return None;
                        }
                    }
                }
                _ => Value::Reference(Mrid::parse(iri)),
            },
            StatementValue::Literal(text) => {
                let prim = match def.kind {
                    AttrKind::Primitive(p) => p,
                    AttrKind::Datatype(d) => schema.datatype(d).value,
                    _ => Primitive::String,
                };
                match Value::parse_primitive(prim, text) {
                    Ok(v) => v,
                    Err(e) => {
                        report.push(
                            Diagnostic::error(Rule::InvalidValue, e.to_string())
                                .with_attribute(def.name)
                                .with_object(s.subject.clone()),
                        );
                        return None;
                    }
                }
            }
        };
        Some((attr, value))
    }

    fn apply_statement(
        &mut self,
        s: &Statement,
        assert: bool,
        profiles: crate::schema::ProfileMask,
        report: &mut Report,
    ) {
        let schema = self.schema();
        let Some((attr, value)) = self.statement_value(s, report) else {
            return;
        };
        let def = schema.attr(attr);

        // Asserting into an absent object creates it, which a forward difference may
        // legitimately do when it introduces a new object.
        let id = match self.find(&s.subject) {
            Some(id) => id,
            None if assert => {
                let class = s
                    .class
                    .as_ref()
                    .and_then(|c| schema.find_class(&c.ns, &c.local))
                    .unwrap_or(def.owner);
                self.insert(Object::new(class, s.subject.clone()))
            }
            None => {
                report.push(
                    Diagnostic::warning(
                        Rule::DanglingReference,
                        format!(
                            "difference removes from {} which is not in the dataset",
                            s.subject.canonical()
                        ),
                    )
                    .with_attribute(def.name),
                );
                return;
            }
        };

        // As in the reader: never assert an attribute the object's class lacks, since
        // writer and validation would never see it. Retractions are exempt, because
        // retracting such a value is how a change set removes it.
        let class = self.get(id).map(|o| o.class());
        if assert
            && let Some(class) = class
            && !schema.is_a(class, def.owner)
        {
            report.push(
                Diagnostic::warning(
                    Rule::UnknownAttribute,
                    format!(
                        "difference statement sets {} on {}, which does not have it",
                        def.name,
                        schema.class(class).name
                    ),
                )
                .with_class(schema.class(class).name)
                .with_object(s.subject.clone())
                .with_attribute(def.name),
            );
            return;
        }

        let Some(obj) = self.get_mut(id) else { return };
        if assert {
            if def.mult.is_many() {
                obj.push_in(profiles, attr, value);
            } else {
                obj.set_in(profiles, attr, value);
            }
            obj.mark_profile(profiles);
        } else if !obj.remove_value(attr, &value) {
            report.push(
                Diagnostic::info(
                    Rule::Structure,
                    format!("difference removes {} which was not present", def.name),
                )
                .with_object(s.subject.clone()),
            );
        }
    }

    /// Write one profile of this dataset to a file.
    pub fn save_profile(
        &self,
        path: &Path,
        profile: ProfileId,
        header: Option<ModelHeader>,
    ) -> Result<()> {
        // A caller's header wins; without one the writer derives a conforming one.
        let options = match header {
            Some(h) => WriteOptions::default().with_header(h),
            None => WriteOptions::default(),
        };
        let file = File::create(path)?;
        write_profile(
            self,
            profile,
            BufWriter::with_capacity(1 << 16, file),
            &options,
        )
    }

    /// Write every profile the dataset carries data for, into `dir`, one file each.
    ///
    /// Files are named `<stem>_<KEYWORD>.xml`. Use [`Dataset::save_as_loaded`] instead
    /// when the goal is to reproduce the file set the model was read from.
    pub fn save_all_profiles(&self, dir: &Path, stem: &str) -> Result<Vec<PathBuf>> {
        std::fs::create_dir_all(dir)?;
        let mut written = Vec::new();
        // Once per export, not per profile: it walks the whole model.
        let content = self.content_id();
        for cov in crate::validate::profile_coverage(self) {
            if cov.objects == 0 {
                continue;
            }
            let path = dir.join(format!("{stem}_{}.xml", cov.keyword));
            let header =
                crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
            self.save_profile(&path, cov.profile, Some(header))?;
            written.push(path);
        }
        Ok(written)
    }

    /// Write the model back out as the file set it was read from.
    ///
    /// One output file per loaded header, carrying that header, its profiles and the
    /// objects read from that file ([`Dataset::objects_from`]), so a merged model with two
    /// Equipment files writes two. Objects built programmatically go with the first header
    /// whose profiles can carry them.
    ///
    /// A header without a resolvable profile is skipped and named in
    /// [`SaveReport::skipped`]; objects only it held are counted in
    /// [`SaveReport::unwritten`]. [`Dataset::save_all_profiles`] always writes something.
    pub fn save_as_loaded(&self, dir: &Path) -> Result<SaveReport> {
        std::fs::create_dir_all(dir)?;
        let schema = self.schema();
        let mut out = SaveReport::default();

        // Objects built programmatically go with the first file that can carry them.
        let unsourced: Vec<crate::dataset::ObjectId> = self
            .iter()
            .filter(|(_, o)| !o.from_file())
            .map(|(id, _)| id)
            .collect();
        let mut unsourced_placed = false;
        let mut used_names: Vec<String> = Vec::new();
        // Which objects reached a file, for `SaveReport::unwritten`.
        let mut covered = vec![false; self.len()];
        let mark = |ids: &[crate::dataset::ObjectId], covered: &mut Vec<bool>| {
            for id in ids {
                if let Some(slot) = covered.get_mut(id.index()) {
                    *slot = true;
                }
            }
        };

        for (i, header) in self.headers().iter().enumerate() {
            let profiles = header
                .profiles
                .iter()
                .filter_map(|iri| schema.profile_by_iri(iri))
                .fold(0, |acc, p| acc | p.mask());
            if profiles == 0 {
                out.skipped.push(
                    header
                        .source
                        .clone()
                        .unwrap_or_else(|| format!("header {i}")),
                );
                continue;
            }

            // Reuse the source file name, made unique: only the final component is kept,
            // so `BE/EQ.xml` and `NL/EQ.xml` would otherwise collide.
            let name = unique_name(
                header
                    .source
                    .as_deref()
                    .and_then(output_file_name)
                    .unwrap_or_else(|| format!("model_{i}.xml")),
                &mut used_names,
            );
            let path = dir.join(&name);
            let file = File::create(&path)?;
            let sink = BufWriter::with_capacity(1 << 16, file);
            let options = WriteOptions {
                profiles,
                header: crate::writer::HeaderSource::Given(Box::new(header.clone())),
                ..Default::default()
            };

            if header.kind == ModelKind::Difference {
                // Match the statements to this header by identifier, else by source
                // document (a `dm:DifferenceModel` may lack `rdf:about`).
                let diff = self
                    .differences()
                    .iter()
                    .find(|d| d.header.id.is_some() && d.header.id == header.id)
                    .or_else(|| {
                        self.differences()
                            .iter()
                            .find(|d| d.header.source.is_some() && d.header.source == header.source)
                    });
                match diff {
                    Some(d) => crate::writer::write_difference(schema, d, sink, &options)?,
                    None => {
                        out.skipped
                            .push(format!("{name}: difference statements were not retained"));
                        continue;
                    }
                }
                out.written.push(path);
                continue;
            }

            // Everything the file carried, including property-less objects such as
            // `<cim:ConnectivityNode rdf:ID="_x"/>` in boundary sets (D55).
            let mut ids: Vec<_> = self.objects_from(i).collect();
            if !unsourced_placed && !unsourced.is_empty() {
                let before = ids.len();
                ids.extend(unsourced.iter().copied().filter(|&id| {
                    self.get(id)
                        .is_some_and(|o| crate::writer::object_has_content_in(schema, o, profiles))
                }));
                unsourced_placed = ids.len() > before;
            }

            mark(&ids, &mut covered);
            crate::writer::write_objects(self, ids.into_iter(), sink, &options)?;
            out.written.push(path);
        }

        out.unwritten = self
            .iter()
            .filter(|(id, _)| !covered.get(id.index()).copied().unwrap_or(false))
            .count();
        Ok(out)
    }
}

/// The schema vintage a set of inputs declares, taken from the first file that answers.
///
/// Files that cannot be read or are unrecognised are skipped, so one broken file does not
/// decide the vintage of the rest.
pub fn detect_vintage<I, P>(paths: I) -> Option<&'static Schema>
where
    I: IntoIterator<Item = P>,
    P: AsRef<Path>,
{
    paths.into_iter().find_map(|p| detect_file(p.as_ref()))
}

/// The schema vintage a file declares, or `None` if it cannot be read or is unrecognised.
///
/// A zip archive is opened for its first CIM/XML entry, since a model set often arrives as
/// one. Unreadable is not an error here: [`Dataset::open`] moves on to the next file.
pub fn detect_file(path: &Path) -> Option<&'static Schema> {
    #[cfg(feature = "zip")]
    if path
        .extension()
        .is_some_and(|e| e.eq_ignore_ascii_case("zip"))
    {
        let file = File::open(path).ok()?;
        let mut zip = zip::ZipArchive::new(BufReader::new(file)).ok()?;
        // Only looking for one readable document here; an undecodable name is reported
        // by the load that reads the archive.
        let mut names: Vec<String> = zip
            .file_names()
            .filter_map(|n| n.ok())
            .filter(|n| n.to_ascii_lowercase().ends_with(".xml"))
            .map(|n| n.into_owned())
            .collect();
        names.sort();
        let entry = zip.by_name(names.first()?).ok()?;
        return crate::reader::sniff(BufReader::new(entry)).ok().flatten();
    }
    let file = File::open(path).ok()?;
    crate::reader::sniff(BufReader::new(file)).ok().flatten()
}

/// Every CIM input under `path`, sorted so that a load is reproducible.
///
/// A plain file is returned as itself whatever its name; a directory is walked recursively
/// for `.xml` files, and `.zip` files when the `zip` feature is on.
pub fn instance_files(path: impl AsRef<Path>) -> Vec<PathBuf> {
    let path = path.as_ref();
    fn looks_like_input(path: &Path) -> bool {
        let Some(ext) = path.extension() else {
            return false;
        };
        ext.eq_ignore_ascii_case("xml")
            || (cfg!(feature = "zip") && ext.eq_ignore_ascii_case("zip"))
    }
    fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for e in entries.flatten() {
            let p = e.path();
            if p.is_dir() {
                walk(&p, out);
            } else if looks_like_input(&p) {
                out.push(p);
            }
        }
    }

    let mut out = Vec::new();
    if path.is_dir() {
        walk(path, &mut out);
        out.sort();
    } else if path.is_file() {
        out.push(path.to_path_buf());
    }
    out
}

/// Outcome of writing a model back to disk.
#[derive(Debug, Default)]
pub struct SaveReport {
    pub written: Vec<PathBuf>,
    /// Headers that declared no profile this schema recognises.
    pub skipped: Vec<String>,
    /// Objects no output file covers.
    ///
    /// Non-zero means the export is incomplete: those objects came from a file whose
    /// header declares no recognised profile (e.g. one with no `md:FullModel`).
    pub unwritten: usize,
}

/// The file name to write a header's model back to, confined to the output directory.
///
/// A zip entry name is chosen by the archive's author and may contain separators or `..`
/// (zip-slip), so only the final component is kept, and only when it is an ordinary name.
fn output_file_name(source: &str) -> Option<String> {
    let candidate = Path::new(source).file_name()?.to_str()?;
    let plain = !candidate.is_empty()
        && candidate != "."
        && candidate != ".."
        && !candidate.contains(['/', '\\', '\0']);
    plain.then(|| candidate.to_owned())
}

/// Give `name` a suffix if `used` already holds it, and record the result, so no output
/// file overwrites another.
fn unique_name(name: String, used: &mut Vec<String>) -> String {
    let mut candidate = name.clone();
    let (stem, ext) = match name.rsplit_once('.') {
        Some((s, e)) if !s.is_empty() => (s, format!(".{e}")),
        _ => (name.as_str(), String::new()),
    };
    let mut n = 1;
    while used.contains(&candidate) {
        n += 1;
        candidate = format!("{stem}_{n}{ext}");
    }
    used.push(candidate.clone());
    candidate
}

/// Write a dataset to any sink, as a single document.
pub fn write_to<W: Write>(dataset: &Dataset, out: W, options: &WriteOptions) -> Result<()> {
    crate::writer::write(dataset, out, options)
}

// ---------------------------------------------------------------------------
// Zip archives
// ---------------------------------------------------------------------------

#[cfg(feature = "zip")]
impl Dataset {
    /// Load every CIM/XML entry in a zip archive.
    ///
    /// Entries are read in name order and share one input budget.
    pub fn load_zip(&mut self, path: &Path, options: &ReadOptions) -> Result<LoadReport> {
        self.load_zip_within(path, options, &Budget::new(options))
    }

    fn load_zip_within(
        &mut self,
        path: &Path,
        options: &ReadOptions,
        budget: &Budget,
    ) -> Result<LoadReport> {
        use crate::error::Error;

        let file = File::open(path)?;
        let mut archive = zip::ZipArchive::new(BufReader::new(file))
            .map_err(|e| Error::Zip(format!("{}: {e}", path.display())))?;

        // Read entries in name order so a load is reproducible.
        let mut out = LoadReport::default();
        let mut names: Vec<String> = Vec::new();
        for name in archive.file_names() {
            match name {
                Ok(n) if n.to_ascii_lowercase().ends_with(".xml") => names.push(n.into_owned()),
                Ok(_) => {}
                // An undecodable entry name is not read; report it.
                Err(e) => out.report.push(
                    Diagnostic::error(
                        Rule::UnreadableFile,
                        format!("an entry name could not be decoded: {e}"),
                    )
                    .with_source(path.display().to_string()),
                ),
            }
        }
        names.sort();

        for name in names {
            let entry = archive
                .by_name(&name)
                .map_err(|e| Error::Zip(format!("{name}: {e}")))?;
            // Decompressed bytes are metered as parsed; the archive's size fields are not
            // trusted. An I/O failure inside an entry is reported as a zip error, named.
            let outcome = read_into_within(
                self,
                BufReader::with_capacity(1 << 16, entry),
                Some(&name),
                options,
                budget,
            )
            .map_err(|e| match e {
                Error::Io(io) => Error::Zip(format!("{}: {name}: {io}", path.display())),
                other => other,
            })?;
            out.report.extend(outcome.report);
            out.objects_read += outcome.objects_read;
            out.files
                .push((PathBuf::from(&name), outcome.header.clone()));
        }
        Ok(out)
    }

    /// Write every populated profile into one zip archive.
    pub fn save_zip(&self, path: &Path, stem: &str) -> Result<Vec<String>> {
        use crate::error::Error;
        use zip::write::SimpleFileOptions;

        let file = File::create(path)?;
        let mut zw = zip::ZipWriter::new(BufWriter::new(file));
        let mut written = Vec::new();
        // Once for the archive, not once per profile: see `save_all_profiles`.
        let content = self.content_id();

        for cov in crate::validate::profile_coverage(self) {
            if cov.objects == 0 {
                continue;
            }
            let name = format!("{stem}_{}.xml", cov.keyword);
            zw.start_file(&name, SimpleFileOptions::default())
                .map_err(|e| Error::Zip(e.to_string()))?;
            let header =
                crate::writer::derive_header_with(self.schema(), cov.profile.mask(), &content);
            write_profile(
                self,
                cov.profile,
                &mut zw,
                &WriteOptions::default().with_header(header),
            )?;
            written.push(name);
        }
        zw.finish().map_err(|e| Error::Zip(e.to_string()))?;
        Ok(written)
    }
}

#[cfg(test)]
mod tests {
    use super::{output_file_name, unique_name};

    #[test]
    fn two_files_wanting_one_name_get_two_files() {
        // A merged common grid model assembled from `BE/EQ.xml` and `NL/EQ.xml`: only the
        // final component survives the traversal guard, so both headers ask for `EQ.xml`.
        let mut used = Vec::new();
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ.xml");
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_2.xml");
        assert_eq!(unique_name("EQ.xml".into(), &mut used), "EQ_3.xml");
        assert_eq!(unique_name("SSH.xml".into(), &mut used), "SSH.xml");
        // A name without an extension still gets a distinct one.
        assert_eq!(unique_name("model".into(), &mut used), "model");
        assert_eq!(unique_name("model".into(), &mut used), "model_2");
        // And a collision with an already-suffixed name keeps counting rather than looping.
        assert_eq!(unique_name("EQ_2.xml".into(), &mut used), "EQ_2_2.xml");
    }

    #[test]
    fn an_export_never_escapes_its_output_directory() {
        // A header's source is the name of the document it was read from, and for a zip
        // archive that name is chosen by whoever built the archive.
        assert_eq!(output_file_name("EQ.xml").as_deref(), Some("EQ.xml"));
        assert_eq!(
            output_file_name("model/EQ.xml").as_deref(),
            Some("EQ.xml"),
            "a nested archive entry keeps only its file name"
        );
        assert_eq!(
            output_file_name("../../../etc/cron.d/pwn").as_deref(),
            Some("pwn")
        );
        assert_eq!(output_file_name("/etc/passwd").as_deref(), Some("passwd"));
        for hostile in ["..", ".", "", "/", "..\\..\\evil.xml", "a\0b"] {
            assert_eq!(output_file_name(hostile), None, "{hostile:?}");
        }
    }
}