feat(review): add versioned JSON comparison reports

This commit is contained in:
Jan Petykiewicz 2026-11-15 10:38:48 -08:00
commit 248f6bcff7

View file

@ -1,3 +1,4 @@
use klamath_rs_ext::review::report::{ReportInputs, ReportOptions, failure_report};
use klamath_rs_ext::review::{
Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer,
parse_layer_name, write_layer_names,
@ -7,12 +8,13 @@ use std::{
ffi::OsString,
fs,
io::{self, Write},
path::PathBuf,
process::ExitCode,
};
const HELP: &str = "Usage:
klamath dump FILE [--records]
klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none]\n [--max-changes N] [--depth N]
klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none|graph]\n [--max-changes N] [--depth N] [--format text|json]
klamath hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n klamath git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE
klamath name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
@ -85,8 +87,57 @@ fn stdout(output: &str) -> Result<(), String> {
.map_err(|e| e.to_string())
}
fn run() -> Result<u8, String> {
let args: Vec<_> = std::env::args_os().skip(1).collect();
fn json_stdout(report: &serde_json::Value) -> Result<(), String> {
let mut output = io::stdout().lock();
serde_json::to_writer_pretty(&mut output, report).map_err(|e| e.to_string())?;
output.write_all(b"\n").map_err(|e| e.to_string())
}
fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result<u8, String> {
let inputs = ReportInputs {
old: Some(PathBuf::from(&paths[0])),
new: Some(PathBuf::from(&paths[1])),
};
let comparison = || {
let read = |index, side| {
fs::read(&paths[index])
.map_err(|e| ("io_error", format!("{:?}: {e}", paths[index]), Some(side)))
};
let old_bytes = read(0, "old")?;
let new_bytes = read(1, "new")?;
let old = Document::parse(&old_bytes).map_err(|e| ("invalid_input", e, Some("old")))?;
let new = Document::parse(&new_bytes).map_err(|e| ("invalid_input", e, Some("new")))?;
scope
.validate_pair(&old, &new)
.map_err(|e| ("invalid_scope", e, None))?;
let old = old
.selected(scope, true)
.map_err(|e| ("invalid_scope", e, Some("old")))?;
let new = new
.selected(scope, true)
.map_err(|e| ("invalid_scope", e, Some("new")))?;
let diff = Comparison::between(&old, &new);
Ok::<_, (&str, String, Option<&str>)>((
diff.json_report(&old, &new, &inputs, options),
diff.exit_code(),
))
};
let (report, status) = match comparison() {
Ok(result) => result,
Err((code, message, side)) => (
failure_report(&inputs, scope, options, code, &message, side),
2,
),
};
if let Err(error) = json_stdout(&report) {
// Once output starts, never append a second report on a write failure.
eprintln!("klamath: {error}");
return Ok(2);
}
Ok(status)
}
fn run(args: &[OsString]) -> Result<u8, String> {
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
stdout(HELP)?;
return Ok(0);
@ -111,7 +162,10 @@ fn run() -> Result<u8, String> {
"ascii".to_string()
};
let mut max_changes = 100;
let mut explicit_max = None;
let mut output_format = "text".to_string();
let mut depth = 8;
let mut explicit_depth = false;
let mut paths = Vec::new();
let mut literal = false;
let mut i = 1;
@ -128,22 +182,25 @@ fn run() -> Result<u8, String> {
return Ok(0);
}
Some("--records") if command == "dump" => raw = true,
Some("--top") => scope.top = Some(value(&args, &mut i)?),
Some("--cell") => scope.cell = Some(value(&args, &mut i)?),
Some("--layer") => scope.layer = Some(parse_layer(&value(&args, &mut i)?)?),
Some("--show-cell") if compare => show.cell = Some(value(&args, &mut i)?),
Some("--top") => scope.top = Some(value(args, &mut i)?),
Some("--cell") => scope.cell = Some(value(args, &mut i)?),
Some("--layer") => scope.layer = Some(parse_layer(&value(args, &mut i)?)?),
Some("--show-cell") if compare => show.cell = Some(value(args, &mut i)?),
Some("--show-layer") if compare => {
show.layer = Some(parse_layer(&value(&args, &mut i)?)?)
show.layer = Some(parse_layer(&value(args, &mut i)?)?)
}
Some("--hierarchy") if compare => format = value(&args, &mut i)?,
Some("--format") if command == "hierarchy" => format = value(&args, &mut i)?,
Some("--hierarchy") if compare => format = value(args, &mut i)?,
Some("--format") if command == "hierarchy" => format = value(args, &mut i)?,
Some("--format") if command == "diff" => output_format = value(args, &mut i)?,
Some("--max-changes") if compare => {
max_changes = value(&args, &mut i)?
max_changes = value(args, &mut i)?
.parse()
.map_err(|_| "invalid change limit")?
.map_err(|_| "invalid change limit")?;
explicit_max = Some(max_changes);
}
Some("--depth") if command != "dump" => {
depth = value(&args, &mut i)?.parse().map_err(|_| "invalid depth")?
depth = value(args, &mut i)?.parse().map_err(|_| "invalid depth")?;
explicit_depth = true;
}
Some(s) if s.starts_with('-') => return Err(format!("unknown option {s:?}")),
_ => paths.push(args[i].clone()),
@ -153,6 +210,25 @@ fn run() -> Result<u8, String> {
if paths.len() != expected && !(command == "git-diff" && paths.len() == 9) {
return Err(HELP.to_string());
}
if !matches!(output_format.as_str(), "text" | "json") {
return Err("diff format must be text or json".to_string());
}
if output_format == "json" {
if !matches!(format.as_str(), "none" | "graph") || explicit_depth {
return Err(
"JSON accepts --hierarchy graph|none; --depth applies to text output".to_string(),
);
}
return json_diff(
&paths,
&scope,
&ReportOptions {
filter: show,
max_objects: explicit_max,
hierarchy: format == "graph",
},
);
}
if !matches!(format.as_str(), "ascii" | "mermaid" | "none")
|| (command == "hierarchy" && format == "none")
{
@ -248,11 +324,51 @@ fn run() -> Result<u8, String> {
})
}
fn wants_json(args: &[OsString]) -> bool {
if args.first().is_none_or(|arg| arg != "diff") {
return false;
}
let mut format = None;
let mut i = 1;
while i < args.len() {
match args[i].to_str() {
Some("--") => break,
Some("--format") => {
format = args.get(i + 1).and_then(|v| v.to_str());
i += 1;
}
Some(
"--top" | "--cell" | "--layer" | "--show-cell" | "--show-layer" | "--hierarchy"
| "--max-changes" | "--depth",
) => i += 1,
_ => (),
}
i += 1;
}
format == Some("json")
}
fn main() -> ExitCode {
match run() {
let args: Vec<_> = std::env::args_os().skip(1).collect();
let json = wants_json(&args);
match run(&args) {
Ok(status) => ExitCode::from(status),
Err(message) => {
eprintln!("klamath: {message}");
if json {
let report = failure_report(
&ReportInputs::default(),
&Scope::default(),
&ReportOptions::default(),
"command_error",
&message,
None,
);
if let Err(error) = json_stdout(&report) {
eprintln!("klamath: {error}");
}
} else {
eprintln!("klamath: {message}");
}
ExitCode::from(2)
}
}