cimoxide-cli 0.8.0

cimox: command-line tool to decode, validate, convert and query ENTSO-E CGMES data, and to convert MATPOWER and UCTE-DEF files to it
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
mod sarif;

use std::path::PathBuf;
use std::process;

/// Unwrap a `Result`, or print `"{context}: {error}"` to stderr and exit(1).
fn or_die<T, E: std::fmt::Display>(result: Result<T, E>, context: &str) -> T {
    result.unwrap_or_else(|e| {
        eprintln!("{context}: {e}");
        process::exit(1);
    })
}

fn usage() -> ! {
    eprintln!("Usage:");
    eprintln!("  cimox import [--json] <xml-files...>");
    eprintln!("  cimox convert <case.m | file.uct ...> [--out <dir/>] [--zip]");
    eprintln!(
        "                [--no-breakers] [--no-name-grouping] [--time <2026-01-01T00:00:00Z>]"
    );
    eprintln!("  cimox convert --to json <xml-files...> [--out <output.json>]");
    eprintln!("  cimox convert --to xml  <input.json>   [--out <output.xml>]");
    eprintln!("  cimox convert --to xml  <input.json>   --profile EQ,SSH [--out <dir/>]");
    eprintln!("  cimox validate [--profiles EQ,SSH,...] [--solved] [--not-solved]");
    eprintln!("                 [--common] [--quality] [--silence rule1,rule2]");
    eprintln!("                 [--format text|json|sarif] <xml-files...>");
    #[cfg(feature = "sparql")]
    {
        eprintln!("                 [--sparql | --sparql=both]  (with CIMOXIDE_PROFILES)");
        eprintln!("  cimox query  --query \"SELECT ...\" | --file <query.rq>");
        eprintln!("               [--format text|json|csv|tsv] <xml-files...>");
    }
    process::exit(1);
}

fn main() {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.is_empty() {
        usage();
    }
    if args[0] == "import" {
        cmd_import(&args[1..]);
        return;
    }
    if args[0] == "validate" {
        cmd_validate(&args[1..]);
        return;
    }
    if args[0] == "query" {
        #[cfg(feature = "sparql")]
        {
            cmd_query(&args[1..]);
            return;
        }
        #[cfg(not(feature = "sparql"))]
        {
            eprintln!("error: this build has no SPARQL support");
            eprintln!("hint: rebuild with `cargo build -p cimoxide-cli --features sparql`");
            process::exit(1);
        }
    }
    if args[0] != "convert" {
        usage();
    }

    let mut to_format: Option<String> = None;
    let mut out_path: Option<PathBuf> = None;
    let mut profile_str: Option<String> = None;
    let mut input_files: Vec<PathBuf> = Vec::new();
    let mut import = cimimport::Options::default();
    let mut zip = false;

    let mut i = 1usize;
    while i < args.len() {
        match args[i].as_str() {
            "--to" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --to requires an argument");
                    usage();
                }
                to_format = Some(args[i].clone());
            }
            "--out" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --out requires an argument");
                    usage();
                }
                out_path = Some(PathBuf::from(&args[i]));
            }
            "--profile" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --profile requires an argument");
                    usage();
                }
                profile_str = Some(args[i].clone());
            }
            "--zip" => zip = true,
            "--no-breakers" => import.breakers = false,
            "--no-name-grouping" => import.name_grouping = false,
            "--time" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --time requires an argument");
                    usage();
                }
                import.time = Some(args[i].clone());
            }
            arg if !arg.starts_with('-') => {
                input_files.push(PathBuf::from(arg));
            }
            unknown => {
                eprintln!("error: unknown flag: {unknown}");
                usage();
            }
        }
        i += 1;
    }

    // MATPOWER and UCTE-DEF files convert to CGMES, whatever else is asked.
    let convertible = |p: &PathBuf| cimimport::convertible(&p.to_string_lossy());
    if !input_files.is_empty() && input_files.iter().all(convertible) {
        if to_format.as_deref().is_some_and(|f| f != "cgmes") || profile_str.is_some() {
            eprintln!(
                "error: MATPOWER and UCTE-DEF files convert to CGMES; drop --to and --profile"
            );
            usage();
        }
        cmd_import_convert(&input_files, out_path.as_deref(), zip, &import);
        return;
    }
    if input_files.iter().any(convertible) {
        eprintln!("error: convert MATPOWER or UCTE-DEF files on their own, not with CIM files");
        usage();
    }
    if zip || !import.breakers || !import.name_grouping || import.time.is_some() {
        eprintln!(
            "error: --zip, --no-breakers, --no-name-grouping and --time are for MATPOWER and UCTE-DEF files"
        );
        usage();
    }

    let format = to_format.as_deref().unwrap_or_else(|| {
        eprintln!("error: --to <json|xml> is required");
        usage();
    });

    if input_files.is_empty() {
        eprintln!("error: at least one input file is required");
        usage();
    }

    match format {
        "json" => cmd_to_json(&input_files, out_path.as_deref()),
        "xml" => {
            let profiles: Vec<&str> = profile_str
                .as_deref()
                .map(|s| s.split(',').collect())
                .unwrap_or_default();
            cmd_to_xml(&input_files[0], out_path.as_deref(), &profiles);
        }
        other => {
            eprintln!("error: unknown format '{other}', expected 'json' or 'xml'");
            usage();
        }
    }
}

