diff --git a/Cargo.lock b/Cargo.lock index 3c11424..cfec364 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -133,7 +133,7 @@ dependencies = [ "android-tzdata", "iana-time-zone", "num-traits", - "windows-link", + "windows-link 0.1.1", ] [[package]] @@ -378,6 +378,7 @@ dependencies = [ "flate2", "serde", "serde_json", + "termcolor", ] [[package]] @@ -465,6 +466,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -550,6 +560,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys", +] + [[package]] name = "windows-core" version = "0.61.0" @@ -558,7 +577,7 @@ checksum = "4763c1de310c86d75a878046489e2e5ba02c649d185f21c67d4cf8a56d098980" dependencies = [ "windows-implement", "windows-interface", - "windows-link", + "windows-link 0.1.1", "windows-result", "windows-strings", ] @@ -591,13 +610,19 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "76840935b766e1b0a05c0066835fb9ec80071d4c09a16f6bd5f7e655e3c14c38" +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + [[package]] name = "windows-result" version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c64fd11a4fd95df68efcfee5f44a294fe71b8bc6a91993e2791938abcc712252" dependencies = [ - "windows-link", + "windows-link 0.1.1", ] [[package]] @@ -606,7 +631,16 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a2ba9642430ee452d5a7aa78d72907ebe8cfda358e8cb7918a2050581322f97" dependencies = [ - "windows-link", + "windows-link 0.1.1", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 11a6afe..93004b5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -21,6 +21,7 @@ arrow-schema = "^54" flate2 = "1" serde = "1" serde_json = "1" +termcolor = "1.4" [profile.release] diff --git a/docs/cli.md b/docs/cli.md index b22f4ca..d4f59c3 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -32,11 +32,15 @@ pheon hierarchy chip.gds --format mermaid --top CHIP normalized object within a cell. Coordinates are in database units. Rectangles show two corners, and longer vertex lists wrap across lines. References show the target and any array dimensions before the coordinates. Add `--records` -to inspect the original record sequence, including timestamps. +to inspect the original record sequence, including timestamps. In color +output, the object dump highlights cell headings and layer numbers, and the +record dump highlights record names. -`hierarchy` shows direct placement counts on references. Shared cells are -marked where their contents appear earlier in the tree. Mermaid output is -diagram source for a Mermaid renderer. +`hierarchy` shows direct placement counts on references. `[subtree elided]` +marks a repeated cell whose children were skipped. Repeated leaves show +each parent's placement count without the marker. At the depth limit, +`[children omitted]` marks a cell with further descendants. Mermaid +output is diagram source for a Mermaid renderer. ## Compare revisions @@ -66,6 +70,12 @@ vertices show their width, vertex count, and vertex bounds in one line. Use `--format json` for details of individual objects and `--hierarchy` to see which parent cells are affected. +`diff` and `dump` use `--color auto` by default. Colors appear on supported +terminals and are disabled when `NO_COLOR` is set or `TERM=dumb`. Use +`--color=always` to keep colors in a pipe, for example +`pheon diff before.gds after.gds --color=always | less -R`. Use +`--color=never` for plain text. JSON reports and Mermaid diagram source stay plain. + For large unscoped diffs with substantial byte overlap, Pheon reuses parsed contents of matching cells. Cell timestamps and file offsets can differ. diff --git a/docs/git.md b/docs/git.md index d17aadb..2a571d0 100644 --- a/docs/git.md +++ b/docs/git.md @@ -28,6 +28,9 @@ indicates whether it was added or deleted. Keep the final `--` because Git appen its path and revision arguments after it. Put Pheon options such as `--top CHIP` or `--show-layer 1/0` before that marker. +The external driver also accepts `--color=always` before `--` to keep colors +when its output goes through a pager that supports ANSI colors. + For an existing `diff=layout` attribute, put the configuration under `[diff "layout"]` instead. Attribute names only select a Git driver. diff --git a/src/bin/pheon.rs b/src/bin/pheon.rs index ca92916..309fd6b 100644 --- a/src/bin/pheon.rs +++ b/src/bin/pheon.rs @@ -1,3 +1,6 @@ +#[path = "pheon/color.rs"] +mod color; + use flate2::read::MultiGzDecoder; use pheon::review::report::{ReportInputs, ReportOptions, failure_report}; use pheon::review::{ @@ -14,10 +17,12 @@ use std::{ process::ExitCode, thread, }; +use termcolor::ColorChoice; const HELP: &str = "Usage: - pheon dump FILE [--records] + pheon dump FILE [--records] [--color auto|always|never] 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] + [--color auto|always|never] 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 ... @@ -268,6 +273,8 @@ fn run(args: &[OsString]) -> Result { _ => return Err(HELP.to_string()), }; let compare = command == "diff" || command == "git-diff"; + let color_supported = compare || command == "dump"; + let mut color_choice = ColorChoice::Auto; let mut scope = Scope::default(); let mut show = DisplayFilter::default(); let mut raw = false; @@ -297,6 +304,12 @@ fn run(args: &[OsString]) -> Result { return Ok(0); } Some("--records") if command == "dump" => raw = true, + Some("--color") if color_supported => { + color_choice = color::parse_choice(&value(args, &mut i)?)?; + } + Some(s) if color_supported && s.starts_with("--color=") => { + color_choice = color::parse_choice(&s["--color=".len()..])?; + } 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)?)?), @@ -354,19 +367,22 @@ fn run(args: &[OsString]) -> Result { if scope != Scope::default() { return Err("record dumps do not accept object scope selectors".to_string()); } - stdout(&dump_records(&read(&paths[0])?)?)?; + color::print( + &dump_records(&read(&paths[0])?)?, + color::Report::Records, + color_choice, + ) + .map_err(|error| error.to_string())?; 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() + if command == "dump" { + color::print(&doc.canonical_dump(), color::Report::Dump, color_choice) + .map_err(|error| error.to_string())?; } else { - doc.hierarchy(format == "mermaid", depth) - }; - stdout(&output)?; - if command == "hierarchy" { + stdout(&doc.hierarchy(format == "mermaid", depth))?; for diagnostic in &doc.diagnostics { eprintln!("INCOMPLETE: {}", diagnostic.message); } @@ -419,7 +435,7 @@ fn run(args: &[OsString]) -> Result { output.push_str("```\n"); } } - stdout(&output)?; + color::print(&output, color::Report::Diff, color_choice).map_err(|error| error.to_string())?; // 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 { @@ -444,7 +460,7 @@ fn wants_json(args: &[OsString]) -> bool { } Some( "--top" | "--cell" | "--layer" | "--show-cell" | "--show-layer" | "--hierarchy" - | "--max-changes" | "--depth", + | "--max-changes" | "--depth" | "--color", ) => i += 1, _ => (), } diff --git a/src/bin/pheon/color.rs b/src/bin/pheon/color.rs new file mode 100644 index 0000000..e2061d7 --- /dev/null +++ b/src/bin/pheon/color.rs @@ -0,0 +1,195 @@ +use std::{ + fmt, + io::{self, IsTerminal, Write}, +}; +use termcolor::{BufferedStandardStream, Color, ColorChoice, ColorSpec, WriteColor}; + +pub(super) enum Report { + Diff, + Dump, + Records, +} + +pub(super) fn parse_choice(value: &str) -> Result { + match value { + "auto" => Ok(ColorChoice::Auto), + "always" => Ok(ColorChoice::Always), + "never" => Ok(ColorChoice::Never), + _ => Err("color must be auto, always, or never".to_string()), + } +} + +pub(super) fn print(text: &str, report: Report, choice: ColorChoice) -> io::Result<()> { + let stdout = io::stdout(); + if choice == ColorChoice::Never || (choice == ColorChoice::Auto && !stdout.is_terminal()) { + return stdout.lock().write_all(text.as_bytes()); + } + let mut out = BufferedStandardStream::stdout(choice); + if !out.supports_color() { + out.write_all(text.as_bytes())?; + return out.flush(); + } + + let mut in_cells = false; + let mut in_mermaid = false; + for line in text.split_inclusive('\n') { + let body = line.strip_suffix('\n').unwrap_or(line); + match report { + Report::Diff => match body { + "```mermaid" => { + in_mermaid = true; + out.write_all(body.as_bytes())?; + } + "```" => { + in_mermaid = false; + out.write_all(body.as_bytes())?; + } + _ if in_mermaid => out.write_all(body.as_bytes())?, + _ => { + match body { + "Cells:" => in_cells = true, + "Hierarchy" | "Diagnostics" => in_cells = false, + _ => (), + } + diff_line(&mut out, body, in_cells)?; + } + }, + Report::Dump => dump_line(&mut out, body)?, + Report::Records => record_line(&mut out, body)?, + } + if line.ends_with('\n') { + out.write_all(b"\n")?; + } + } + out.flush() +} + +fn paint( + out: &mut impl WriteColor, + value: impl fmt::Display, + color: Color, + bold: bool, +) -> io::Result<()> { + out.set_color(ColorSpec::new().set_fg(Some(color)).set_bold(bold))?; + let result = write!(out, "{value}"); + result.and(out.reset()) +} + +fn diff_line(out: &mut impl WriteColor, line: &str, in_cells: bool) -> io::Result<()> { + let content = line.trim_start_matches(' '); + let indent = &line[..line.len() - content.len()]; + let first = content.split_once(' ').map_or(content, |(word, _)| word); + if indent.is_empty() { + let color = match first { + "Equal" => Some(Color::Green), + "Different" | "Incomplete" | "Omitted" => Some(Color::Yellow), + "Failed" => Some(Color::Red), + "Cells:" | "Hierarchy" | "Diagnostics" | "Scope" | "Display" | "layout" | "mode" => { + Some(Color::Cyan) + } + _ => None, + }; + if let Some(color) = color { + return paint(out, line, color, true); + } + } + let color = match first { + "+" => Some(Color::Green), + "-" => Some(Color::Red), + "*" | "~" => Some(Color::Yellow), + _ => None, + }; + if let Some(color) = color { + out.write_all(indent.as_bytes())?; + return paint(out, content, color, false); + } + if in_cells && indent == " " { + if (layer_token(content).is_some() || content.starts_with("unknown layer: ")) + && let Some((layer, counts)) = content.rsplit_once(": ") + { + out.write_all(indent.as_bytes())?; + paint(out, layer, Color::Cyan, false)?; + out.write_all(b": ")?; + for (index, clause) in counts.split(" · ").enumerate() { + if index > 0 { + out.write_all(" · ".as_bytes())?; + } + let color = match clause.rsplit_once(' ').map(|(_, action)| action) { + Some("added") => Color::Green, + Some("removed") => Color::Red, + _ => Color::Yellow, + }; + paint(out, clause, color, false)?; + } + return Ok(()); + } + if let Some((target, counts)) = content.rsplit_once(" · -") + && let Some((removed, added)) = counts.split_once(", +") + { + let (added, totals) = added + .split_once(" · ") + .map_or((added, None), |(added, totals)| (added, Some(totals))); + write!(out, "{indent}{target} · ")?; + paint(out, format_args!("-{removed}"), Color::Red, false)?; + out.write_all(b", ")?; + paint(out, format_args!("+{added}"), Color::Green, false)?; + if let Some(totals) = totals { + write!(out, " · {totals}")?; + } + return Ok(()); + } + } + out.write_all(line.as_bytes()) +} + +fn layer_token(line: &str) -> Option<&str> { + let token = line.split([' ', ':']).next()?; + let (layer, datatype) = token.split_once('/')?; + (layer.parse::().is_ok() && datatype.parse::().is_ok()).then_some(token) +} + +fn dump_line(out: &mut impl WriteColor, line: &str) -> io::Result<()> { + if line.starts_with("cell ") || line.starts_with("library ") || line.starts_with("Scope ") { + return paint(out, line, Color::Cyan, true); + } + if line.starts_with("INCOMPLETE: ") { + return paint(out, line, Color::Yellow, true); + } + let mut object = line.trim_start_matches(' '); + if let Some((token, rest)) = object.split_once(' ') + && token + .strip_suffix('x') + .is_some_and(|count| count.parse::().is_ok()) + { + object = rest; + } + let heading = layer_token(object).or_else(|| { + ["reference", "array reference"] + .into_iter() + .find(|heading| { + object + .strip_prefix(heading) + .is_some_and(|rest| rest.starts_with(' ')) + }) + }); + if let Some(heading) = heading { + let prefix = &line[..line.len() - object.len()]; + out.write_all(prefix.as_bytes())?; + paint(out, heading, Color::Cyan, false)?; + return out.write_all(object[heading.len()..].as_bytes()); + } + out.write_all(line.as_bytes()) +} + +fn record_line(out: &mut impl WriteColor, line: &str) -> io::Result<()> { + let mut parts = line.splitn(4, ' '); + if let (Some(offset), Some(tag), Some(name), Some(data)) = + (parts.next(), parts.next(), parts.next(), parts.next()) + { + write!(out, "{offset} {tag} ")?; + paint(out, name, Color::Cyan, false)?; + write!(out, " {data}") + } else { + out.write_all(line.as_bytes()) + } +} diff --git a/src/review.rs b/src/review.rs index 05fadf5..9e49dd4 100644 --- a/src/review.rs +++ b/src/review.rs @@ -1947,13 +1947,16 @@ fn render_hierarchy( while let Some((name, depth, parent)) = stack.pop() { let seen = !included.insert(name.clone()); let descendants = children.get(&name).map(Vec::as_slice).unwrap_or(&[]); - rows.push(( - name.clone(), - depth, - parent, - seen, - depth >= max_depth && !descendants.is_empty(), - )); + let note = if descendants.is_empty() { + "" + } else if depth >= max_depth { + " [children omitted]" + } else if seen { + " [subtree elided]" + } else { + "" + }; + rows.push((name.clone(), depth, parent, note)); if !seen && depth < max_depth { for child in descendants.iter().rev() { stack.push((child.clone(), depth + 1, Some(name.clone()))); @@ -1961,7 +1964,7 @@ fn render_hierarchy( } } for name in visible.difference(&reachable) { - rows.push((name.clone(), 0, None, false, true)); + rows.push((name.clone(), 0, None, " [children omitted]")); } let status = |name: &String| { if !old.cells.contains(name) && !new.cells.contains(name) { @@ -2035,7 +2038,7 @@ fn render_hierarchy( if changes.is_none() { new.scope.write_restrictions(&mut out); } - for (name, depth, parent, seen, limited) in rows { + for (name, depth, parent, note) in rows { out.push_str(&" ".repeat(depth)); if direct.contains(&name) { let marker = cell_marker(old.cells.contains(&name), new.cells.contains(&name)); @@ -2049,14 +2052,7 @@ fn render_hierarchy( if let Some(parent) = parent { write!(out, " {}", edge_label(&parent, &name)).unwrap(); } - writeln!( - out, - "{}{}{}", - status(&name), - if seen { " [shown above]" } else { "" }, - if limited { " [children omitted]" } else { "" } - ) - .unwrap(); + writeln!(out, "{}{note}", status(&name)).unwrap(); } if visible.is_empty() { out.push_str("No changed hierarchy\n"); diff --git a/tests/golden/review-hierarchy.txt b/tests/golden/review-hierarchy.txt index ebaae5e..60542a2 100644 --- a/tests/golden/review-hierarchy.txt +++ b/tests/golden/review-hierarchy.txt @@ -3,4 +3,4 @@ CHIP [affected] left x1 [affected] * leaf x2 right x1 [affected] - * leaf x3 [shown above] + * leaf x3 diff --git a/tests/review.rs b/tests/review.rs index c30f5e2..2b51f45 100644 --- a/tests/review.rs +++ b/tests/review.rs @@ -503,7 +503,7 @@ fn unknown_records_never_produce_a_successful_equality_claim() { } #[test] -fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { +fn shared_hierarchy_reports_ancestors_and_each_leaf_placement_count() { let a = shared(square()); let b = shared(triangle()); let a = Document::parse(&a).unwrap(); @@ -517,7 +517,7 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { " left x1 [affected]\n", " * leaf x2\n", " right x1 [affected]\n", - " * leaf x3 [shown above]\n", + " * leaf x3\n", ) ); let graph = diff.hierarchy(true, 8); @@ -533,6 +533,44 @@ fn shared_hierarchy_reports_ancestors_and_marks_repeated_definitions() { ); } +#[test] +fn ascii_hierarchy_marks_repeated_subtrees_and_depth_limits() { + let bytes = layout(&[ + ( + "CHIP", + vec![reference("left", 0, 1), reference("right", 0, 1)], + ), + ("left", vec![reference("branch", 0, 2)]), + ("right", vec![reference("branch", 0, 3)]), + ("branch", vec![reference("leaf", 0, 1)]), + ("leaf", vec![]), + ]); + let doc = Document::parse(&bytes).unwrap(); + assert_eq!( + doc.hierarchy(false, 8), + concat!( + "Hierarchy\n", + "\"CHIP\"\n", + " \"left\" x1\n", + " \"branch\" x2\n", + " \"leaf\" x1\n", + " \"right\" x1\n", + " \"branch\" x3 [subtree elided]\n", + ) + ); + assert_eq!( + doc.hierarchy(false, 2), + concat!( + "Hierarchy\n", + "\"CHIP\"\n", + " \"left\" x1\n", + " \"branch\" x2 [children omitted]\n", + " \"right\" x1\n", + " \"branch\" x3 [children omitted]\n", + ) + ); +} + #[test] fn reference_changes_keep_unchanged_targets_and_old_edges_visible() { for pair in corpus() @@ -824,6 +862,95 @@ fn cli_uses_documented_exit_codes_and_accepts_paths_with_spaces() { ); } +#[test] +fn cli_color_preserves_plain_output_and_machine_formats() { + let directory = std::env::temp_dir().join(format!("pheon color {}", std::process::id())); + fs::create_dir_all(&directory).unwrap(); + struct Cleanup(PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(directory.clone()); + let old = directory.join("old.gds"); + let new = directory.join("new.gds"); + let with_changes = |name, shape, positions: std::ops::Range| { + let objects = positions + .map(|x| reference("leaf", x, 1)) + .chain([shape]) + .collect(); + layout(&[("CHIP", objects), ("leaf", vec![]), (name, vec![])]) + }; + fs::write(&old, with_changes("obsolete", square(), 0..2)).unwrap(); + fs::write(&new, with_changes("new", triangle(), 10..13)).unwrap(); + let command = || Command::new(env!("CARGO_BIN_EXE_pheon")); + let diff = |options: &[&str]| { + let output = command() + .arg("diff") + .arg(&old) + .arg(&new) + .args(options) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + String::from_utf8(output.stdout).unwrap() + }; + let plain = diff(&["--hierarchy", "mermaid"]); + let colored = diff(&["--hierarchy", "mermaid", "--color=always"]); + for span in [ + "\x1b[31m- obsolete", + "\x1b[32m+ new", + "\x1b[33m* CHIP", + "\x1b[31m-2 refs", + "\x1b[32m+3 refs", + "\x1b[33m1 polygon changed", + ] { + assert!(colored.contains(span), "{span:?} in {colored:?}"); + } + let strip_ansi = |text: &str| { + let mut parts = text.split("\x1b["); + let mut plain = parts.next().unwrap().to_string(); + for part in parts { + let (code, text) = part.split_once('m').unwrap(); + assert!(code.bytes().all(|b| b.is_ascii_digit() || b == b';')); + plain.push_str(text); + } + plain + }; + assert_eq!(strip_ansi(&colored), plain); + assert_eq!(diff(&["--hierarchy", "mermaid", "--color", "never"]), plain); + assert_eq!( + colored.split_once("```mermaid\n").unwrap().1, + plain.split_once("```mermaid\n").unwrap().1 + ); + assert_eq!( + diff(&["--color", "always", "--format", "json"]), + diff(&["--format", "json"]) + ); + + for (options, token) in [ + (&[][..], "\x1b[36mcell \"CHIP\""), + (&["--records"][..], "\x1b[36mBGNSTR"), + ] { + let dump = |choice| { + let output = command() + .arg("dump") + .arg(&old) + .args(options) + .args(["--color", choice]) + .output() + .unwrap(); + assert!(output.status.success()); + String::from_utf8(output.stdout).unwrap() + }; + let colored = dump("always"); + assert!(colored.contains(token), "{colored:?}"); + assert_eq!(strip_ansi(&colored), dump("auto")); + assert_eq!(dump("auto"), dump("never")); + } +} + #[test] fn cli_decodes_gzip_by_header_and_checks_the_trailer() { let directory = std::env::temp_dir().join(format!("pheon gzip {}", std::process::id())); @@ -1413,7 +1540,7 @@ fn combined_ascii_hierarchy_preserves_paths_to_changed_and_shared_cells() { " * changed x1 [reference changed]\n", " shared x1 [reference changed]\n", " * right x1\n", - " shared x1 [reference changed] [shown above]\n", + " shared x1 [reference changed]\n", ) ); }