Add terminal colors and clarify elided hierarchy branches
This commit is contained in:
parent
ed1e0595bc
commit
28b7f10f6e
3 changed files with 421 additions and 39 deletions
|
|
@ -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<u8, String> {
|
|||
_ => 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<u8, String> {
|
|||
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<u8, String> {
|
|||
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<u8, String> {
|
|||
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,
|
||||
_ => (),
|
||||
}
|
||||
|
|
|
|||
195
src/bin/pheon/color.rs
Normal file
195
src/bin/pheon/color.rs
Normal file
|
|
@ -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<ColorChoice, String> {
|
||||
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::<u16>().is_ok() && datatype.parse::<u16>().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::<usize>().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())
|
||||
}
|
||||
}
|
||||
|
|
@ -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");
|
||||
|
|
|
|||
Loading…
Reference in a new issue