/// Each MATPOWER or UCTE-DEF file converted to CGMES: its profiles written
/// into `out` (default the current directory), or one `<stem>.zip` there.
/// The written paths go to stdout, what the conversion decided to stderr.
fn cmd_import_convert(
    files: &[PathBuf],
    out: Option<&std::path::Path>,
    zip: bool,
    options: &cimimport::Options,
) {
    let dir = out.unwrap_or_else(|| std::path::Path::new("."));
    or_die(
        std::fs::create_dir_all(dir),
        &format!("error creating directory {}", dir.display()),
    );
    for file in files {
        let name = file.to_string_lossy();
        let bytes = or_die(std::fs::read(file), &format!("error reading {name}"));
        let model = or_die(
            cimimport::convert(&name, &bytes, options),
            &format!("error converting {name}"),
        );
        let format = cimimport::Format::of(&name).map_or("", cimimport::Format::name);
        for note in &model.notes {
            eprintln!("{name}: note: {note}");
        }
        if zip {
            let stem = file
                .file_stem()
                .map_or("model".into(), |s| s.to_string_lossy());
            let path = dir.join(format!("{stem}.zip"));
            or_die(
                write_zip(&path, &model.files),
                &format!("error writing {}", path.display()),
            );
            println!("{}", path.display());
        } else {
            for (file_name, xml) in &model.files {
                let path = dir.join(file_name);
                or_die(
                    std::fs::write(&path, xml),
                    &format!("error writing {}", path.display()),
                );
                println!("{}", path.display());
            }
        }
        eprintln!(
            "{name}: converted from {format}, {} file(s), {} note(s)",
            model.files.len(),
            model.notes.len()
        );
    }
}

/// `files` as `(name, text)` in a deflated zip at `path`.
fn write_zip(path: &std::path::Path, files: &[(String, String)]) -> Result<(), String> {
    use std::io::Write as _;
    let out = std::fs::File::create(path).map_err(|e| e.to_string())?;
    let mut zip = zip::ZipWriter::new(out);
    let options = zip::write::SimpleFileOptions::default()
        .compression_method(zip::CompressionMethod::Deflated);
    for (name, text) in files {
        zip.start_file(name.as_str(), options)
            .map_err(|e| e.to_string())?;
        zip.write_all(text.as_bytes()).map_err(|e| e.to_string())?;
    }
    zip.finish().map_err(|e| e.to_string())?;
    Ok(())
}

fn cmd_to_json(xml_files: &[PathBuf], out: Option<&std::path::Path>) {
    let paths: Vec<&std::path::Path> = xml_files.iter().map(PathBuf::as_path).collect();
    let ds = or_die(
        cimmodel::CimDataset::decode_files_parallel(&paths),
        "error decoding XML",
    );
    let json = cimmodel::convert::dataset_to_json(&ds);
    let text = or_die(
        serde_json::to_string_pretty(&json),
        "error serializing JSON",
    );
    write_output(&text, out);
}

