feat(review): add scoped reports and native Git integration
Separate top, exact-cell and layer comparison scopes from display filters. Explain unique replacements and preserve full evidence, duplicate counts and incomplete-result handling. Version the dump profile and freeze canonical, hierarchy and diff goldens. Package native Git and textconv drivers with integration coverage for edits, additions, deletions, renames, quoted paths and errors. Document embedded metadata writing and validate deep hierarchies, large polygons and symbolic arrays.
This commit is contained in:
parent
e56026c3a6
commit
d8f764c7fe
4 changed files with 1191 additions and 97 deletions
|
|
@ -1,5 +1,6 @@
|
|||
use klamath_rs_ext::review::{
|
||||
Comparison, Document, dump_records, hierarchy, parse_layer, parse_layer_name, write_layer_names,
|
||||
Comparison, DisplayFilter, Document, Scope, dump_records, hierarchy, parse_layer,
|
||||
parse_layer_name, write_layer_names,
|
||||
};
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
|
|
@ -11,8 +12,8 @@ use std::{
|
|||
|
||||
const HELP: &str = "Usage:
|
||||
klamath dump FILE [--records]
|
||||
klamath diff OLD NEW [--hierarchy ascii|mermaid|none] [--max-changes N] [--depth N]
|
||||
klamath hierarchy FILE [--format ascii|mermaid] [--depth N]
|
||||
klamath diff OLD NEW [--top NAME] [--cell NAME] [--layer L/T]\n [--show-cell NAME] [--show-layer L/T] [--hierarchy ascii|mermaid|none]\n [--max-changes N] [--depth N]
|
||||
klamath hierarchy FILE [--format ascii|mermaid] [--depth N] [--top NAME]\n klamath git-diff [OPTIONS] -- PATH OLD OLD_OID OLD_MODE NEW NEW_OID NEW_MODE
|
||||
klamath name-layers INPUT OUTPUT --cell NAME --carrier L/T --name L:T:NAME ...
|
||||
|
||||
Object profile: ignore timestamps and element order, normalize polygon start/winding,
|
||||
|
|
@ -77,39 +78,66 @@ fn name_layers(args: &[OsString]) -> Result<u8, String> {
|
|||
Ok(0)
|
||||
}
|
||||
|
||||
fn stdout(output: &str) -> Result<(), String> {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(output.as_bytes())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn run() -> Result<u8, String> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args.is_empty() || args[0] == "--help" || args[0] == "-h" {
|
||||
print!("{HELP}");
|
||||
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 paths = match command {
|
||||
let expected = match command {
|
||||
"dump" | "hierarchy" => 1,
|
||||
"diff" => 2,
|
||||
"git-diff" => 7,
|
||||
_ => return Err(HELP.to_string()),
|
||||
};
|
||||
if args.len() <= paths {
|
||||
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 command == "diff" {
|
||||
let mut format = if compare {
|
||||
"none".to_string()
|
||||
} else {
|
||||
"ascii".to_string()
|
||||
};
|
||||
let mut max_changes = 100;
|
||||
let mut depth = 8;
|
||||
let mut i = paths + 1;
|
||||
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("--hierarchy") if command == "diff" => format = value(&args, &mut i)?,
|
||||
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("--max-changes") if command == "diff" => {
|
||||
Some("--max-changes") if compare => {
|
||||
max_changes = value(&args, &mut i)?
|
||||
.parse()
|
||||
.map_err(|_| "invalid change limit")?
|
||||
|
|
@ -117,71 +145,107 @@ fn run() -> Result<u8, String> {
|
|||
Some("--depth") if command != "dump" => {
|
||||
depth = value(&args, &mut i)?.parse().map_err(|_| "invalid depth")?
|
||||
}
|
||||
_ => return Err(format!("unknown option {:?}\n{HELP}", args[i])),
|
||||
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!(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 old_bytes = fs::read(&args[1]).map_err(|e| format!("{:?}: {e}", args[1]))?;
|
||||
let read = |path: &OsString| fs::read(path).map_err(|e| format!("{path:?}: {e}"));
|
||||
if raw {
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(dump_records(&old_bytes)?.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
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);
|
||||
}
|
||||
let old = Document::parse(&old_bytes)?;
|
||||
let (output, status) = match command {
|
||||
"dump" => (
|
||||
old.canonical_dump(),
|
||||
if old.issues.is_empty() { 0 } else { 2 },
|
||||
),
|
||||
"hierarchy" => {
|
||||
let mut output = hierarchy(&old, &old, None, format == "mermaid", depth);
|
||||
if format != "mermaid" {
|
||||
for issue in &old.issues {
|
||||
output.push_str(&format!("INCOMPLETE: {issue}\n"));
|
||||
}
|
||||
} else {
|
||||
for issue in &old.issues {
|
||||
eprintln!("INCOMPLETE: {issue}");
|
||||
}
|
||||
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}");
|
||||
}
|
||||
(output, if old.issues.is_empty() { 0 } else { 2 })
|
||||
}
|
||||
"diff" => {
|
||||
let new_bytes = fs::read(&args[2]).map_err(|e| format!("{:?}: {e}", args[2]))?;
|
||||
let new = Document::parse(&new_bytes)?;
|
||||
let diff = Comparison::between(&old, &new);
|
||||
let mut output = diff.text(max_changes);
|
||||
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");
|
||||
}
|
||||
}
|
||||
(output, diff.exit_code())
|
||||
}
|
||||
_ => unreachable!(),
|
||||
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 }])?)
|
||||
};
|
||||
io::stdout()
|
||||
.lock()
|
||||
.write_all(output.as_bytes())
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(status)
|
||||
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 main() -> ExitCode {
|
||||
|
|
|
|||
167
src/review.rs
167
src/review.rs
|
|
@ -10,8 +10,12 @@ use std::{
|
|||
|
||||
mod names;
|
||||
pub use names::{parse_layer, parse_layer_name, write_layer_names};
|
||||
mod selection;
|
||||
pub use selection::{DisplayFilter, Scope};
|
||||
mod changes;
|
||||
pub use changes::Replacement;
|
||||
|
||||
pub const PROFILE: &str = "klamath-object-v1";
|
||||
pub const PROFILE: &str = "klamath-object-v2";
|
||||
pub const LAYER_SENTINEL: &str = "KLAMATH_LAYER_NAMES_V1";
|
||||
pub type Layer = (u16, u16);
|
||||
pub type Bounds = [i32; 4];
|
||||
|
|
@ -41,6 +45,7 @@ pub struct Object<'a> {
|
|||
pub multiplicity: u64,
|
||||
key: Key<'a>,
|
||||
metadata: bool,
|
||||
issues: Vec<String>,
|
||||
}
|
||||
|
||||
impl Object<'_> {
|
||||
|
|
@ -71,6 +76,7 @@ pub struct Cell<'a> {
|
|||
pub end_offset: usize,
|
||||
pub objects: Vec<Object<'a>>,
|
||||
attributes: Vec<(u16, &'a [u8])>,
|
||||
issues: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -81,6 +87,10 @@ pub struct Document<'a> {
|
|||
/// Unsupported features or invalid reference graphs prevent an equality claim.
|
||||
pub issues: Vec<String>,
|
||||
header: Vec<(u16, &'a [u8])>,
|
||||
global_issues: Vec<String>,
|
||||
known_cells: BTreeSet<String>,
|
||||
pub scope: Scope,
|
||||
present: bool,
|
||||
}
|
||||
|
||||
fn error(offset: usize, message: impl std::fmt::Display) -> String {
|
||||
|
|
@ -299,6 +309,7 @@ fn object<'a>(records: &[Record<'a>], issues: &mut Vec<String>) -> Result<Object
|
|||
properties,
|
||||
},
|
||||
metadata: false,
|
||||
issues: Vec::new(),
|
||||
};
|
||||
let xy = object
|
||||
.field(RTAG_XY)
|
||||
|
|
@ -414,6 +425,10 @@ impl<'a> Document<'a> {
|
|||
layer_names: BTreeMap::new(),
|
||||
issues: Vec::new(),
|
||||
header: Vec::new(),
|
||||
global_issues: Vec::new(),
|
||||
known_cells: BTreeSet::new(),
|
||||
scope: Scope::default(),
|
||||
present: true,
|
||||
};
|
||||
let mut i = 2;
|
||||
let mut global_seen = BTreeSet::new();
|
||||
|
|
@ -446,7 +461,7 @@ impl<'a> Document<'a> {
|
|||
| RTAG_SRFNAME
|
||||
| RTAG_LIBSECUR
|
||||
) {
|
||||
doc.issues.push(error(
|
||||
doc.global_issues.push(error(
|
||||
record.offset,
|
||||
format!("unsupported library record 0x{:04x}", record.tag),
|
||||
));
|
||||
|
|
@ -483,6 +498,7 @@ impl<'a> Document<'a> {
|
|||
end_offset: 0,
|
||||
objects: Vec::new(),
|
||||
attributes: Vec::new(),
|
||||
issues: Vec::new(),
|
||||
};
|
||||
loop {
|
||||
let record = doc
|
||||
|
|
@ -508,15 +524,17 @@ impl<'a> Document<'a> {
|
|||
if i == doc.records.len() {
|
||||
return Err(error(offset, "missing ENDEL"));
|
||||
}
|
||||
cell.objects
|
||||
.push(object(&doc.records[start..=i], &mut doc.issues)?);
|
||||
let mut issues = Vec::new();
|
||||
let mut parsed = object(&doc.records[start..=i], &mut issues)?;
|
||||
parsed.issues = issues;
|
||||
cell.objects.push(parsed);
|
||||
i += 1;
|
||||
} else {
|
||||
if matches!(record.tag, RTAG_ENDLIB | RTAG_BGNSTR) {
|
||||
return Err(error(record.offset, "missing ENDSTR"));
|
||||
}
|
||||
if record.tag != RTAG_STRCLASS {
|
||||
doc.issues.push(error(
|
||||
cell.issues.push(error(
|
||||
record.offset,
|
||||
format!("unsupported cell record 0x{:04x}", record.tag),
|
||||
));
|
||||
|
|
@ -543,16 +561,17 @@ impl<'a> Document<'a> {
|
|||
}
|
||||
doc.header.sort();
|
||||
doc.read_metadata()?;
|
||||
doc.check_graph();
|
||||
doc.known_cells = doc.cells.keys().cloned().collect();
|
||||
doc.refresh_issues();
|
||||
Ok(doc)
|
||||
}
|
||||
|
||||
fn read_metadata(&mut self) -> Result<(), String> {
|
||||
for cell in self.cells.values_mut() {
|
||||
for object in cell.objects.iter().filter(|o| o.kind == RTAG_TEXT) {
|
||||
for object in cell.objects.iter_mut().filter(|o| o.kind == RTAG_TEXT) {
|
||||
let text = object.field(RTAG_STRING).unwrap();
|
||||
if text.starts_with(b"KLAMATH_LAYER_NAMES_") && text != LAYER_SENTINEL.as_bytes() {
|
||||
self.issues.push(error(
|
||||
object.issues.push(error(
|
||||
object.offset,
|
||||
"unsupported layer-name metadata version",
|
||||
));
|
||||
|
|
@ -595,8 +614,8 @@ impl<'a> Document<'a> {
|
|||
|
||||
fn check_graph(&mut self) {
|
||||
let edges = self.edges();
|
||||
for ((parent, target), _) in &edges {
|
||||
if !self.cells.contains_key(target) {
|
||||
for (parent, target) in edges.keys() {
|
||||
if !self.known_cells.contains(target) {
|
||||
self.issues
|
||||
.push(format!("cell {parent:?}: unresolved reference {target:?}"));
|
||||
}
|
||||
|
|
@ -646,7 +665,8 @@ impl<'a> Document<'a> {
|
|||
|
||||
pub fn canonical_dump(&self) -> String {
|
||||
let mut out = format!(
|
||||
"profile {PROFILE}\ncoordinates: integer database units; bounds: coordinate envelopes\n"
|
||||
"profile {PROFILE}\n{}\ncoordinates: integer database units; bounds: coordinate envelopes\n",
|
||||
self.scope.description()
|
||||
);
|
||||
for (tag, data) in &self.header {
|
||||
writeln!(out, "{}={}", tag_name(*tag), format_data(*tag, data)).unwrap();
|
||||
|
|
@ -706,8 +726,13 @@ fn format_records(records: &[Record<'_>]) -> String {
|
|||
#[derive(Debug)]
|
||||
pub struct ObjectChange {
|
||||
pub offset: usize,
|
||||
pub kind: u16,
|
||||
pub layer: Option<Layer>,
|
||||
pub bounds: Option<Bounds>,
|
||||
pub target: Option<String>,
|
||||
pub origin: Option<[i32; 2]>,
|
||||
pub width: Option<i32>,
|
||||
pub counts: Option<[u16; 2]>,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
|
|
@ -715,8 +740,25 @@ impl From<&Object<'_>> for ObjectChange {
|
|||
fn from(object: &Object<'_>) -> Self {
|
||||
Self {
|
||||
offset: object.offset,
|
||||
kind: object.kind,
|
||||
layer: object.layer,
|
||||
bounds: object.bounds,
|
||||
target: object.target.clone(),
|
||||
origin: object.field(RTAG_XY).map(|data| {
|
||||
[
|
||||
i32::from_be_bytes(data[..4].try_into().unwrap()),
|
||||
i32::from_be_bytes(data[4..8].try_into().unwrap()),
|
||||
]
|
||||
}),
|
||||
width: object
|
||||
.field(RTAG_WIDTH)
|
||||
.map(|data| i32::from_be_bytes(data.try_into().unwrap())),
|
||||
counts: object.target.as_ref().map(|_| {
|
||||
object
|
||||
.field(RTAG_COLROW)
|
||||
.map(|data| [integer(&data[..2]), integer(&data[2..])])
|
||||
.unwrap_or([1, 1])
|
||||
}),
|
||||
description: object.description(),
|
||||
}
|
||||
}
|
||||
|
|
@ -730,6 +772,7 @@ pub struct CellChange {
|
|||
pub attributes_changed: bool,
|
||||
pub removed: Vec<ObjectChange>,
|
||||
pub added: Vec<ObjectChange>,
|
||||
pub replacements: Vec<Replacement>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
@ -748,6 +791,9 @@ pub struct LibraryFieldChange {
|
|||
|
||||
#[derive(Debug)]
|
||||
pub struct Comparison {
|
||||
pub scope: Scope,
|
||||
/// Unchanged names are displayed once when objects on that layer change.
|
||||
pub layer_legend: BTreeMap<Layer, String>,
|
||||
pub library_fields: Vec<LibraryFieldChange>,
|
||||
pub layer_names: Vec<LayerNameChange>,
|
||||
pub cells: Vec<CellChange>,
|
||||
|
|
@ -757,11 +803,28 @@ pub struct Comparison {
|
|||
impl Comparison {
|
||||
pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self {
|
||||
let mut result = Self {
|
||||
scope: old.scope.clone(),
|
||||
layer_legend: old
|
||||
.layer_names
|
||||
.iter()
|
||||
.filter(|(pair, name)| new.layer_names.get(pair) == Some(*name))
|
||||
.map(|(pair, name)| (*pair, name.clone()))
|
||||
.collect(),
|
||||
library_fields: Vec::new(),
|
||||
layer_names: Vec::new(),
|
||||
cells: Vec::new(),
|
||||
issues: Vec::new(),
|
||||
};
|
||||
if old.scope != new.scope {
|
||||
result.issues.push("comparison scopes differ".to_string());
|
||||
}
|
||||
if old.present != new.present {
|
||||
result.library_fields.push(LibraryFieldChange {
|
||||
field: "presence".to_string(),
|
||||
old: vec![if old.present { "present" } else { "absent" }.to_string()],
|
||||
new: vec![if new.present { "present" } else { "absent" }.to_string()],
|
||||
});
|
||||
}
|
||||
for (side, doc) in [("old", old), ("new", new)] {
|
||||
result
|
||||
.issues
|
||||
|
|
@ -820,6 +883,7 @@ impl Comparison {
|
|||
attributes_changed: a.map(|c| &c.attributes) != b.map(|c| &c.attributes),
|
||||
removed: Vec::new(),
|
||||
added: Vec::new(),
|
||||
replacements: Vec::new(),
|
||||
};
|
||||
let a: Vec<_> = a
|
||||
.into_iter()
|
||||
|
|
@ -859,6 +923,7 @@ impl Comparison {
|
|||
|| !change.removed.is_empty()
|
||||
|| !change.added.is_empty()
|
||||
{
|
||||
change.replacements = changes::replacements(&change.removed, &change.added);
|
||||
result.cells.push(change);
|
||||
}
|
||||
}
|
||||
|
|
@ -884,7 +949,14 @@ impl Comparison {
|
|||
|
||||
/// Limit presentation only: the complete comparison has already been made.
|
||||
pub fn text(&self, max_objects: usize) -> String {
|
||||
let mut out = format!("profile {PROFILE}\n");
|
||||
self.text_filtered(max_objects, &DisplayFilter::default())
|
||||
}
|
||||
|
||||
pub fn text_filtered(&self, max_objects: usize, show: &DisplayFilter) -> String {
|
||||
let mut out = format!("profile {PROFILE}\n{}\n", self.scope.description());
|
||||
if show.cell.is_some() || show.layer.is_some() {
|
||||
writeln!(out, "display-only filter cell={:?} layer={:?}; status, totals and hierarchy are unfiltered", show.cell, show.layer).unwrap();
|
||||
}
|
||||
for change in &self.library_fields {
|
||||
writeln!(
|
||||
out,
|
||||
|
|
@ -904,13 +976,29 @@ impl Comparison {
|
|||
)
|
||||
.unwrap();
|
||||
}
|
||||
let changed_layers: BTreeSet<_> = self
|
||||
.cells
|
||||
.iter()
|
||||
.filter(|cell| show.cell.as_ref().is_none_or(|name| name == &cell.name))
|
||||
.flat_map(|cell| cell.removed.iter().chain(&cell.added))
|
||||
.filter_map(|object| object.layer)
|
||||
.filter(|layer| show.layer.is_none_or(|selected| selected == *layer))
|
||||
.collect();
|
||||
for layer in changed_layers {
|
||||
if let Some(name) = self.layer_legend.get(&layer) {
|
||||
writeln!(out, "layer {}/{} name={name:?}", layer.0, layer.1).unwrap();
|
||||
}
|
||||
}
|
||||
let total: usize = self
|
||||
.cells
|
||||
.iter()
|
||||
.map(|c| c.removed.len() + c.added.len())
|
||||
.sum();
|
||||
let mut shown = 0;
|
||||
let mut shown: usize = 0;
|
||||
for cell in &self.cells {
|
||||
if show.cell.as_ref().is_some_and(|name| name != &cell.name) {
|
||||
continue;
|
||||
}
|
||||
writeln!(
|
||||
out,
|
||||
"cell {:?} old@{:?} new@{:?}{}",
|
||||
|
|
@ -924,8 +1012,45 @@ impl Comparison {
|
|||
}
|
||||
)
|
||||
.unwrap();
|
||||
for (sign, objects) in [("-", &cell.removed), ("+", &cell.added)] {
|
||||
for object in objects {
|
||||
let mut paired_old = BTreeSet::new();
|
||||
let mut paired_new = BTreeSet::new();
|
||||
for replacement in &cell.replacements {
|
||||
let a = &cell.removed[replacement.removed];
|
||||
let b = &cell.added[replacement.added];
|
||||
if shown.saturating_add(2) <= max_objects
|
||||
&& show
|
||||
.layer
|
||||
.is_none_or(|layer| a.layer == Some(layer) && b.layer == Some(layer))
|
||||
{
|
||||
writeln!(out, " ~ {}", replacement.explanation).unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
" - @{} bbox={:?} {}",
|
||||
a.offset, a.bounds, a.description
|
||||
)
|
||||
.unwrap();
|
||||
writeln!(
|
||||
out,
|
||||
" + @{} bbox={:?} {}",
|
||||
b.offset, b.bounds, b.description
|
||||
)
|
||||
.unwrap();
|
||||
paired_old.insert(replacement.removed);
|
||||
paired_new.insert(replacement.added);
|
||||
shown += 2;
|
||||
}
|
||||
}
|
||||
for (sign, objects, paired) in [
|
||||
("-", &cell.removed, &paired_old),
|
||||
("+", &cell.added, &paired_new),
|
||||
] {
|
||||
for (index, object) in objects.iter().enumerate() {
|
||||
if paired.contains(&index) {
|
||||
continue;
|
||||
}
|
||||
if show.layer.is_some_and(|layer| object.layer != Some(layer)) {
|
||||
continue;
|
||||
}
|
||||
if shown < max_objects {
|
||||
writeln!(
|
||||
out,
|
||||
|
|
@ -1054,7 +1179,13 @@ pub fn hierarchy(
|
|||
rows.push((name.clone(), 0, None, false, true));
|
||||
}
|
||||
let status = |name: &String| {
|
||||
if direct.contains(name) {
|
||||
if !old.cells.contains_key(name) && !new.cells.contains_key(name) {
|
||||
if old.known_cells.contains(name) || new.known_cells.contains(name) {
|
||||
" [outside scope]"
|
||||
} else {
|
||||
" [unresolved]"
|
||||
}
|
||||
} else if direct.contains(name) {
|
||||
" [cell changed]"
|
||||
} else if affected.contains(name) {
|
||||
" [affected]"
|
||||
|
|
@ -1091,7 +1222,7 @@ pub fn hierarchy(
|
|||
.enumerate()
|
||||
.map(|(i, n)| (n, i))
|
||||
.collect();
|
||||
let mut out = "flowchart TD\n".to_string();
|
||||
let mut out = format!("flowchart TD\n %% {}\n", new.scope.description());
|
||||
for (name, id) in &ids {
|
||||
let label = format!("{name}{}", status(name));
|
||||
let label = label
|
||||
|
|
@ -1112,7 +1243,7 @@ pub fn hierarchy(
|
|||
}
|
||||
out
|
||||
} else {
|
||||
let mut out = String::new();
|
||||
let mut out = format!("{}\n", new.scope.description());
|
||||
for (name, depth, parent, seen, limited) in rows {
|
||||
let count = parent
|
||||
.map(|p| edge_label(&p, &name))
|
||||
|
|
|
|||
117
src/review/changes.rs
Normal file
117
src/review/changes.rs
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Replacement {
|
||||
pub removed: usize,
|
||||
pub added: usize,
|
||||
pub explanation: String,
|
||||
}
|
||||
|
||||
type Group = (u16, Option<Layer>, Option<String>, Option<Bounds>);
|
||||
|
||||
fn group(object: &ObjectChange, bounds: bool) -> Group {
|
||||
(
|
||||
object.kind,
|
||||
object.layer,
|
||||
object.target.clone(),
|
||||
if bounds && object.target.is_none() {
|
||||
object.bounds
|
||||
} else {
|
||||
None
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Pair only unique candidates in the remaining multisets. Ambiguous groups
|
||||
/// remain additions/removals; no identity or geometric equivalence is inferred.
|
||||
pub(super) fn replacements(old: &[ObjectChange], new: &[ObjectChange]) -> Vec<Replacement> {
|
||||
let (mut used_old, mut used_new) = (BTreeSet::new(), BTreeSet::new());
|
||||
let mut result = Vec::new();
|
||||
for bounds in [true, false] {
|
||||
let (mut a, mut b) = (
|
||||
BTreeMap::<Group, Vec<usize>>::new(),
|
||||
BTreeMap::<Group, Vec<usize>>::new(),
|
||||
);
|
||||
for (i, object) in old
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !used_old.contains(i))
|
||||
{
|
||||
a.entry(group(object, bounds)).or_default().push(i);
|
||||
}
|
||||
for (i, object) in new
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| !used_new.contains(i))
|
||||
{
|
||||
b.entry(group(object, bounds)).or_default().push(i);
|
||||
}
|
||||
for (key, indices) in a {
|
||||
if let (1, Some(others)) = (indices.len(), b.get(&key)) {
|
||||
if others.len() == 1 {
|
||||
let (i, j) = (indices[0], others[0]);
|
||||
result.push(Replacement {
|
||||
removed: i,
|
||||
added: j,
|
||||
explanation: explain(&old[i], &new[j]),
|
||||
});
|
||||
used_old.insert(i);
|
||||
used_new.insert(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
result.sort_by_key(|r| (r.removed, r.added));
|
||||
result
|
||||
}
|
||||
|
||||
fn explain(old: &ObjectChange, new: &ObjectChange) -> String {
|
||||
let mut parts = vec![format!(
|
||||
"{} modified{}",
|
||||
kind_name(old.kind),
|
||||
old.target
|
||||
.as_ref()
|
||||
.map(|t| format!(" target={t:?}"))
|
||||
.unwrap_or_default()
|
||||
)];
|
||||
if old.target.is_some() && old.origin != new.origin {
|
||||
if let (Some(a), Some(b)) = (old.origin, new.origin) {
|
||||
parts.push(format!(
|
||||
"origin {a:?} -> {b:?}, delta=({}, {}) dbu",
|
||||
i64::from(b[0]) - i64::from(a[0]),
|
||||
i64::from(b[1]) - i64::from(a[1])
|
||||
));
|
||||
}
|
||||
}
|
||||
if old.counts != new.counts {
|
||||
let counts = |c: Option<[u16; 2]>| {
|
||||
c.map(|[a, b]| format!("{a} x {b}"))
|
||||
.unwrap_or_else(|| "absent".to_string())
|
||||
};
|
||||
parts.push(format!(
|
||||
"columns/rows {} -> {}",
|
||||
counts(old.counts),
|
||||
counts(new.counts)
|
||||
));
|
||||
}
|
||||
if old.width != new.width {
|
||||
let width = |n: Option<i32>| {
|
||||
n.map(|n| n.to_string())
|
||||
.unwrap_or_else(|| "absent".to_string())
|
||||
};
|
||||
parts.push(format!(
|
||||
"width {} -> {} dbu",
|
||||
width(old.width),
|
||||
width(new.width)
|
||||
));
|
||||
}
|
||||
if old.bounds == new.bounds {
|
||||
parts.push("coordinate bounds unchanged".to_string());
|
||||
} else {
|
||||
parts.push(format!(
|
||||
"coordinate bounds {:?} -> {:?}",
|
||||
old.bounds, new.bounds
|
||||
));
|
||||
}
|
||||
parts.join("; ")
|
||||
}
|
||||
221
src/review/selection.rs
Normal file
221
src/review/selection.rs
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
use super::*;
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct Scope {
|
||||
pub top: Option<String>,
|
||||
pub cell: Option<String>,
|
||||
pub layer: Option<Layer>,
|
||||
}
|
||||
|
||||
/// Presentation filters never modify comparison status, totals, or hierarchy.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct DisplayFilter {
|
||||
pub cell: Option<String>,
|
||||
pub layer: Option<Layer>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
pub fn description(&self) -> String {
|
||||
let top = self
|
||||
.top
|
||||
.as_ref()
|
||||
.map(|s| format!("{s:?}"))
|
||||
.unwrap_or_else(|| "all".to_string());
|
||||
let cell = self
|
||||
.cell
|
||||
.as_ref()
|
||||
.map(|s| format!("{s:?}"))
|
||||
.unwrap_or_else(|| "all".to_string());
|
||||
let layer = self
|
||||
.layer
|
||||
.map(|(a, b)| format!("{a}/{b}"))
|
||||
.unwrap_or_else(|| "all".to_string());
|
||||
format!("scope top={top} cell={cell} layer={layer}")
|
||||
}
|
||||
|
||||
pub fn validate_pair(&self, old: &Document<'_>, new: &Document<'_>) -> Result<(), String> {
|
||||
for (kind, name) in [("top", &self.top), ("cell", &self.cell)] {
|
||||
if let Some(name) = name {
|
||||
if !old.cells.contains_key(name) && !new.cells.contains_key(name) {
|
||||
return Err(format!(
|
||||
"selected {kind} {name:?} exists in neither revision"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let (Some(top), Some(cell)) = (&self.top, &self.cell) {
|
||||
if !old.reachable(top).contains(cell) && !new.reachable(top).contains(cell) {
|
||||
return Err(format!(
|
||||
"selected cell {cell:?} is not reachable from {top:?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Document<'a> {
|
||||
/// A missing Git revision has no cells or declarations. Retain the other
|
||||
/// revision's library header to avoid inventing a unit/name change.
|
||||
pub fn empty_like(&self) -> Self {
|
||||
Self {
|
||||
records: Vec::new(),
|
||||
cells: BTreeMap::new(),
|
||||
layer_names: BTreeMap::new(),
|
||||
issues: Vec::new(),
|
||||
header: self.header.clone(),
|
||||
global_issues: Vec::new(),
|
||||
known_cells: BTreeSet::new(),
|
||||
scope: self.scope.clone(),
|
||||
present: false,
|
||||
}
|
||||
}
|
||||
fn reachable(&self, root: &str) -> BTreeSet<String> {
|
||||
let mut found = BTreeSet::new();
|
||||
let mut pending = vec![root.to_string()];
|
||||
while let Some(name) = pending.pop() {
|
||||
if let Some(cell) = self.cells.get(&name) {
|
||||
if found.insert(name) {
|
||||
pending.extend(cell.objects.iter().filter_map(|o| o.target.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
pub(super) fn refresh_issues(&mut self) {
|
||||
self.issues = self.global_issues.clone();
|
||||
for (name, cell) in &self.cells {
|
||||
for issue in cell
|
||||
.issues
|
||||
.iter()
|
||||
.chain(cell.objects.iter().flat_map(|o| &o.issues))
|
||||
{
|
||||
self.issues.push(format!("cell {name:?}: {issue}"));
|
||||
}
|
||||
}
|
||||
self.check_graph();
|
||||
}
|
||||
|
||||
/// Project a parsed document. Missing selectors are allowed only for one
|
||||
/// side of a comparison, after Scope::validate_pair has checked both sides.
|
||||
pub fn selected(mut self, scope: &Scope, allow_missing: bool) -> Result<Self, String> {
|
||||
if self.scope != Scope::default() {
|
||||
return Err("document is already scoped; combine selectors in one Scope".to_string());
|
||||
}
|
||||
if !allow_missing {
|
||||
scope.validate_pair(&self, &self)?;
|
||||
}
|
||||
let mut wanted = scope
|
||||
.top
|
||||
.as_ref()
|
||||
.map(|t| self.reachable(t))
|
||||
.unwrap_or_else(|| self.cells.keys().cloned().collect());
|
||||
if let Some(cell) = &scope.cell {
|
||||
wanted.retain(|n| n == cell);
|
||||
}
|
||||
// Determine layer coverage before projecting cells: exact-cell scopes
|
||||
// still need to know whether a referenced definition uses this layer.
|
||||
let relevant = scope.layer.map(|layer| {
|
||||
let mut relevant: BTreeSet<_> = self
|
||||
.cells
|
||||
.iter()
|
||||
.filter(|(_, c)| {
|
||||
!c.issues.is_empty()
|
||||
|| c.objects.iter().any(|o| {
|
||||
!o.metadata
|
||||
&& (o.layer == Some(layer)
|
||||
|| (!o.issues.is_empty() && o.layer.is_none()))
|
||||
})
|
||||
})
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
let mut parents = BTreeMap::<String, Vec<String>>::new();
|
||||
for (parent, cell) in &self.cells {
|
||||
for o in &cell.objects {
|
||||
if let Some(target) = &o.target {
|
||||
parents
|
||||
.entry(target.clone())
|
||||
.or_default()
|
||||
.push(parent.clone());
|
||||
if !self.known_cells.contains(target) {
|
||||
relevant.insert(parent.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pending: Vec<_> = relevant.iter().cloned().collect();
|
||||
// A cycle cannot be proven to have no effect on a layer. Preserve
|
||||
// cycles (and their descendants) so graph validation remains visible.
|
||||
let mut indegree: BTreeMap<_, usize> =
|
||||
self.cells.keys().map(|n| (n.clone(), 0)).collect();
|
||||
for cell in self.cells.values() {
|
||||
for target in cell.objects.iter().filter_map(|o| o.target.as_ref()) {
|
||||
if let Some(n) = indegree.get_mut(target) {
|
||||
*n += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut ready: Vec<_> = indegree
|
||||
.iter()
|
||||
.filter(|(_, n)| **n == 0)
|
||||
.map(|(n, _)| n.clone())
|
||||
.collect();
|
||||
while let Some(name) = ready.pop() {
|
||||
for target in self.cells[&name]
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| o.target.as_ref())
|
||||
{
|
||||
if let Some(n) = indegree.get_mut(target) {
|
||||
*n -= 1;
|
||||
if *n == 0 {
|
||||
ready.push(target.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (name, _) in indegree.iter().filter(|(_, n)| **n != 0) {
|
||||
if relevant.insert(name.clone()) {
|
||||
pending.push(name.clone());
|
||||
}
|
||||
}
|
||||
while let Some(child) = pending.pop() {
|
||||
for parent in parents.get(&child).into_iter().flatten() {
|
||||
if relevant.insert(parent.clone()) {
|
||||
pending.push(parent.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
relevant
|
||||
});
|
||||
self.cells.retain(|name, _| {
|
||||
wanted.contains(name) && relevant.as_ref().is_none_or(|r| r.contains(name))
|
||||
});
|
||||
if let (Some(layer), Some(relevant)) = (scope.layer, relevant) {
|
||||
for cell in self.cells.values_mut() {
|
||||
cell.objects.retain(|o| {
|
||||
o.metadata
|
||||
|| o.layer == Some(layer)
|
||||
|| o.target
|
||||
.as_ref()
|
||||
.is_some_and(|t| relevant.contains(t) || !self.known_cells.contains(t))
|
||||
|| (!o.issues.is_empty() && o.layer.is_none())
|
||||
});
|
||||
}
|
||||
self.layer_names.retain(|pair, _| *pair == layer);
|
||||
} else if scope.top.is_some() || scope.cell.is_some() {
|
||||
let layers: BTreeSet<_> = self
|
||||
.cells
|
||||
.values()
|
||||
.flat_map(|c| &c.objects)
|
||||
.filter(|o| !o.metadata)
|
||||
.filter_map(|o| o.layer)
|
||||
.collect();
|
||||
self.layer_names.retain(|pair, _| layers.contains(pair));
|
||||
}
|
||||
self.scope = scope.clone();
|
||||
self.refresh_issues();
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue