Simplify text diff and hierarchy reports

Use signed cell rows and keep whole-cell contents out of the text diff. Group reference changes, fold redundant terminal edges into the cell list, and inline one-off layer names. Count identical unmatched objects while retaining occurrence-based display limits.
This commit is contained in:
Jan Petykiewicz 2026-11-18 20:12:42 -08:00
commit ed1e0595bc

View file

@ -886,7 +886,7 @@ impl<'a> Document<'a> {
pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
let revision = Revision::from_document(self);
render_hierarchy(&revision, &revision, None, mermaid, max_depth)
render_hierarchy(&revision, &revision, None, mermaid, max_depth, None)
}
pub fn canonical_dump(&self) -> String {
@ -1194,7 +1194,7 @@ impl Revision {
pub struct Comparison {
pub old: Revision,
pub new: Revision,
/// Unchanged names are displayed once when objects on that layer change.
/// Unchanged layer names available to the text report.
pub layer_legend: BTreeMap<Layer, String>,
pub library_changes: Vec<LibraryChange>,
pub layer_names: Vec<LayerNameChange>,
@ -1202,12 +1202,10 @@ pub struct Comparison {
pub diagnostics: Vec<Diagnostic>,
}
/// A comparison for text and hierarchy reports. Layered objects in whole-cell
/// changes contribute to the cell's object count.
/// A comparison for text and hierarchy reports.
#[derive(Debug)]
pub struct TextComparison {
comparison: Comparison,
whole_cell_objects: BTreeMap<String, usize>,
}
impl TextComparison {
@ -1216,11 +1214,8 @@ impl TextComparison {
}
fn collect(old: &Document<'_>, new: &Document<'_>, reused_cells: &BTreeSet<&str>) -> Self {
let mut whole_cell_objects = BTreeMap::new();
let comparison = Comparison::collect(old, new, reused_cells, Some(&mut whole_cell_objects));
Self {
comparison,
whole_cell_objects,
comparison: Comparison::collect(old, new, reused_cells, false),
}
}
@ -1230,11 +1225,23 @@ impl TextComparison {
show: &DisplayFilter,
show_library_presence: bool,
) -> String {
self.comparison.render_text_with_counts(
self.comparison
.render_text(max_objects, show, show_library_presence)
}
/// Render the cell changes and their ASCII hierarchy together.
pub fn render_text_with_ascii_hierarchy(
&self,
max_objects: usize,
show: &DisplayFilter,
show_library_presence: bool,
max_depth: usize,
) -> String {
self.comparison.render_text_with_ascii_hierarchy(
max_objects,
show,
show_library_presence,
&self.whole_cell_objects,
max_depth,
)
}
@ -1249,14 +1256,14 @@ impl TextComparison {
impl Comparison {
pub fn between(old: &Document<'_>, new: &Document<'_>) -> Self {
Self::collect(old, new, &BTreeSet::new(), None)
Self::collect(old, new, &BTreeSet::new(), true)
}
fn collect(
old: &Document<'_>,
new: &Document<'_>,
reused_cells: &BTreeSet<&str>,
mut whole_cell_objects: Option<&mut BTreeMap<String, usize>>,
include_whole_cell_objects: bool,
) -> Self {
let mut result = Self {
old: Revision::from_document(old),
@ -1350,27 +1357,20 @@ impl Comparison {
added: Vec::new(),
replacements: Vec::new(),
};
if let Some(counts) = whole_cell_objects.as_deref_mut()
&& (a.is_none() || b.is_none())
{
if !include_whole_cell_objects && (a.is_none() || b.is_none()) {
let details = if a.is_some() {
&mut change.removed
} else {
&mut change.added
};
let mut count = 0;
for object in a.or(b).into_iter().flat_map(|cell| &cell.objects) {
if object.metadata {
continue;
}
count += 1;
if object.layer.is_none() || object.target.is_some() {
details.push(object.into());
}
}
if count != details.len() {
counts.insert(name.clone(), count);
}
// The hierarchy uses the changed reference targets.
details.extend(
a.or(b)
.into_iter()
.flat_map(|cell| &cell.objects)
.filter(|object| !object.metadata && object.target.is_some())
.map(ObjectChange::from),
);
result.cells.push(change);
continue;
}
@ -1428,9 +1428,16 @@ impl Comparison {
}
}
/// Render the affected hierarchy. ASCII output is empty when no cells changed.
/// Render the affected hierarchy. ASCII output shows relationships between cells.
pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String {
render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth)
render_hierarchy(
&self.old,
&self.new,
Some(&self.cells),
mermaid,
max_depth,
None,
)
}
/// Limit presentation only: the complete comparison has already been made.
@ -1450,45 +1457,36 @@ impl Comparison {
show: &DisplayFilter,
show_library_presence: bool,
) -> String {
self.render_text_with_counts(max_objects, show, show_library_presence, &BTreeMap::new())
self.render_text_report(max_objects, show, show_library_presence, None)
}
fn render_text_with_counts(
/// Render the cell changes and omit simple hierarchy edges already shown there.
pub fn render_text_with_ascii_hierarchy(
&self,
max_objects: usize,
show: &DisplayFilter,
show_library_presence: bool,
whole_cell_objects: &BTreeMap<String, usize>,
max_depth: usize,
) -> String {
let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize);
for cell in &self.cells {
match (&cell.old, &cell.new) {
(None, Some(_)) => added += 1,
(Some(_), None) => removed += 1,
_ => modified += 1,
}
}
let mut out = match self.outcome() {
self.render_text_report(max_objects, show, show_library_presence, Some(max_depth))
}
fn render_text_report(
&self,
max_objects: usize,
show: &DisplayFilter,
show_library_presence: bool,
ascii_depth: Option<usize>,
) -> String {
let outcome = self.outcome();
let mut out = match outcome {
Outcome::Equal => "Equal",
Outcome::Different => "Different",
Outcome::Incomplete { .. } => "Incomplete",
Outcome::Failed => "Failed",
}
.to_string();
let mut cell_counts = [
(modified, "modified"),
(added, "added"),
(removed, "removed"),
]
.into_iter()
.filter(|(count, _)| *count != 0);
if let Some((count, action)) = cell_counts.next() {
let noun = if count == 1 { "cell" } else { "cells" };
write!(out, " · {count} {noun} {action}").unwrap();
for (count, action) in cell_counts {
write!(out, ", {count} {action}").unwrap();
}
}
let headline_end = out.len();
let library_changes = self.library_changes.iter().filter(|change| {
show_library_presence || !matches!(change, LibraryChange::Presence { .. })
});
@ -1543,51 +1541,49 @@ impl Comparison {
.unwrap();
}
let body_start = out.len();
let mut shown_layers = BTreeSet::new();
let mut removed_cells = String::new();
let mut added_cells = String::new();
let mut layers = changes::LayerRows::new(&self.layer_legend);
let mut annotations = Vec::new();
let mut covered_edges = BTreeSet::new();
let mut detail_total = 0;
let mut selected = 0;
let mut shown: usize = 0;
let mut hidden_cell_changes = 0;
let presence = |action, count| {
let objects = if count == 1 { "object" } else { "objects" };
Cow::Owned(format!(" ({action}, {count} {objects})"))
};
let visible =
|object: &ObjectChange| show.layer.is_none_or(|layer| object.layer == Some(layer));
for cell in &self.cells {
let object_count = |details| {
whole_cell_objects
.get(&cell.name)
.copied()
.unwrap_or(details)
};
let note = match (&cell.old, &cell.new) {
(None, Some(_)) => presence("added", object_count(cell.added.len())),
(Some(_), None) => presence("removed", object_count(cell.removed.len())),
_ if cell.attributes_changed() => Cow::Borrowed(" (attributes changed)"),
_ => Cow::Borrowed(""),
};
let whole_cell = cell.old.is_none() || cell.new.is_none();
// The heading accounts for layered objects in a whole-cell change.
detail_total += if whole_cell {
cell.removed
.iter()
.chain(&cell.added)
.filter(|object| object.layer.is_none())
.count()
} else {
cell.removed.len() + cell.added.len()
};
let marker = cell_marker(cell.old.is_some(), cell.new.is_some());
let attributes_changed = marker == '*' && cell.attributes_changed();
if marker == '*' {
detail_total += cell.removed.len() + cell.added.len();
}
if show.cell.as_ref().is_some_and(|name| name != &cell.name) {
hidden_cell_changes += usize::from(!note.is_empty());
hidden_cell_changes += usize::from(marker != '*' || attributes_changed);
continue;
}
let name = cell_label(&cell.name);
match marker {
'-' => {
writeln!(removed_cells, "- {name}").unwrap();
continue;
}
'+' => {
writeln!(added_cells, "+ {name}").unwrap();
continue;
}
_ => (),
};
let note = if attributes_changed {
" (attributes changed)"
} else {
""
};
let cell_start = out.len();
let previously_shown = shown;
writeln!(out, "cell {:?}{note}", cell.name).unwrap();
let visible = |object: &ObjectChange| {
(!whole_cell || object.layer.is_none())
&& show.layer.is_none_or(|layer| object.layer == Some(layer))
};
writeln!(out, "* {name}{note}").unwrap();
let mut polygons = changes::PolygonChanges::default();
let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new();
let mut paired_old = BTreeSet::new();
let mut paired_new = BTreeSet::new();
for replacement in &cell.replacements {
@ -1599,18 +1595,28 @@ impl Comparison {
if is_polygon(a.kind) {
polygons.replacement(a, b);
} else {
writeln!(out, " ~ {}", changes::replacement_summary(a, b)).unwrap();
out.push_str(" ~ ");
let row_start = out.len();
layers.record(a.layer, row_start);
writeln!(out, "{}", changes::replacement_summary(a, b)).unwrap();
if let Some(target) = &a.target {
shown_refs
.entry(target)
.or_default()
.replacement(a, b, row_start);
}
}
shown_layers.extend(a.layer);
shown += 2;
}
}
for (removed, objects, paired) in [
(true, &cell.removed, &paired_old),
(false, &cell.added, &paired_new),
let mut removed_refs = BTreeMap::new();
let mut added_refs = BTreeMap::new();
for (removed, objects, paired, references) in [
(true, &cell.removed, &paired_old, &mut removed_refs),
(false, &cell.added, &paired_new, &mut added_refs),
] {
let sign = if removed { "-" } else { "+" };
let mut references = BTreeMap::new();
let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new();
for (index, object) in objects.iter().enumerate() {
if !visible(object) {
continue;
@ -1624,33 +1630,102 @@ impl Comparison {
.entry(target)
.or_insert_with(|| (object, changes::ReferenceCounts::default()));
counts.add(object);
} else if let Some((last, count)) = unmatched.last_mut()
&& last.kind == object.kind
&& last.fields == object.fields
&& last.properties == object.properties
{
*count += 1;
} else {
changes::write_unmatched(&mut out, sign, object);
unmatched.push((object, 1));
}
shown_layers.extend(object.layer);
shown += 1;
}
}
for (target, (first, counts)) in references {
if whole_cell || counts.len() > 1 {
counts.write(&mut out, sign, target);
} else {
writeln!(out, " {sign} {first}").unwrap();
// The comparison orders these objects by kind, fields, and properties.
for (object, count) in unmatched {
write!(out, " {sign} ").unwrap();
if count > 1 {
write!(out, "{count}× ").unwrap();
}
layers.record(object.layer, out.len());
changes::write_unmatched(&mut out, object);
}
}
let no_refs = changes::ReferenceCounts::default();
for (target, (first, counts)) in removed_refs {
let row_start = out.len();
if let Some((_, added)) = added_refs.remove(target) {
counts.write_change(&mut out, target, &added);
shown_refs
.entry(target)
.or_default()
.unmatched(&counts, &added, row_start);
} else {
counts.write(&mut out, "-", target, first);
shown_refs
.entry(target)
.or_default()
.unmatched(&counts, &no_refs, row_start);
}
}
for (target, (first, counts)) in added_refs {
let row_start = out.len();
counts.write(&mut out, "+", target, first);
shown_refs
.entry(target)
.or_default()
.unmatched(&no_refs, &counts, row_start);
}
if !shown_refs.is_empty() {
for target in cell
.removed
.iter()
.chain(&cell.added)
.filter_map(|o| o.target.as_deref())
{
if let Some(shown) = shown_refs.get_mut(target) {
shown.count_change();
}
}
for (target, shown) in shown_refs {
if shown.complete() {
let edge = (cell.name.clone(), target.to_owned());
let old = self.old.edges.get(&edge).copied().unwrap_or(0);
let new = self.new.edges.get(&edge).copied().unwrap_or(0);
shown.annotate(&out, &mut annotations, old, new);
if ascii_depth.is_some() && outcome.is_complete() {
covered_edges.insert(edge);
}
}
}
}
polygons.write(&mut out);
if shown == previously_shown && note.is_empty() {
polygons.write(&mut out, &mut layers);
if shown == previously_shown && !attributes_changed {
out.truncate(cell_start);
}
}
let mut legend = String::new();
for layer in shown_layers {
if let Some(name) = self.layer_legend.get(&layer) {
writeln!(legend, "{}/{}: name {name:?}", layer.0, layer.1).unwrap();
let mut before_cells = String::new();
layers.finish(&out, &mut annotations, &mut before_cells);
// Resolve row offsets before inserting the section headers.
if !annotations.is_empty() {
annotations.sort_unstable_by_key(|(at, _)| *at);
let mut annotated = String::with_capacity(out.len());
let mut start = 0;
for (at, annotation) in annotations {
annotated.push_str(&out[start..at]);
annotated.push_str(&annotation);
start = at;
}
annotated.push_str(&out[start..]);
out = annotated;
}
out.insert_str(body_start, &legend);
if out.len() > body_start || !removed_cells.is_empty() || !added_cells.is_empty() {
before_cells.push_str("Cells:\n");
before_cells.push_str(&removed_cells);
before_cells.push_str(&added_cells);
}
out.insert_str(body_start, &before_cells);
let mut omissions = Vec::new();
for (count, label, reason) in [
(detail_total - selected, "object change", "filtered out"),
@ -1668,6 +1743,36 @@ impl Comparison {
&format!("Omitted · {}\n", omissions.join(" · ")),
);
}
const COMPACT_HEADLINE_CELL_LIMIT: usize = 3;
if !self.cells.is_empty()
&& (self.cells.len() > COMPACT_HEADLINE_CELL_LIMIT
|| !outcome.is_complete()
|| !omissions.is_empty())
{
let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize);
for cell in &self.cells {
match cell_marker(cell.old.is_some(), cell.new.is_some()) {
'-' => removed += 1,
'+' => added += 1,
_ => modified += 1,
}
}
let mut counts = [
(modified, "modified"),
(added, "added"),
(removed, "removed"),
]
.into_iter()
.filter(|(count, _)| *count != 0);
if let Some((count, action)) = counts.next() {
let noun = if count == 1 { "cell" } else { "cells" };
let mut summary = format!(" · {count} {noun} {action}");
for (count, action) in counts {
write!(summary, ", {count} {action}").unwrap();
}
out.insert_str(headline_end, &summary);
}
}
// General comparison errors precede revision-specific errors in text.
if !self.diagnostics.is_empty() {
out.push_str("Diagnostics\n");
@ -1680,6 +1785,16 @@ impl Comparison {
writeln!(out, " {diagnostic}").unwrap();
}
}
if let Some(max_depth) = ascii_depth {
out.push_str(&render_hierarchy(
&self.old,
&self.new,
Some(&self.cells),
false,
max_depth,
Some(&covered_edges),
));
}
out
}
}
@ -1745,6 +1860,7 @@ fn render_hierarchy(
changes: Option<&[CellChange]>,
mermaid: bool,
max_depth: usize,
covered_edges: Option<&BTreeSet<(String, String)>>,
) -> String {
if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) {
return String::new();
@ -1758,7 +1874,7 @@ fn render_hierarchy(
affected,
changed_refs,
} = HierarchyAnalysis::between(old, new, changes);
let visible: BTreeSet<_> = if changes.is_some() {
let mut visible: BTreeSet<_> = if changes.is_some() {
affected
.iter()
.cloned()
@ -1783,6 +1899,35 @@ fn render_hierarchy(
targets.insert(target.clone());
}
}
if let Some(covered) = covered_edges {
if !covered.is_empty() {
let mut incoming = BTreeMap::new();
for target in children.values().flatten() {
*incoming.entry(target).or_insert(0_usize) += 1;
}
// Keep changed or shared descendants, branches, and target status notes.
let redundant: BTreeSet<_> = covered
.iter()
.map(|(_, target)| target)
.filter(|&target| {
incoming.get(target) == Some(&1)
&& !children.contains_key(target)
&& !affected.contains(target)
&& old.cells.contains(target)
&& new.cells.contains(target)
})
.collect();
children.retain(|_, children| {
children.retain(|target| !redundant.contains(target));
!children.is_empty()
});
targets.retain(|target| !redundant.contains(target));
}
visible.retain(|name| children.contains_key(name) || targets.contains(name));
}
if changes.is_some() && !mermaid && children.is_empty() {
return String::new();
}
let roots: Vec<_> = visible.difference(&targets).cloned().collect();
// Distinguish rootless cycles from descendants hidden by the depth limit.
let mut reachable = BTreeSet::new();
@ -1826,15 +1971,7 @@ fn render_hierarchy(
" [unresolved]"
}
} else if direct.contains(name) {
if mermaid {
" [cell changed]"
} else if !old.known_cells.contains(name) {
" [added]"
} else if !new.known_cells.contains(name) {
" [removed]"
} else {
" [changed]"
}
if mermaid { " [cell changed]" } else { "" }
} else if affected.contains(name) {
" [affected]"
} else if mermaid && changes.is_some() {
@ -1899,7 +2036,16 @@ fn render_hierarchy(
new.scope.write_restrictions(&mut out);
}
for (name, depth, parent, seen, limited) in rows {
write!(out, "{}{name:?}", " ".repeat(depth)).unwrap();
out.push_str(&" ".repeat(depth));
if direct.contains(&name) {
let marker = cell_marker(old.cells.contains(&name), new.cells.contains(&name));
write!(out, "{marker} ").unwrap();
}
if changes.is_some() {
out.push_str(&cell_label(&name));
} else {
write!(out, "{name:?}").unwrap();
}
if let Some(parent) = parent {
write!(out, " {}", edge_label(&parent, &name)).unwrap();
}
@ -1919,6 +2065,25 @@ fn render_hierarchy(
}
}
fn cell_marker(old: bool, new: bool) -> char {
match (old, new) {
(true, false) => '-',
(false, true) => '+',
_ => '*',
}
}
fn cell_label(name: &str) -> Cow<'_, str> {
if name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'$' | b'?' | b'.' | b'-'))
{
Cow::Borrowed(name)
} else {
Cow::Owned(format!("{name:?}"))
}
}
fn quoted(data: &[u8]) -> String {
let mut out = "\"".to_string();
for byte in data {