fn cmd_to_xml(json_file: &std::path::Path, out: Option<&std::path::Path>, profiles: &[&str]) {
    let src = or_die(
        std::fs::read_to_string(json_file),
        &format!("error reading {}", json_file.display()),
    );
    let ds = or_die(
        cimmodel::convert::dataset_from_json(&src),
        "error parsing JSON",
    );

    if profiles.is_empty() {
        let xml = or_die(
            cimmodel::convert::dataset_to_xml(&ds),
            "error generating XML",
        );
        write_output(&xml, out);
        return;
    }

    if profiles.len() > 1 {
        let dir = out.unwrap_or_else(|| {
            eprintln!("error: --out <dir/> is required when multiple --profile codes are given");
            usage();
        });
        if !dir.is_dir() {
            or_die(
                std::fs::create_dir_all(dir),
                &format!("error creating directory {}", dir.display()),
            );
        }
        for &code in profiles {
            let xml = or_die(
                cimmodel::convert::dataset_to_xml_for_profile(&ds, code),
                &format!("error generating XML for profile {code}"),
            );
            let path = dir.join(format!("{code}.xml"));
            or_die(
                std::fs::write(&path, &xml),
                &format!("error writing {}", path.display()),
            );
        }
    } else {
        let code = profiles[0];
        let xml = or_die(
            cimmodel::convert::dataset_to_xml_for_profile(&ds, code),
            &format!("error generating XML for profile {code}"),
        );
        write_output(&xml, out);
    }
}

fn write_output(text: &str, out: Option<&std::path::Path>) {
    match out {
        Some(path) => or_die(
            std::fs::write(path, text),
            &format!("error writing {}", path.display()),
        ),
        None => print!("{text}"),
    }
}

fn cmd_import(args: &[String]) {
    let mut input_files: Vec<PathBuf> = Vec::new();
    let mut output_json = false;

    let mut i = 0usize;
    while i < args.len() {
        match args[i].as_str() {
            "--json" => {
                output_json = true;
            }
            arg if !arg.starts_with('-') => {
                input_files.push(PathBuf::from(arg));
            }
            unknown => {
                eprintln!("error: unknown flag: {unknown}");
                usage();
            }
        }
        i += 1;
    }

    if input_files.is_empty() {
        eprintln!("error: at least one input file is required");
        usage();
    }

    struct FileResult {
        name: String,
        count: usize,
    }

    // Decode all files in parallel, collecting per-file counts before merging.
    let paths: Vec<&std::path::Path> = input_files.iter().map(PathBuf::as_path).collect();
    let datasets = or_die(
        cimmodel::CimDataset::decode_files_parallel_separate(&paths),
        "error decoding input",
    );

    let mut per_file: Vec<FileResult> = Vec::new();
    let mut combined = cimmodel::CimDataset::new();
    for (path, ds) in input_files.iter().zip(datasets) {
        let name = path
            .file_name()
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| path.display().to_string());
        per_file.push(FileResult {
            name,
            count: ds.entries.len(),
        });
        combined.merge(ds);
    }

    let total = combined.entries.len();
    let mut type_counts: Vec<(String, usize)> = combined
        .by_type
        .iter()
        .map(|(t, v)| (t.clone(), v.len()))
        .collect();
    type_counts.sort_by(|a, b| a.0.cmp(&b.0));

    if output_json {
        let files_json: Vec<serde_json::Value> = per_file
            .iter()
            .map(|f| serde_json::json!({ "file": f.name, "count": f.count }))
            .collect();
        let type_map: serde_json::Map<String, serde_json::Value> = type_counts
            .iter()
            .map(|(t, n)| (t.clone(), serde_json::Value::from(*n)))
            .collect();
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "total": total,
                "files": files_json,
                "type_counts": type_map,
            }))
            .unwrap()
        );
    } else {
        println!(
            "Total elements: {} (from {} file(s))\n",
            total,
            per_file.len()
        );
        for f in &per_file {
            println!("  {}: {} elements", f.name, f.count);
        }
        if !type_counts.is_empty() {
            println!("\nBy type:");
            for (t, n) in &type_counts {
                println!("  {:<50} {}", t, n);
            }
        }
    }
}

