pheon/src/bin/pheon.rs

379 lines
13 KiB
Rust
Raw Normal View History

use pheon::review::report::{ReportInputs, ReportOptions, failure_report};
use pheon::review::{
Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer,
parse_layer_name, write_layer_names,
};
use std::{
collections::BTreeMap,
ffi::OsString,
fs,
io::{self, Write},
path::PathBuf,
process::ExitCode,
};
const HELP: &str = "Usage:
pheon dump FILE [--records]
pheon 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]
pheon hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n pheon git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE
pheon name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
Object profile: ignore timestamps and element order, normalize polygon start/winding,
preserve duplicates, compare all retained fields exactly. No geometric XOR or tolerance.
Exit status: 0 equal/success, 1 different, 2 invalid/unsupported/incomplete.
";
fn value(args: &[OsString], index: &mut usize) -> Result<String, String> {
*index += 1;
args.get(*index)
.and_then(|s| s.to_str())
.map(str::to_owned)
.ok_or_else(|| "missing UTF-8 option value".to_string())
}
fn name_layers(args: &[OsString]) -> Result<u8, String> {
if args.len() < 2 {
return Err(HELP.to_string());
}
let (mut cell, mut carrier) = (None, None);
let mut names = BTreeMap::new();
let mut i = 2;
while i < args.len() {
match args[i].to_str() {
Some("--cell") => cell = Some(value(args, &mut i)?),
Some("--carrier") => carrier = Some(parse_layer(&value(args, &mut i)?)?),
Some("--name") => {
let (pair, name) = parse_layer_name(&value(args, &mut i)?)?;
if names.get(&pair).is_some_and(|old| old != &name) {
return Err("conflicting --name arguments".to_string());
}
names.insert(pair, name);
}
_ => {
return Err(
"name-layers requires --cell, --carrier and --name arguments".to_string(),
);
}
}
i += 1;
}
if names.is_empty() {
return Err("provide at least one --name".to_string());
}
let input = fs::read(&args[0]).map_err(|e| format!("{:?}: {e}", args[0]))?;
let output = write_layer_names(
&input,
&cell.ok_or("provide --cell")?,
carrier.ok_or("provide --carrier")?,
&names,
)?;
let mut file = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&args[1])
.map_err(|e| format!("{:?}: {e}", args[1]))?;
if let Err(e) = file.write_all(&output).and_then(|_| file.sync_all()) {
drop(file);
let _ = fs::remove_file(&args[1]);
return Err(e.to_string());
}
Ok(0)
}
fn stdout(output: &str) -> Result<(), String> {
io::stdout()
.lock()
.write_all(output.as_bytes())
.map_err(|e| e.to_string())
}
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!("pheon: {error}");
return Ok(2);
}
Ok(status)
}
fn run(args: &[OsString]) -> Result<u8, String> {
if args.len() == 1 && matches!(args[0].to_str(), Some("--version" | "-V")) {
stdout(&format!("pheon {}\n", env!("CARGO_PKG_VERSION")))?;
return Ok(0);
}
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
stdout(HELP)?;
return Ok(0);
}
let command = args[0].to_str().ok_or("invalid command")?;
if command == "name-layers" {
return name_layers(&args[1..]);
}
let expected = match command {
"dump" | "hierarchy" => 1,
"diff" => 2,
"git-diff" => 7,
_ => return Err(HELP.to_string()),
};
let compare = command == "diff" || command == "git-diff";
let mut scope = Scope::default();
let mut show = DisplayFilter::default();
let mut raw = false;
let mut format = if compare {
"none".to_string()
} else {
"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;
while i < args.len() {
if literal {
paths.push(args[i].clone());
i += 1;
continue;
}
match args[i].to_str() {
Some("--") => literal = true,
Some("--help" | "-h") => {
stdout(HELP)?;
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("--show-layer") if compare => {
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("--format") if command == "diff" => output_format = value(args, &mut i)?,
Some("--max-changes") if compare => {
max_changes = value(args, &mut i)?
.parse()
.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")?;
explicit_depth = true;
}
Some(s) if s.starts_with('-') => return Err(format!("unknown option {s:?}")),
_ => paths.push(args[i].clone()),
}
i += 1;
}
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")
{
return Err("format must be ascii or mermaid (diff also accepts none)".to_string());
}
let read = |path: &OsString| fs::read(path).map_err(|e| format!("{path:?}: {e}"));
if raw {
if scope != Scope::default() {
return Err("record dumps do not accept object scope selectors".to_string());
}
stdout(&dump_records(&read(&paths[0])?)?)?;
return Ok(0);
}
if !compare {
let bytes = read(&paths[0])?;
let doc = Document::parse(&bytes)?.selected(&scope, false)?;
let output = if command == "dump" {
doc.canonical_dump()
} else {
hierarchy(&doc, &doc, None, format == "mermaid", depth)
};
stdout(&output)?;
if command == "hierarchy" {
for issue in &doc.issues {
eprintln!("INCOMPLETE: {issue}");
}
}
return Ok(if doc.issues.is_empty() { 0 } else { 2 });
}
let git = command == "git-diff";
let old_missing = git && (paths[3] == "000000" || paths[3] == ".");
let new_missing = git && (paths[6] == "000000" || paths[6] == ".");
if old_missing && new_missing {
return Err("both Git revisions are absent".to_string());
}
let old_bytes = if old_missing {
None
} else {
Some(read(&paths[if git { 1 } else { 0 }])?)
};
let new_bytes = if new_missing {
None
} else {
Some(read(&paths[if git { 4 } else { 1 }])?)
};
let old = old_bytes.as_ref().map(|b| Document::parse(b)).transpose()?;
let new = new_bytes.as_ref().map(|b| Document::parse(b)).transpose()?;
let old = old.unwrap_or_else(|| new.as_ref().unwrap().empty_like());
let new = new.unwrap_or_else(|| old.empty_like());
scope.validate_pair(&old, &new)?;
let old = old.selected(&scope, true)?;
let new = new.selected(&scope, true)?;
let diff = Comparison::between(&old, &new);
let mut output = String::new();
if git {
if paths.len() == 9 {
output.push_str(&format!("layout {:?} -> {:?}\n", paths[0], paths[7]));
} else {
output.push_str(&format!("layout {:?}\n", paths[0]));
}
if old_missing {
output.push_str("layout added\n");
} else if new_missing {
output.push_str("layout deleted\n");
}
if paths[3] != paths[6] {
output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6]));
}
}
output.push_str(&diff.text_filtered(max_changes, &show));
if format != "none" {
if format == "mermaid" {
output.push_str("```mermaid\n");
}
output.push_str(&hierarchy(
&old,
&new,
Some(&diff),
format == "mermaid",
depth,
));
if format == "mermaid" {
output.push_str("```\n");
}
}
stdout(&output)?;
// Git's external driver expects successful rendering for either equality
// or differences. Actual comparison/input failures remain nonzero.
Ok(if git && diff.exit_code() == 1 {
0
} else {
diff.exit_code()
})
}
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 {
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) => {
if json {
let report = failure_report(
&ReportInputs::default(),
&Scope::default(),
&ReportOptions::default(),
"command_error",
&message,
None,
);
if let Err(error) = json_stdout(&report) {
eprintln!("pheon: {error}");
}
} else {
eprintln!("pheon: {message}");
}
ExitCode::from(2)
}
}
}