Accept embedded layer names in CLI selectors

Resolve scope and display selectors against both revisions before projection. Keep display-only selection on the large-file comparison path and list numeric choices for ambiguous names.
This commit is contained in:
Jan Petykiewicz 2026-11-18 23:07:22 -08:00
commit 87683db7e8
5 changed files with 209 additions and 35 deletions

View file

@ -103,7 +103,7 @@ pheon diff before.gds after.gds --cell RESONATOR
| --- | --- | | --- | --- |
| `--top NAME` | The named cell and its reachable descendants in each revision. | | `--top NAME` | The named cell and its reachable descendants in each revision. |
| `--cell NAME` | One cell, including its references, without its descendants. | | `--cell NAME` | One cell, including its references, without its descendants. |
| `--layer L/T` | Objects on a numeric layer/type pair, plus references leading to that layer. | | `--layer L/T\|NAME` | Objects on the selected layer/type pair, plus references leading to that layer. |
Selectors combine: `--top CHIP --cell RESONATOR` selects that cell within CHIP's Selectors combine: `--top CHIP --cell RESONATOR` selects that cell within CHIP's
subtree. A name absent from both revisions is an error; presence on only one subtree. A name absent from both revisions is an error; presence on only one
@ -112,10 +112,14 @@ layer, but library fields and metadata-version diagnostics remain relevant.
The complete input is parsed before scope selection, so malformed records The complete input is parsed before scope selection, so malformed records
outside the scope still fail the command. outside the scope still fail the command.
Both `--layer` and `--show-layer` accept exact, case-sensitive names from the
embedded metadata in either revision. If a name refers to several numeric pairs,
Pheon lists the choices. A valid numeric pair always selects that pair directly.
## Control report detail ## Control report detail
```sh ```sh
pheon diff before.gds after.gds --show-cell RESONATOR --show-layer 1/0 pheon diff before.gds after.gds --show-cell RESONATOR --show-layer WG
pheon diff before.gds after.gds --hierarchy mermaid --depth 4 pheon diff before.gds after.gds --hierarchy mermaid --depth 4
``` ```

View file