fn cmd_validate(args: &[String]) {
    let mut input_files: Vec<PathBuf> = Vec::new();
    let mut profiles_override: Option<Vec<String>> = None;
    let mut force_solved = false;
    let mut force_not_solved = false;
    let mut enable_common = false;
    let mut enable_quality = false;
    let mut silenced: Vec<String> = Vec::new();
    let mut format = "text";
    // The profiles' own SPARQL queries: in place of the hand-written rules, or beside them.
    #[cfg(feature = "sparql")]
    let mut sparql_mode: Option<&str> = None;

    let mut i = 0usize;
    while i < args.len() {
        match args[i].as_str() {
            "--profiles" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --profiles requires an argument");
                    usage();
                }
                profiles_override = Some(args[i].split(',').map(str::to_string).collect());
            }
            "--solved" => {
                force_solved = true;
            }
            "--not-solved" => {
                force_not_solved = true;
            }
            "--common" => {
                enable_common = true;
            }
            "--quality" => {
                enable_quality = true;
            }
            #[cfg(feature = "sparql")]
            "--sparql" => {
                sparql_mode = Some("replace");
            }
            #[cfg(feature = "sparql")]
            "--sparql=both" => {
                sparql_mode = Some("both");
            }
            "--silence" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --silence requires an argument");
                    usage();
                }
                silenced.extend(args[i].split(',').map(str::to_string));
            }
            "--format" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --format requires an argument");
                    usage();
                }
                format = match args[i].as_str() {
                    "json" => "json",
                    "text" => "text",
                    "sarif" => "sarif",
                    other => {
                        eprintln!(
                            "error: unknown format '{other}', expected 'text', 'json' or 'sarif'"
                        );
                        usage();
                    }
                };
            }
            arg if !arg.starts_with('-') => {
                input_files.push(PathBuf::from(arg));
            }
            unknown => {
                eprintln!("error: unknown flag: {unknown}");
                usage();
            }
        }
        i += 1;
    }

    if input_files.is_empty() {
        eprintln!("error: at least one input file is required");
        usage();
    }

    // Decode each file separately (in parallel) to enable per-profile pre-merge validation.
    let paths: Vec<&std::path::Path> = input_files.iter().map(PathBuf::as_path).collect();
    let datasets = or_die(
        cimmodel::CimDataset::decode_files_parallel_separate(&paths),
        "error decoding input",
    );

    let solved_override = if force_solved {
        Some(true)
    } else if force_not_solved {
        Some(false)
    } else {
        None
    };
    let cfg = cimvalidation::combined_config(
        &datasets,
        profiles_override,
        solved_override,
        enable_common,
        enable_quality,
        silenced,
    );

    #[cfg(feature = "sparql")]
    let queried = sparql_mode.map(|mode| (mode, run_sparql_shapes(&datasets, &cfg)));

    // Two-phase validation: per-file local checks in parallel, then crossprofile checks
    // on the merged dataset, with rule silencing applied.
    #[allow(unused_mut)]
    let mut violations = cimvalidation::validate_files(datasets, &cfg);

    #[cfg(feature = "sparql")]
    if let Some((mode, (ids, found))) = queried {
        let queried_rule = |v: &cimvalidation::Violation| ids.contains(v.rule_id.as_str());
        if mode == "replace" {
            violations.retain(|v| !queried_rule(v));
            violations.extend(found);
        } else {
            report_differences(violations.iter().filter(|v| queried_rule(v)), found.iter());
        }
    }

    if format == "sarif" {
        let log = sarif::render(&violations, &input_files);
        let mut out = std::io::BufWriter::new(std::io::stdout().lock());
        or_die(
            serde_json::to_writer_pretty(&mut out, &log),
            "error writing SARIF",
        );
        or_die(
            std::io::Write::write_all(&mut out, b"\n"),
            "error writing SARIF",
        );
    } else if format == "json" {
        let arr: Vec<serde_json::Value> = violations
            .iter()
            .map(|v| {
                serde_json::json!({
                    "object_id": v.object_id,
                    "rule_id":   v.rule_id,
                    "name":      v.name,
                    "class":     v.class,
                    "property":  v.property,
                    "message":   v.message,
                    "severity":  v.severity,
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&arr).unwrap());
    } else if violations.is_empty() {
        println!("No violations found.");
    } else {
        for v in &violations {
            println!(
                "[{}] {} — {} ({})",
                v.severity, v.rule_id, v.message, v.object_id
            );
        }
        // sh:Info is advisory and does not fail the run. NC leans on it
        // heavily — 842 occurrences against CGMES's 7, nearly all of them the
        // sh:closed "property not in profile" rule — so treating every finding
        // as a failure would fail almost every real NC dataset.
        let failures = violations
            .iter()
            .filter(|v| v.severity != "sh:Info")
            .count();
        let advisory = violations.len() - failures;
        if advisory > 0 {
            eprintln!("{failures} violation(s), {advisory} advisory (sh:Info).");
        } else {
            eprintln!("{failures} violation(s) found.");
        }
        if failures > 0 {
            process::exit(2);
        }
    }
}

/// Run the profiles' SPARQL constraints, read from `CIMOXIDE_PROFILES`: the rule ids they
/// cover, and what they found.
#[cfg(feature = "sparql")]
fn run_sparql_shapes(
    datasets: &[cimmodel::CimDataset],
    cfg: &cimvalidation::Config,
) -> (
    std::collections::HashSet<String>,
    Vec<cimvalidation::Violation>,
) {
    use cimvalidation::sparql_shapes;
    let rules = match sparql_shapes::from_env() {
        Some(Ok(rules)) => rules,
        Some(Err(e)) => {
            eprintln!("error: reading the SPARQL constraints: {e}");
            process::exit(1);
        }
        None => {
            eprintln!(
                "error: --sparql reads the queries from ENTSO-E's profile files; set \
                 CIMOXIDE_PROFILES to their directories (e.g. CGMES-AP:NC-AP)"
            );
            process::exit(1);
        }
    };
    for (rule, why) in &rules.skipped {
        eprintln!("warning: SPARQL constraint {rule} not run: {why}");
    }
    let report = sparql_shapes::validate_files(datasets, cfg, &rules);
    for (rule, error) in &report.failed {
        eprintln!("warning: SPARQL constraint {rule} failed: {error}");
    }
    let ids = rules
        .rules
        .iter()
        .map(|r| r.constraint.rule_id.clone())
        .collect();
    (ids, report.violations.into_iter().map(|(_, v)| v).collect())
}

/// `--sparql=both`: where the hand-written rules and the profiles' queries disagree, on
/// stderr.
#[cfg(feature = "sparql")]
fn report_differences<'a>(
    hand: impl Iterator<Item = &'a cimvalidation::Violation>,
    queried: impl Iterator<Item = &'a cimvalidation::Violation>,
) {
    use std::collections::BTreeSet;
    let key = |v: &cimvalidation::Violation| (v.rule_id.clone(), v.object_id.clone());
    let hand: BTreeSet<(String, String)> = hand.map(key).collect();
    let queried: BTreeSet<(String, String)> = queried.map(key).collect();
    let (only_hand, only_query): (Vec<_>, Vec<_>) = (
        hand.difference(&queried).collect(),
        queried.difference(&hand).collect(),
    );
    for (rule, object) in &only_hand {
        eprintln!("differs: {rule} ({object}): found by the hand-written rule only");
    }
    for (rule, object) in &only_query {
        eprintln!("differs: {rule} ({object}): found by the profile's query only");
    }
    eprintln!(
        "{} finding(s) where the hand-written rules and the profiles' queries differ.",
        only_hand.len() + only_query.len()
    );
}

