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
//! `cim` — a command line over the library, behind the `cli` feature.
//!
//! ```text
//! cargo install cim-kit --features cli
//! cim info     MicroGrid-BE/
//! cim validate MicroGrid-BE/ --rule CIM0007
//! cim rdf      MicroGrid-BE/ --out graphs/
//! cim diff     before/ after/ --out change_DIFF.xml
//! cim apply    before/ --change change_DIFF.xml --out updated/
//! ```
//!
//! A thin shell over the public API, with no dependencies of its own (argument parsing
//! included). Output goes through an explicit writer, not `println!`, which panics on a
//! closed pipe (`cim info big-model/ | head`).

use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use cim_kit::VINTAGES;
use cim_kit::prelude::*;
use cim_kit::rdf::{RdfOptions, Syntax};
use cim_kit::schema::{ProfileId, Schema};

const USAGE: &str = "\
cim — IEC CIM / CGMES grid models

usage: cim <command> [options] <input>...

commands:
  info       <input>...              what a model set contains
  validate   <input>...              structural checks; exits 1 on any error
  export     <input>... --out DIR    write the model back as CIM/XML
  rdf        <input>... --out DIR    export as RDF, one graph per profile with data
  diff       <base> <target>         compute a dm:DifferenceModel
  apply      <input>... --change F    apply a change set and write the result
  schema                             what the built-in vintages declare

an <input> is a CIM/XML file, a zip archive, or a directory holding either; several are
loaded into one model, which is what a CGMES profile set is.

options:
  -o, --out PATH    where to write (a directory, or a file for `diff`)
  --vintage KEY     which schema to read against (default: detected from the input)
  --profile KEY     restrict `rdf` and `diff` to one profile, e.g. SSH
  --assume-profile KEY
                    profile to attribute values to when a file declares none
  --rule CODE       show only this rule in `validate`, e.g. CIM0007
  --ntriples        write N-Triples rather than Turtle
  --merged          `rdf` writes one graph for the whole model, not one per profile
  --strict          fail on anything the schema does not define
  --max-input SIZE  stop reading after SIZE bytes, archives counted decompressed
                    (default 2GiB; e.g. 512MB, 8GiB, unlimited)
  --limit N         how many findings to list (default 20; 0 for all)
  -q, --quiet       less chatter
  -h, --help        this text
  -V, --version     the version of this binary

exit status: 0 clean, 1 the model has errors, 2 the command was wrong.
";

fn main() -> ExitCode {
    let stdout = io::stdout();
    let mut out = io::BufWriter::new(stdout.lock());
    let code = match run(&mut out) {
        Ok(code) => code,
        // A closed pipe is not a failure (`cim info … | head`).
        Err(Fail::Pipe) => ExitCode::SUCCESS,
        Err(Fail::Message(m)) => {
            let _ = writeln!(io::stderr(), "cim: {m}");
            ExitCode::from(2)
        }
    };
    match out.flush() {
        Ok(()) => code,
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS,
        Err(e) => {
            let _ = writeln!(io::stderr(), "cim: {e}");
            ExitCode::from(2)
        }
    }
}