@ -4,8 +4,9 @@ mod color;
use flate2::read::MultiGzDecoder; use flate2::read::MultiGzDecoder;
use pheon::review::report::{ReportInputs, ReportOptions, failure_report}; use pheon::review::report::{ReportInputs, ReportOptions, failure_report};
use pheon::review::{ use pheon::review::{
Comparison, Diagnostic, Document, Outcome, RevisionPair, Side, TextComparison, dump_records, Comparison, Diagnostic, Document, Layer, Outcome, RevisionPair, Side, TextComparison,
names::{parse_layer, parse_layer_name, write_layer_names}, dump_records,
names::{parse_layer, parse_layer_name, resolve_layer_name, write_layer_names},
selection::{DisplayFilter, Scope}, selection::{DisplayFilter, Scope},
}; };
use std::{ use std::{
@ -21,7 +22,7 @@ use termcolor::ColorChoice;
const HELP: &str = "Usage: const HELP: &str = "Usage:
pheon dump FILE [--records] [--color auto|always|never] 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] pheon diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T|NAME]\n [--show-cell NAME] [--show-layer L/T|NAME] [--hierarchy ascii|mermaid|none|graph]\n [--max-changes N] [--depth N] [--format text|json]
[--color auto|always|never] [--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 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 ... pheon name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
@ -145,10 +146,55 @@ fn parse_revision(bytes: Option<&[u8]>, side: Side) -> Result<Option<Document<'_
.transpose() .transpose()
} }
#[derive(Default)]
struct Selectors {
scope: Scope,
filter: DisplayFilter,
layer_name: Option<String>,
show_layer_name: Option<String>,
}
fn layer_argument(value: String) -> (Option<Layer>, Option<String>) {
match parse_layer(&value) {
Ok(pair) => (Some(pair), None),
Err(_) => (None, Some(value)),
}
}
impl Selectors {
fn resolve_layers(
&mut self,
resolve: impl Fn(&str) -> Result<Layer, String>,
) -> Result<(), Diagnostic> {
for (flag, code, name, pair) in [
(
"--layer",
"invalid_scope",
&self.layer_name,
&mut self.scope.layer,
),
(
"--show-layer",
"command_error",
&self.show_layer_name,
&mut self.filter.layer,
),
] {
if let Some(name) = name {
*pair = Some(
resolve(name)
.map_err(|error| Diagnostic::new(code, format!("{flag} {error}"), None))?,
);
}
}
Ok(())
}
}
fn prepare_comparison<T>( fn prepare_comparison<T>(
old_path: Option<&OsStr>, old_path: Option<&OsStr>,
new_path: Option<&OsStr>, new_path: Option<&OsStr>,
scope: &Scope, selectors: &mut Selectors,
compare: impl FnOnce(&Document<'_>, &Document<'_>) -> T, compare: impl FnOnce(&Document<'_>, &Document<'_>) -> T,
compare_pair: impl FnOnce(RevisionPair<'_>) -> T, compare_pair: impl FnOnce(RevisionPair<'_>) -> T,
) -> Result<T, Diagnostic> { ) -> Result<T, Diagnostic> {
@ -168,10 +214,13 @@ fn prepare_comparison<T>(
.as_deref() .as_deref()
.zip(new_bytes.as_deref()) .zip(new_bytes.as_deref())
.filter(|(old, new)| old.len().min(new.len()) >= PARALLEL_PARSE_MIN_BYTES); .filter(|(old, new)| old.len().min(new.len()) >= PARALLEL_PARSE_MIN_BYTES);
if scope == &Scope::default() if selectors.scope == Scope::default()
&& selectors.layer_name.is_none()
&& let Some((old, new)) = large_pair && let Some((old, new)) = large_pair
{ {
return RevisionPair::parse(old, new).map(compare_pair); let pair = RevisionPair::parse(old, new)?;
selectors.resolve_layers(|name| pair.resolve_layer_name(name))?;
return Ok(compare_pair(pair));
} }
let parse_old = || parse_revision(old_bytes.as_deref(), Side::Old); let parse_old = || parse_revision(old_bytes.as_deref(), Side::Old);
let parse_new = || parse_revision(new_bytes.as_deref(), Side::New); let parse_new = || parse_revision(new_bytes.as_deref(), Side::New);
@ -206,6 +255,9 @@ fn prepare_comparison<T>(
)); ));
} }
}; };
selectors
.resolve_layers(|name| resolve_layer_name(name, [&old.layer_names, &new.layer_names]))?;
let scope = &selectors.scope;
if scope == &Scope::default() { if scope == &Scope::default() {
return Ok(compare(&old, &new)); return Ok(compare(&old, &new));
} }
@ -221,24 +273,35 @@ fn prepare_comparison<T>(
Ok(compare(&old, &new)) Ok(compare(&old, &new))
} }
fn json_diff(paths: &[OsString], scope: &Scope, options: &ReportOptions) -> Result<u8, String> { fn json_diff(
paths: &[OsString],
selectors: &mut Selectors,
max_objects: Option<usize>,
hierarchy: bool,
) -> Result<u8, String> {
let inputs = ReportInputs { let inputs = ReportInputs {
old: Some(PathBuf::from(&paths[0])), old: Some(PathBuf::from(&paths[0])),
new: Some(PathBuf::from(&paths[1])), new: Some(PathBuf::from(&paths[1])),
}; };
let (result, outcome) = match prepare_comparison( let comparison = prepare_comparison(
Some(&paths[0]), Some(&paths[0]),
Some(&paths[1]), Some(&paths[1]),
scope, selectors,
Comparison::between, Comparison::between,
|pair| pair.compare(), |pair| pair.compare(),
) { );
let options = ReportOptions {
filter: selectors.filter.clone(),
max_objects,
hierarchy,
};
let (result, outcome) = match comparison {
Ok(diff) => ( Ok(diff) => (
json_stdout(|output| diff.write_json_report(output, &inputs, options)), json_stdout(|output| diff.write_json_report(output, &inputs, &options)),
diff.outcome(), diff.outcome(),
), ),
Err(error) => { Err(error) => {
let report = failure_report(&inputs, scope, options, &error); let report = failure_report(&inputs, &selectors.scope, &options, &error);
( (
json_stdout(|output| serde_json::to_writer_pretty(output, &report)), json_stdout(|output| serde_json::to_writer_pretty(output, &report)),
Outcome::Failed, Outcome::Failed,
@ -275,8 +338,7 @@ fn run(args: &[OsString]) -> Result<u8, String> {
let compare = command == "diff" || command == "git-diff"; let compare = command == "diff" || command == "git-diff";
let color_supported = compare || command == "dump"; let color_supported = compare || command == "dump";
let mut color_choice = ColorChoice::Auto; let mut color_choice = ColorChoice::Auto;
let mut scope = Scope::default(); let mut selectors = Selectors::default();
let mut show = DisplayFilter::default();
let mut raw = false; let mut raw = false;
let mut format = if compare { let mut format = if compare {
"none".to_string() "none".to_string()
@ -310,12 +372,16 @@ fn run(args: &[OsString]) -> Result<u8, String> {
Some(s) if color_supported && s.starts_with("--color=") => { Some(s) if color_supported && s.starts_with("--color=") => {
color_choice = color::parse_choice(&s["--color=".len()..])?; color_choice = color::parse_choice(&s["--color=".len()..])?;
} }
Some("--top") => scope.top = Some(value(args, &mut i)?), Some("--top") => selectors.scope.top = Some(value(args, &mut i)?),
Some("--cell") => scope.cell = Some(value(args, &mut i)?), Some("--cell") => selectors.scope.cell = Some(value(args, &mut i)?),
Some("--layer") => scope.layer = Some(parse_layer(&value(args, &mut i)?)?), Some("--layer") => {
Some("--show-cell") if compare => show.cell = Some(value(args, &mut i)?), (selectors.scope.layer, selectors.layer_name) =
layer_argument(value(args, &mut i)?);
}
Some("--show-cell") if compare => selectors.filter.cell = Some(value(args, &mut i)?),
Some("--show-layer") if compare => { Some("--show-layer") if compare => {
show.layer = Some(parse_layer(&value(args, &mut i)?)?) (selectors.filter.layer, selectors.show_layer_name) =
layer_argument(value(args, &mut i)?);
} }
Some("--hierarchy") if compare => 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 == "hierarchy" => format = value(args, &mut i)?,
@ -347,15 +413,7 @@ fn run(args: &[OsString]) -> Result<u8, String> {
"JSON accepts --hierarchy graph|none; --depth applies to text output".to_string(), "JSON accepts --hierarchy graph|none; --depth applies to text output".to_string(),
); );
} }
return json_diff( return json_diff(&paths, &mut selectors, explicit_max, format == "graph");
&paths,
&scope,
&ReportOptions {
filter: show,
max_objects: explicit_max,
hierarchy: format == "graph",
},
);
} }
if !matches!(format.as_str(), "ascii" | "mermaid" | "none") if !matches!(format.as_str(), "ascii" | "mermaid" | "none")
|| (command == "hierarchy" && format == "none") || (command == "hierarchy" && format == "none")
@ -364,7 +422,7 @@ fn run(args: &[OsString]) -> Result<u8, String> {
} }
let read = |path: &OsString| read_input(path).map_err(|error| error.message); let read = |path: &OsString| read_input(path).map_err(|error| error.message);
if raw { if raw {
if scope != Scope::default() { if selectors.scope != Scope::default() || selectors.layer_name.is_some() {
return Err("record dumps do not accept object scope selectors".to_string()); return Err("record dumps do not accept object scope selectors".to_string());
} }
color::print( color::print(
@ -377,7 +435,11 @@ fn run(args: &[OsString]) -> Result<u8, String> {
} }
if !compare { if !compare {
let bytes = read(&paths[0])?; let bytes = read(&paths[0])?;
let doc = Document::parse(&bytes)?.selected(&scope, false)?; let doc = Document::parse(&bytes)?;
selectors
.resolve_layers(|name| resolve_layer_name(name, [&doc.layer_names]))
.map_err(|error| error.message)?;
let doc = doc.selected(&selectors.scope, false)?;
if command == "dump" { if command == "dump" {
color::print(&doc.canonical_dump(), color::Report::Dump, color_choice) color::print(&doc.canonical_dump(), color::Report::Dump, color_choice)
.map_err(|error| error.to_string())?; .map_err(|error| error.to_string())?;
@ -395,7 +457,7 @@ fn run(args: &[OsString]) -> Result<u8, String> {
let diff = prepare_comparison( let diff = prepare_comparison(
(!old_missing).then_some(paths[if git { 1 } else { 0 }].as_os_str()), (!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()), (!new_missing).then_some(paths[if git { 4 } else { 1 }].as_os_str()),
&scope, &mut selectors,
TextComparison::between, TextComparison::between,
|pair| pair.compare_text(), |pair| pair.compare_text(),
) )
@ -423,12 +485,12 @@ fn run(args: &[OsString]) -> Result<u8, String> {
if format == "ascii" { if format == "ascii" {
output.push_str(&diff.render_text_with_ascii_hierarchy( output.push_str(&diff.render_text_with_ascii_hierarchy(
max_changes, max_changes,
&show, &selectors.filter,
show_library_presence, show_library_presence,
depth, depth,
)); ));
} else { } else {
output.push_str(&diff.render_text(max_changes, &show, show_library_presence)); output.push_str(&diff.render_text(max_changes, &selectors.filter, show_library_presence));
if format == "mermaid" { if format == "mermaid" {
output.push_str("Hierarchy\n```mermaid\n"); output.push_str("Hierarchy\n```mermaid\n");
output.push_str(&diff.hierarchy(true, depth)); output.push_str(&diff.hierarchy(true, depth));

View file

@ -68,6 +68,30 @@ pub fn parse_layer(value: &str) -> Result<Layer, String> {
Ok((decimal(a)?, decimal(b)?)) Ok((decimal(a)?, decimal(b)?))
} }
/// Find the unique numeric pair for an exact name across the supplied revisions.
pub fn resolve_layer_name<'a>(
name: &str,
revisions: impl IntoIterator<Item = &'a BTreeMap<Layer, String>>,
) -> Result<Layer, String> {
let matches: BTreeSet<_> = revisions
.into_iter()
.flatten()
.filter_map(|(&pair, label)| (label == name).then_some(pair))
.collect();
match matches.len() {
0 => Err(format!("unknown layer name {name:?}")),
1 => Ok(*matches.first().unwrap()),
_ => {
let choices = matches
.into_iter()
.map(|(layer, datatype)| format!("{layer}/{datatype}"))
.collect::<Vec<_>>()
.join(", ");
Err(format!("ambiguous layer name {name:?} (choose {choices})"))
}
}
}
fn decimal(value: &str) -> Result<u16, String> { fn decimal(value: &str) -> Result<u16, String> {
if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) { if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
return Err("layer numbers must be unsigned decimal integers".to_string()); return Err("layer numbers must be unsigned decimal integers".to_string());

View file

@ -184,6 +184,11 @@ impl<'a> RevisionPair<'a> {
Comparison::collect(&self.old, &self.new, &self.reused_cells, true) Comparison::collect(&self.old, &self.new, &self.reused_cells, true)
} }
/// Resolve a layer name from the embedded metadata in either revision.
pub fn resolve_layer_name(&self, name: &str) -> Result<Layer, String> {
names::resolve_layer_name(name, [&self.old.layer_names, &self.new.layer_names])
}
pub fn compare_text(self) -> TextComparison { pub fn compare_text(self) -> TextComparison {
TextComparison::collect(&self.old, &self.new, &self.reused_cells) TextComparison::collect(&self.old, &self.new, &self.reused_cells)
} }

View file

@ -2164,6 +2164,85 @@ fn cli_scope_and_display_filters_have_distinct_exit_behavior() {
fs::remove_dir_all(directory).unwrap(); fs::remove_dir_all(directory).unwrap();
} }
#[test]
fn cli_resolves_layer_names_before_applying_scope_and_display_filters() {
let directory = std::env::temp_dir().join(format!("pheon-named-layer-{}", 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 fixture = |shape, text, name| {
layout(&[
("CHIP", vec![shape, label((2, 0), text)]),
(
"legend",
vec![label((900, 7), LAYER_SENTINEL), label((900, 7), name)],
),
])
};
fs::write(&old, fixture(square(), "before", "1:0:WG")).unwrap();
fs::write(&new, fixture(triangle(), "after", "1:0:CORE")).unwrap();
let command = || Command::new(env!("CARGO_BIN_EXE_pheon"));
let diff = |options: &[&str]| {
command()
.arg("diff")
.arg(&old)
.arg(&new)
.args(options)
.output()
.unwrap()
};
for (option, name) in [("--layer", "WG"), ("--show-layer", "CORE")] {
for format in ["text", "json"] {
let named = diff(&[option, name, "--cell", "CHIP", "--format", format]);
let numeric = diff(&[option, "1/0", "--cell", "CHIP", "--format", format]);
assert_eq!(
named.status.code(),
Some(1),
"{}",
String::from_utf8_lossy(&named.stderr)
);
assert_eq!(named.stdout, numeric.stdout);
}
}
let dump = |layer| {
let output = command()
.arg("dump")
.arg(&old)
.args(["--layer", layer])
.output()
.unwrap();
assert!(output.status.success());
output.stdout
};
assert_eq!(dump("WG"), dump("1/0"));
let unknown = diff(&["--show-layer", "wg", "--format", "json"]);
assert_eq!(unknown.status.code(), Some(2));
let report: serde_json::Value = serde_json::from_slice(&unknown.stdout).unwrap();
assert_eq!(report["diagnostics"][0]["code"], "command_error");
assert_eq!(
report["diagnostics"][0]["message"],
"--show-layer unknown layer name \"wg\""
);
fs::write(&new, fixture(triangle(), "after", "2:0:WG")).unwrap();
let ambiguous = diff(&["--layer", "WG"]);
assert_eq!(ambiguous.status.code(), Some(2));
assert_eq!(
String::from_utf8(ambiguous.stderr).unwrap().trim_end(),
"pheon: --layer ambiguous layer name \"WG\" (choose 1/0, 2/0)"
);
assert_eq!(diff(&["--layer", "1/0"]).status.code(), Some(1));
}
#[test] #[test]
fn large_polygons_and_billion_instance_arrays_stay_compact() { fn large_polygons_and_billion_instance_arrays_stay_compact() {
let mut points = vec![[0, 0], [0, 1]]; let mut points = vec![[0, 0], [0, 1]];