use flate2::read::MultiGzDecoder; use pheon::review::report::{ReportInputs, ReportOptions, failure_report}; use pheon::review::{ Comparison, Diagnostic, Document, Outcome, Side, dump_records, names::{parse_layer, parse_layer_name, write_layer_names}, selection::{DisplayFilter, Scope}, }; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, fs, io::{self, Read, 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 ... Structural comparison: ignore timestamps and element order, normalize polygon start/winding, preserve duplicates, compare all retained fields exactly. No geometric XOR or tolerance. Gzip-compressed GDSII input is recognized by its header. Exit status: 0 equal/success, 1 different, 2 invalid/unsupported/incomplete. "; fn read_input(path: &OsStr) -> Result, Diagnostic> { let io_error = |error: io::Error| Diagnostic::new("io_error", format!("{path:?}: {error}"), None); let mut file = fs::File::open(path).map_err(io_error)?; let mut bytes = Vec::new(); (&mut file) .take(2) .read_to_end(&mut bytes) .map_err(io_error)?; if bytes == b"\x1f\x8b" { let mut decoded = Vec::new(); MultiGzDecoder::new(bytes.as_slice().chain(file)) .read_to_end(&mut decoded) .map_err(|error| { Diagnostic::new( "invalid_input", format!("{path:?}: gzip decompression failed: {error}"), None, ) })?; return Ok(decoded); } file.read_to_end(&mut bytes).map_err(io_error)?; Ok(bytes) } fn value(args: &[OsString], index: &mut usize) -> Result { *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 { 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 = read_input(&args[0]).map_err(|error| error.message)?; 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 prepare_comparison( old_path: Option<&OsStr>, new_path: Option<&OsStr>, scope: &Scope, ) -> Result { let read = |path: Option<&OsStr>, side| { path.map(|path| { read_input(path).map_err(|mut diagnostic| { diagnostic.side = Some(side); diagnostic }) }) .transpose() }; let old_bytes = read(old_path, Side::Old)?; let new_bytes = read(new_path, Side::New)?; let old = old_bytes .as_deref() .map(Document::parse) .transpose() .map_err(|message| Diagnostic::new("invalid_input", message, Some(Side::Old)))?; let new = new_bytes .as_deref() .map(Document::parse) .transpose() .map_err(|message| Diagnostic::new("invalid_input", message, Some(Side::New)))?; let (old, new) = match (old, new) { (Some(old), Some(new)) => (old, new), (None, Some(new)) => (new.empty_like(), new), (Some(old), None) => { let new = old.empty_like(); (old, new) } (None, None) => { return Err(Diagnostic::new( "invalid_input", "both Git revisions are absent", None, )); } }; scope .validate_pair(&old, &new) .map_err(|message| Diagnostic::new("invalid_scope", message, None))?; let old = old .selected(scope, true) .map_err(|message| Diagnostic::new("invalid_scope", message, Some(Side::Old)))?; let new = new .selected(scope, true) .map_err(|message| Diagnostic::new("invalid_scope", message, Some(Side::New)))?; Ok(Comparison::between(&old, &new)) } fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result { let inputs = ReportInputs { old: Some(PathBuf::from(&paths[0])), new: Some(PathBuf::from(&paths[1])), }; let (report, outcome) = match prepare_comparison(Some(&paths[0]), Some(&paths[1]), scope) { Ok(diff) => (diff.json_report(&inputs, options), diff.outcome()), Err(error) => ( failure_report(&inputs, scope, options, &error), Outcome::Failed, ), }; 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(outcome.exit_code()) } fn run(args: &[OsString]) -> Result { 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| read_input(path).map_err(|error| error.message); 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 { doc.hierarchy(format == "mermaid", depth) }; stdout(&output)?; if command == "hierarchy" { for diagnostic in &doc.diagnostics { eprintln!("INCOMPLETE: {}", diagnostic.message); } } return Ok(if doc.diagnostics.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] == "."); let diff = prepare_comparison( (!old_missing).then_some(paths[if git { 1 } else { 0 }].as_os_str()), (!new_missing).then_some(paths[if git { 4 } else { 1 }].as_os_str()), &scope, ) .map_err(|error| error.message)?; 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(&diff.hierarchy(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.outcome().exit_code() == 1 { 0 } else { diff.outcome().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(), &Diagnostic::new("command_error", message, None), ); if let Err(error) = json_stdout(&report) { eprintln!("pheon: {error}"); } } else { eprintln!("pheon: {message}"); } ExitCode::from(2) } } }