fn run(out: &mut dyn Write) -> Result<ExitCode, Fail> {
    let args = Args::parse(std::env::args().skip(1))?;
    if args.version {
        writeln!(out, "cim {}", env!("CARGO_PKG_VERSION"))?;
        return Ok(ExitCode::SUCCESS);
    }
    if args.help {
        write!(out, "{USAGE}")?;
        return Ok(ExitCode::SUCCESS);
    }
    let Some(command) = args.command.as_deref() else {
        write!(out, "{USAGE}")?;
        return Ok(ExitCode::from(2));
    };

    match command {
        "schema" => schema_command(out, &args),
        "info" => info(out, &args),
        "validate" => validate(out, &args),
        "export" => export(out, &args),
        "rdf" => rdf(out, &args),
        "diff" => diff(out, &args),
        "apply" => apply(out, &args),
        other => Err(format!("unknown command {other:?}; `cim --help` lists them").into()),
    }
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

fn schema_command(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    if VINTAGES.is_empty() {
        return Err(no_vintage().into());
    }
    for schema in VINTAGES {
        writeln!(
            out,
            "{} — {} classes, {} attributes, {} enumerations, {} profiles",
            schema.vintage,
            schema.classes.len(),
            schema.attributes.len(),
            schema.enums.len(),
            schema.profiles.len()
        )?;
        if !args.quiet {
            for p in schema.profiles {
                writeln!(out, "  {:<6} {}", p.keyword, p.version_iri)?;
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

fn info(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let (ds, report) = args.load(schema)?;

    writeln!(out, "== files ==")?;
    for h in ds.headers() {
        let profiles: Vec<&str> = h
            .profiles
            .iter()
            .filter_map(|iri| schema.profile_by_iri(iri))
            .map(|p| schema.profile(p).keyword)
            .collect();
        let profiles = match profiles.is_empty() {
            true => "(no profile)".to_owned(),
            false => profiles.join("+"),
        };
        writeln!(
            out,
            "  {:<44} {profiles:<18} {}",
            h.source.as_deref().unwrap_or("(unnamed)"),
            h.scenario_time.as_deref().unwrap_or("-")
        )?;
    }

    writeln!(out, "\n== model ==")?;
    writeln!(out, "  {:<20} {}", "objects", ds.len())?;
    writeln!(
        out,
        "  {:<20} {}",
        "values",
        ds.iter().map(|(_, o)| o.len()).sum::<usize>()
    )?;
    // Looked up by local name, so this works on either vintage's namespace.
    for name in [
        "Substation",
        "ACLineSegment",
        "PowerTransformer",
        "SynchronousMachine",
        "EnergyConsumer",
        "Terminal",
    ] {
        if let Some(class) = schema.class_by_name(name) {
            writeln!(out, "  {name:<20} {}", ds.count_class(class))?;
        }
    }

    writeln!(out, "\n== profile coverage ==")?;
    for cov in cim_kit::validate::profile_coverage(&ds) {
        if cov.objects == 0 {
            continue;
        }
        writeln!(
            out,
            "  {:<6} {:>8} objects {:>10} values",
            cov.keyword, cov.objects, cov.attributes
        )?;
    }

    let mut all = report;
    all.extend(ds.validate());
    print_report(out, &all, args.limit, "diagnostics")?;
    Ok(exit_on_errors(&all))
}

fn validate(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let (ds, report) = args.load(schema)?;
    let mut all = report;
    all.extend(ds.validate_with(&cim_kit::ValidateOptions::thorough()));

    if let Some(code) = &args.rule {
        let wanted = *cim_kit::Rule::ALL
            .iter()
            .find(|r| r.code().eq_ignore_ascii_case(code))
            .ok_or_else(|| format!("no such rule {code:?}; `cim validate` lists the codes"))?;
        all.diagnostics.retain(|d| d.rule == wanted);
    }

    print_report(out, &all, args.limit, "findings")?;
    Ok(exit_on_errors(&all))
}

fn export(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let dir = args.out_dir()?;
    let (ds, report) = args.load(schema)?;
    let mut saved = ds
        .save_as_loaded(&dir)
        .map_err(|e| format!("writing to {}: {e}", dir.display()))?;

    // An input that declared no profile has no file set to reproduce: write one file per
    // profile instead, and say so on stderr.
    if saved.unwritten > 0 && saved.written.is_empty() && !ds.is_empty() {
        let _ = writeln!(
            io::stderr(),
            "note: no input file declares a profile, so there is no file set to reproduce; \
             writing one file per profile instead (--assume-profile names one explicitly)"
        );
        let stem = args
            .inputs
            .first()
            .and_then(|p| p.file_stem())
            .map_or_else(|| "model".to_owned(), |s| s.to_string_lossy().into_owned());
        let written = ds
            .save_all_profiles(&dir, &stem)
            .map_err(|e| format!("writing to {}: {e}", dir.display()))?;
        saved = cim_kit::SaveReport {
            written,
            ..Default::default()
        };
    }

    // `--quiet` suppresses the file list, as in `rdf`; skipped files still go to stderr.
    if !args.quiet {
        for p in &saved.written {
            writeln!(out, "{}", p.display())?;
        }
    }
    for s in &saved.skipped {
        let _ = writeln!(io::stderr(), "skipped: {s}");
    }
    if saved.unwritten > 0 {
        let _ = writeln!(
            io::stderr(),
            "warning: {} object(s) belong to no exported file",
            saved.unwritten
        );
    }
    if saved.written.is_empty() && !ds.is_empty() {
        return Err("nothing was written".to_owned().into());
    }
    Ok(exit_on_errors(&report))
}

fn rdf(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let dir = args.out_dir()?;
    let (ds, report) = args.load(schema)?;
    let syntax = if args.ntriples {
        Syntax::NTriples
    } else {
        Syntax::Turtle
    };
    let extension = if args.ntriples { "nt" } else { "ttl" };

    // One graph per profile by default, since ENTSO-E's shapes are per profile; `--merged`
    // writes the whole model as one. Named profiles together form a *single* graph.
    let graphs: Vec<(String, cim_kit::ProfileMask)> = if args.merged {
        vec![("model".to_owned(), 0)]
    } else if !args.profile.is_empty() {
        vec![(args.profile_label(schema)?, args.profile_mask(schema)?)]
    } else {
        (0..schema.profiles.len())
            .map(|i| {
                let p = ProfileId(i as u16);
                (schema.profile(p).keyword.to_owned(), p.mask())
            })
            .collect()
    };

    std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
    let mut empty: Vec<&str> = Vec::new();
    for (name, mask) in &graphs {
        let (name, mask) = (name.as_str(), *mask);
        // No file for a profile without data (headers alone would pass as an export);
        // `--merged` is exempt.
        if mask != 0 && !cim_kit::rdf::has_content(&ds, mask) {
            empty.push(name);
            continue;
        }
        let path = dir.join(format!("{name}.{extension}"));
        let file = std::fs::File::create(&path).map_err(|e| format!("{}: {e}", path.display()))?;
        cim_kit::rdf::write(
            &ds,
            io::BufWriter::with_capacity(1 << 16, file),
            &RdfOptions::new(syntax).profiles(mask),
        )
        .map_err(|e| format!("{}: {e}", path.display()))?;
        if !args.quiet {
            writeln!(out, "{}", path.display())?;
        }
    }
    if !empty.is_empty() {
        let _ = writeln!(
            io::stderr(),
            "no data for {} — no graph written",
            empty.join(", ")
        );
    }
    Ok(exit_on_errors(&report))
}

fn diff(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let [base, target] = match args.inputs.as_slice() {
        [a, b] => [a, b],
        _ => {
            return Err("diff takes exactly two inputs: <base> <target>"
                .to_owned()
                .into());
        }
    };
    let before = load_one(schema, base, args)?;
    let after = load_one(schema, target, args)?;

    let mut options = cim_kit::DiffOptions::default();
    if !args.profile.is_empty() {
        options = options.profiles(args.profile_mask(schema)?);
    }
    let change = before.difference_to(&after, &options);
    let _ = writeln!(
        io::stderr(),
        "{} added, {} removed, {} changed — {} statements to retract, {} to assert",
        change.added,
        change.removed,
        change.changed,
        change.model.reverse.len(),
        change.model.forward.len()
    );

    match &args.out {
        Some(path) => {
            let file =
                std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
            cim_kit::writer::write_difference(
                schema,
                &change.model,
                io::BufWriter::new(file),
                &Default::default(),
            )
            .map_err(|e| format!("{}: {e}", path.display()))?;
            writeln!(out, "{}", path.display())?;
        }
        // No `--out`: the change set goes to stdout, the summary to stderr.
        None => {
            cim_kit::writer::write_difference(schema, &change.model, &mut *out, &Default::default())
                .map_err(|e| e.to_string())?
        }
    }
    // Without `--out`, stdout is the document, so the report must go to stderr.
    if !change.report.is_empty() {
        let label = "not expressible as statements";
        match &args.out {
            Some(_) => print_report(out, &change.report, args.limit, label)?,
            None => {
                let mut err = io::stderr();
                let _ = print_report(&mut err, &change.report, args.limit, label);
            }
        }
    }
    Ok(ExitCode::SUCCESS)
}

/// Apply one or more change sets to a model and write the result.
///
/// The counterpart of `diff`. Change sets are named with `--change` rather than found
/// among the inputs: whether a file is model or change is the caller's to state.
fn apply(out: &mut dyn Write, args: &Args) -> Result<ExitCode, Fail> {
    let schema = args.schema()?;
    let dir = args.out_dir()?;
    if args.change.is_empty() {
        return Err("apply needs at least one --change FILE".to_owned().into());
    }
    let (mut ds, report) = args.load(schema)?;

    let mut applied = cim_kit::Report::default();
    for path in &args.change {
        let file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
        let name = path.file_name().map(|n| n.to_string_lossy().into_owned());
        let diff = cim_kit::reader::read_difference(
            schema,
            std::io::BufReader::new(file),
            name.as_deref(),
            &args.read_options(schema)?,
        )
        .map_err(|e| format!("{}: {}", path.display(), load_error(e)))?
        .ok_or_else(|| {
            format!(
                "{} holds no dm:DifferenceModel; `cim diff` writes one",
                path.display()
            )
        })?;
        // In the order given: each change set applies to the state the previous one left.
        applied.extend(ds.apply_difference(&diff));
    }

    // A refused change set left the model unchanged; do not write it out as a result.
    let refused = applied
        .iter()
        .any(|d| d.rule == cim_kit::Rule::UnsatisfiedDependency);
    if refused {
        print_report(&mut io::stderr(), &applied, args.limit, "applying")?;
        return Ok(ExitCode::from(1));
    }

    // Remove the empty shells a difference leaves for deleted objects.
    let pruned = ds.prune_empty();

    let saved = ds
        .save_as_loaded(&dir)
        .map_err(|e| format!("writing to {}: {e}", dir.display()))?;
    if !args.quiet {
        for p in &saved.written {
            writeln!(out, "{}", p.display())?;
        }
        if pruned > 0 {
            let _ = writeln!(
                io::stderr(),
                "pruned {pruned} object(s) the change left empty"
            );
        }
    }
    print_report(&mut io::stderr(), &applied, args.limit, "applying")?;
    let mut all = report;
    all.extend(applied);
    Ok(exit_on_errors(&all))
}

// ---------------------------------------------------------------------------
// Shared plumbing
// ---------------------------------------------------------------------------

/// A command either failed with something to say, or was told to stop writing.
enum Fail {
    Message(String),
    Pipe,
}

impl From<String> for Fail {
    fn from(m: String) -> Fail {
        Fail::Message(m)
    }
}

impl From<io::Error> for Fail {
    fn from(e: io::Error) -> Fail {
        match e.kind() {
            io::ErrorKind::BrokenPipe => Fail::Pipe,
            _ => Fail::Message(e.to_string()),
        }
    }
}

/// Resolve a profile keyword, naming the ones that exist when it is not one.
fn profile_by_keyword(schema: &'static Schema, key: &str) -> Result<ProfileId, String> {
    schema.profile_by_keyword(key).ok_or_else(|| {
        let known: Vec<&str> = schema.profiles.iter().map(|p| p.keyword).collect();
        format!("no profile {key:?} in {}; it has {known:?}", schema.vintage)
    })
}

fn no_vintage() -> String {
    "this build has no CIM vintage compiled in; rebuild with --features cgmes3".to_owned()
}

/// A load error as the person at the terminal needs it.
///
/// A spent budget suggests a `--max-input` value instead of the library's remedy.
fn load_error(e: cim_kit::Error) -> String {
    match e {
        cim_kit::Error::InputTooLarge {
            limit,
            read,
            source,
        } => {
            let within = source
                .map(|s| format!(" while reading {s}"))
                .unwrap_or_default();
            format!(
                "input exceeds the {} input budget ({} read{within}); \
                 rerun with --max-input {}, or --max-input unlimited",
                flag_size(limit),
                flag_size(read),
                flag_size(limit.saturating_mul(4)),
            )
        }
        other => other.to_string(),
    }
}

const SIZE_UNITS: [(&str, u64); 9] = [
    ("tib", 1 << 40),
    ("gib", 1 << 30),
    ("mib", 1 << 20),
    ("kib", 1 << 10),
    ("tb", 1_000_000_000_000),
    ("gb", 1_000_000_000),
    ("mb", 1_000_000),
    ("kb", 1_000),
    ("b", 1),
];

/// `--max-input`'s argument: an integer with an optional unit, or `unlimited`.
///
/// Integers only: `1536MiB`, not `1.5GiB`.
fn parse_size(text: &str) -> Result<u64, String> {
    let t = text.trim().to_ascii_lowercase();
    if t == "unlimited" {
        return Ok(0);
    }
    let digits = t.len() - t.trim_start_matches(|c: char| c.is_ascii_digit()).len();
    let (number, unit) = t.split_at(digits);
    let scale = match unit.trim() {
        "" => Some(1),
        u => SIZE_UNITS
            .iter()
            .find(|(name, _)| *name == u)
            .map(|(_, s)| *s),
    };
    number
        .parse::<u64>()
        .ok()
        .zip(scale)
        .and_then(|(n, s)| n.checked_mul(s))
        .ok_or_else(|| {
            format!(
                "--max-input takes a size such as 512MB, 8GiB or 1048576 (units B, KB, MB, GB, \
                 TB, KiB, MiB, GiB, TiB), or `unlimited`; not {text:?}"
            )
        })
}

/// A byte count in the form `--max-input` accepts, so it can be pasted back.
fn flag_size(n: u64) -> String {
    SIZE_UNITS[..4]
        .iter()
        .find(|(_, s)| n >= *s && n.is_multiple_of(*s))
        .map_or_else(
            || format!("{n}B"),
            |(name, s)| {
                let unit = format!("{}iB", name[..1].to_ascii_uppercase());
                format!("{}{unit}", n / s)
            },
        )
}

fn load_one(schema: &'static Schema, input: &Path, args: &Args) -> Result<Dataset, String> {
    let files = cim_kit::instance_files(input);
    if files.is_empty() {
        return Err(format!("no CIM inputs under {}", input.display()));
    }
    let mut ds = Dataset::new(schema);
    ds.load_files(&files, &args.read_options(schema)?)
        .map_err(|e| format!("{}: {}", input.display(), load_error(e)))?;
    Ok(ds)
}

fn print_report(
    out: &mut dyn Write,
    report: &cim_kit::Report,
    limit: usize,
    label: &str,
) -> Result<(), Fail> {
    writeln!(out, "\n== {label} ==")?;
    if report.is_empty() {
        writeln!(out, "  none")?;
        return Ok(());
    }
    for (rule, n) in report.summary() {
        writeln!(out, "  {rule}  {n:>7}")?;
    }
    writeln!(out)?;
    let shown = if limit == 0 { report.len() } else { limit };
    for d in report.iter().take(shown) {
        writeln!(out, "  {d}")?;
    }
    if report.len() > shown {
        writeln!(out, "  … {} more (--limit 0 for all)", report.len() - shown)?;
    }
    Ok(())
}

fn exit_on_errors(report: &cim_kit::Report) -> ExitCode {
    if report.has_errors() {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

#[derive(Default)]
struct Args {
    command: Option<String>,
    inputs: Vec<PathBuf>,
    out: Option<PathBuf>,
    vintage: Option<String>,
    profile: Vec<String>,
    assume_profile: Option<String>,
    change: Vec<PathBuf>,
    rule: Option<String>,
    ntriples: bool,
    merged: bool,
    strict: bool,
    quiet: bool,
    help: bool,
    version: bool,
    limit: usize,
    max_input: Option<u64>,
}

impl Args {
    fn parse(raw: impl Iterator<Item = String>) -> Result<Args, String> {
        fn value(raw: &mut impl Iterator<Item = String>, flag: &str) -> Result<String, String> {
            raw.next().ok_or_else(|| format!("{flag} needs a value"))
        }

        let mut args = Args {
            limit: 20,
            ..Default::default()
        };
        let mut raw = raw;
        while let Some(a) = raw.next() {
            match a.as_str() {
                "-h" | "--help" => args.help = true,
                "-V" | "--version" => args.version = true,
                "-q" | "--quiet" => args.quiet = true,
                "--strict" => args.strict = true,
                "--ntriples" => args.ntriples = true,
                "--merged" => args.merged = true,
                "-o" | "--out" => args.out = Some(PathBuf::from(value(&mut raw, "--out")?)),
                "--vintage" => args.vintage = Some(value(&mut raw, "--vintage")?),
                "--profile" => args.profile.push(value(&mut raw, "--profile")?),
                "--change" => args
                    .change
                    .push(PathBuf::from(value(&mut raw, "--change")?)),
                "--assume-profile" => {
                    args.assume_profile = Some(value(&mut raw, "--assume-profile")?)
                }
                "--rule" => args.rule = Some(value(&mut raw, "--rule")?),
                "--max-input" => {
                    args.max_input = Some(parse_size(&value(&mut raw, "--max-input")?)?);
                }
                "--limit" => {
                    let v = value(&mut raw, "--limit")?;
                    args.limit = v
                        .parse()
                        .map_err(|_| format!("--limit takes a number, not {v:?}"))?;
                }
                // Reject any unknown flag, short ones too, or it would be taken for an
                // input path and silently ignored. A bare `-` is kept for a future stdin.
                other if other.starts_with('-') && other != "-" => {
                    return Err(format!("unknown option {other:?}"));
                }
                _ if args.command.is_none() => args.command = Some(a),
                _ => args.inputs.push(PathBuf::from(a)),
            }
        }
        Ok(args)
    }

    /// Which schema to read against: what `--vintage` says, or what the files say.
    ///
    /// Detected by default, since the documents declare it.
    fn schema(&self) -> Result<&'static Schema, String> {
        if let Some(key) = &self.vintage {
            return VINTAGES
                .iter()
                .find(|s| s.vintage.eq_ignore_ascii_case(key))
                .copied()
                .ok_or_else(|| {
                    let known: Vec<&str> = VINTAGES.iter().map(|s| s.vintage).collect();
                    format!("no vintage {key:?} in this build; it has {known:?}")
                });
        }
        // Every input until one answers, not just the first.
        let files: Vec<PathBuf> = self
            .inputs
            .iter()
            .flat_map(cim_kit::instance_files)
            .collect();
        if let Some(schema) = cim_kit::load::detect_vintage(&files) {
            return Ok(schema);
        }
        VINTAGES.first().copied().ok_or_else(no_vintage)
    }

    /// The profiles named with `--profile`, as one mask.
    ///
    /// A set, because one file may serve several (`--profile EQ --profile OP --profile SC`).
    fn profile_mask(&self, schema: &'static Schema) -> Result<cim_kit::ProfileMask, String> {
        let mut mask = 0;
        for key in &self.profile {
            mask |= profile_by_keyword(schema, key)?.mask();
        }
        Ok(mask)
    }

    /// The keywords named with `--profile`, joined as a file name.
    fn profile_label(&self, schema: &'static Schema) -> Result<String, String> {
        let mut parts = Vec::new();
        for key in &self.profile {
            parts.push(schema.profile(profile_by_keyword(schema, key)?).keyword);
        }
        Ok(parts.join("_"))
    }

    fn read_options(&self, schema: &'static Schema) -> Result<ReadOptions, String> {
        let mut o = if self.strict {
            ReadOptions::strict()
        } else {
            ReadOptions::lenient()
        };
        // For files with no `md:FullModel`, which otherwise belong to no profile.
        if let Some(keyword) = &self.assume_profile {
            o.assume_profile = Some(profile_by_keyword(schema, keyword)?);
        }
        if let Some(max) = self.max_input {
            o.max_input_bytes = max;
        }
        Ok(o)
    }

    fn out_dir(&self) -> Result<PathBuf, String> {
        self.out
            .clone()
            .ok_or_else(|| "this command needs --out DIR".to_owned())
    }

    /// Load every input into one dataset.
    fn load(&self, schema: &'static Schema) -> Result<(Dataset, cim_kit::Report), String> {
        if self.inputs.is_empty() {
            return Err("no inputs given; `cim --help` shows the usage".to_owned());
        }
        let files: Vec<PathBuf> = self
            .inputs
            .iter()
            .flat_map(cim_kit::instance_files)
            .collect();
        if files.is_empty() {
            return Err("no CIM/XML or zip inputs found".to_owned());
        }
        let mut ds = Dataset::new(schema);
        let report = ds
            .load_files(&files, &self.read_options(schema)?)
            .map_err(load_error)?;
        Ok((ds, report.report))
    }
}