/// `cimox query` — run a SPARQL query over the merged input files.
#[cfg(feature = "sparql")]
fn cmd_query(args: &[String]) {
    use cimsparql::format::Format;

    let mut query: Option<String> = None;
    let mut query_file: Option<PathBuf> = None;
    let mut format = Format::Text;
    let mut input_files: Vec<PathBuf> = Vec::new();

    let mut i = 0usize;
    while i < args.len() {
        match args[i].as_str() {
            "--query" | "-q" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --query requires an argument");
                    usage();
                }
                query = Some(args[i].clone());
            }
            "--file" | "-f" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --file requires an argument");
                    usage();
                }
                query_file = Some(PathBuf::from(&args[i]));
            }
            "--format" => {
                i += 1;
                if i >= args.len() {
                    eprintln!("error: --format requires an argument");
                    usage();
                }
                format = match Format::parse(&args[i]) {
                    Some(f) => f,
                    None => {
                        eprintln!(
                            "error: unknown format: {} (want text|json|csv|tsv)",
                            args[i]
                        );
                        process::exit(1);
                    }
                };
            }
            arg if !arg.starts_with('-') => input_files.push(PathBuf::from(arg)),
            unknown => {
                eprintln!("error: unknown flag: {unknown}");
                usage();
            }
        }
        i += 1;
    }

    let sparql = match (query, query_file) {
        (Some(_), Some(_)) => {
            eprintln!("error: pass either --query or --file, not both");
            process::exit(1);
        }
        (Some(q), None) => q,
        (None, Some(path)) => or_die(std::fs::read_to_string(&path), "error reading query file"),
        (None, None) => {
            eprintln!("error: a query is required (--query or --file)");
            usage();
        }
    };

    if input_files.is_empty() {
        eprintln!("error: at least one input file is required");
        usage();
    }

    let paths: Vec<&std::path::Path> = input_files.iter().map(PathBuf::as_path).collect();
    let dataset = or_die(
        cimmodel::CimDataset::decode_files_parallel(&paths),
        "error decoding input",
    );
    let store = or_die(
        cimsparql::CimStore::from_dataset(&dataset),
        "error building RDF graph",
    );
    let results = or_die(store.query(&sparql), "query failed");

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    or_die(
        cimsparql::format::write(results, format, &mut out),
        "error writing results",
    );
}