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
--single-description
report an object described twice in one file (CIM0005)
--max-input SIZE stop reading after SIZE bytes, archives counted decompressed
(default 8GiB; e.g. 512MB, 16GiB, 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,
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()),
}
}
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>()
)?;
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()))?;
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()
};
}
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" };
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);
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())?;
}
None => {
cim_kit::writer::write_difference(schema, &change.model, &mut *out, &Default::default())
.map_err(|e| e.to_string())?
}
}
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)
}
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()
)
})?;
applied.extend(ds.apply_difference(&diff));
}
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));
}
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))
}
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()),
}
}
}
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()
}
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),
];
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:?}"
)
})
}
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,
single_description: 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,
"--single-description" => args.single_description = 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:?}"))?;
}
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)
}
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:?}")
});
}
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)
}
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)
}
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()
};
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.with_single_description(self.single_description))
}
fn out_dir(&self) -> Result<PathBuf, String> {
self.out
.clone()
.ok_or_else(|| "this command needs --out DIR".to_owned())
}
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))
}
}