Skip to content

Commit 991405e

Browse files
aqeelatzkochan
andauthored
fix(default-reporter): restore ansi-diff to stop duplicated output lines (#12698)
* fix(default-reporter): restore ansi-diff to stop duplicated output lines PR #12351 replaced ansi-diff with manual full-frame reprint, which re-writes unchanged sticky blocks on every progress tick. This caused cached lockfile verdicts and deprecation warnings to appear dozens of times in terminals that record each write (Warp, script, CI logs). The manual countRows also produced unbounded cursor-up values when the frame was taller than the terminal, causing an infinite repaint loop on pnpm run --parallel. TypeScript CLI: restore the `ansi-diff` npm package for differential rendering, wrapping its output with \r (column reset) + \x1b[0J (erase below frame) to preserve the external-process-output fix from #12351. Rust pacquet port: implement a zero-dependency differential renderer (`diff.rs`) with the same algorithm, replacing the full-frame reprint in `Sink::write_output`. Closes #12634. * fix(default-reporter): pass dylint, add trailing newline, harden reporter test Builds on the restored ansi-diff differential renderer: - pacquet: guarantee a trailing newline before diffing a frame, matching the TypeScript reporter. This keeps an interactive prompt on a fresh line below the frame instead of joined onto the last progress line, and leaves the differ's tracked cursor column at 0 so it stays in sync with the \r prepended on the next update (otherwise the inline diff computes relative moves from a stale column and corrupts in-place rendering). - pacquet: move the differ's inline test module into src/diff/tests.rs with explicit imports and drop a stray trailing comma, so cargo dylint passes. - TypeScript: locate the sticky lockfile verdict's first render with findIndex instead of assuming writes[0], and wrap each reporter test body in try/finally so the subscription is always stopped. * fix(default-reporter): align rust diff with ansi-diff edge cases - Add col !== width guard before inline diff, matching the JS ansi-diff edgecase check that prevents mispositioning at exact-width wrap boundaries. - Fix clearDown to start from the cursor's current row (self.row) instead of new_last_row, matching the JS _clearDown pattern. The previous code could clear frame content when trailing lines were unchanged and the frame shrank. - Document the visible_width vs wcwidth simplification. * test(default-reporter): expand diff coverage to 14 tests Add 8 new tests covering: - inline diff skipped for ANSI-containing lines - inline diff threshold edge case - full line rewrite with clear - clear_down starting from cursor row (not new_last_row) - soft-wrapped line height tracking - empty frame clears all previous content - multiple progress ticks (simulated install sequence) - frame without trailing newline * fix(default-reporter): tighten test assertions and avoid hot-path allocation - clear_down_from_cursor_row: replace weak || assertion with direct checks that Line A is absent, Line B changed is present, and clear sequence is emitted. - TS reporterRenderer: capture writes.length before the 'fetched' event and wait for an increase, so the test can't pass early. - pacquet Sink::write_output: write \r, diff output, and erase codes as separate write_all calls instead of format!() which allocated a new String on every frame. * fix(default-reporter): make frame redraw a single write and fix diff test Compose the \r + diff + erase sequence into a reusable per-sink buffer and emit it with one write_all, keeping each frame update atomic against interleaved writers without allocating on the hot progress path. Rework inline_diff_skipped_for_small_change (which actually exercised the inline-diff happy path already covered by inline_diff_writes_only_changed_chars) into inline_diff_skipped_for_short_common_affix, covering the left + right <= 4 full-rewrite branch its name promised. --------- Co-authored-by: Zoltan Kochan <[email protected]>
1 parent a315360 commit 991405e

9 files changed

Lines changed: 603 additions & 62 deletions

File tree

‎.changeset/restore-ansi-diff.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@pnpm/cli.default-reporter": patch
3+
"pnpm": patch
4+
---
5+
6+
Restore differential rendering (`ansi-diff`) to fix duplicated output lines introduced by pnpm/pnpm#12351.
Lines changed: 243 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
//! Differential frame renderer — ports the `ansi-diff` algorithm to compute
2+
//! the minimal ANSI escape sequence that transforms the previously rendered
3+
//! frame into the new one.
4+
//!
5+
//! Unchanged lines are skipped entirely, so sticky blocks (lockfile verdicts,
6+
//! deprecation warnings) are not re-written on every progress tick. This is
7+
//! the same algorithm used by the TypeScript `@pnpm/cli.default-reporter`
8+
//! via the npm `ansi-diff` package.
9+
10+
use std::fmt::Write as _;
11+
12+
use crate::format::visible_width;
13+
14+
// `visible_width` counts one column per char (matching `string-length` in the
15+
// TS reporter), not `wcwidth` (which counts CJK/wide chars as 2). This
16+
// matches the TS `ansi-diff` usage where `string-length` is the width source.
17+
// ASCII-dominant progress output is unaffected; CJK package names would be
18+
// undercounted, same as the pre-pnpm/pnpm#12351 behavior.
19+
20+
/// Renders the differential between successive frames.
21+
pub(crate) struct Diff {
22+
col: usize,
23+
row: usize,
24+
width: usize,
25+
lines: Vec<Line>,
26+
}
27+
28+
impl Diff {
29+
pub(crate) fn new(width: usize) -> Self {
30+
Diff { col: 0, row: 0, width, lines: Vec::new() }
31+
}
32+
33+
/// Appends to `out` the ANSI escape sequence that transforms the previous
34+
/// frame into `frame`. The caller wraps this with `\r` (column reset) and
35+
/// `\x1b[0J` (erase below frame), composing the whole redraw into one
36+
/// buffer so it reaches the terminal as a single write.
37+
pub(crate) fn update_into(&mut self, frame: &str, out: &mut String) {
38+
let next = Line::split(frame, self.width);
39+
let min = next.len().min(self.lines.len());
40+
let mut scrub = false;
41+
42+
// Take ownership of the previous lines so the borrow of `self` ends
43+
// and we can freely mutate `self.col` / `self.row` during the loop.
44+
let old = std::mem::take(&mut self.lines);
45+
46+
for (idx, new_line) in next.iter().enumerate().take(min) {
47+
let old_line = &old[idx];
48+
if new_line.raw == old_line.raw
49+
&& new_line.row == old_line.row
50+
&& new_line.newline == old_line.newline
51+
{
52+
continue;
53+
}
54+
let old_len = old_line.length;
55+
let old_row = old_line.row;
56+
let old_height = old_line.height;
57+
if !scrub
58+
&& self.col != self.width
59+
&& new_line.try_inline_diff(old_line, out, &mut self.col, &mut self.row, self.width)
60+
{
61+
continue;
62+
}
63+
self.move_to(out, 0, new_line.row);
64+
out.push_str(&new_line.raw);
65+
if new_line.row != old_row || new_line.height != old_height {
66+
scrub = true;
67+
}
68+
if old_len > new_line.length || scrub {
69+
out.push_str("\x1b[0K");
70+
}
71+
if new_line.newline {
72+
out.push('\n');
73+
self.col = 0;
74+
self.row = new_line.row + new_line.height + 1;
75+
} else {
76+
self.col = new_line.remainder;
77+
self.row = new_line.row + new_line.height;
78+
}
79+
}
80+
81+
for new_line in &next[min..] {
82+
self.move_to(out, 0, new_line.row);
83+
out.push_str(&new_line.raw);
84+
if scrub {
85+
out.push_str("\x1b[0K");
86+
}
87+
if new_line.newline {
88+
out.push('\n');
89+
self.col = 0;
90+
self.row = new_line.row + new_line.height + 1;
91+
} else {
92+
self.col = new_line.remainder;
93+
self.row = new_line.row + new_line.height;
94+
}
95+
}
96+
97+
if let Some(old_last) = old.last() {
98+
let old_last_row = old_last.row + old_last.height;
99+
let new_last_row = next.last().map_or(0, |line| line.row + line.height);
100+
if next.is_empty() || new_last_row < old_last_row {
101+
self.clear_down(out, old_last_row);
102+
}
103+
}
104+
105+
if let Some(last) = next.last() {
106+
self.move_to(out, last.remainder, last.row + last.height);
107+
}
108+
109+
self.lines = next;
110+
}
111+
112+
#[cfg(test)]
113+
pub(crate) fn update(&mut self, frame: &str) -> String {
114+
let mut out = String::new();
115+
self.update_into(frame, &mut out);
116+
out
117+
}
118+
119+
fn move_to(&mut self, out: &mut String, col: usize, row: usize) {
120+
move_to(out, &mut self.col, &mut self.row, col, row);
121+
}
122+
123+
/// Clear lines from the cursor's current position down to `target_row`,
124+
/// matching `ansi-diff`'s `_clearDown`. The first line starts at the
125+
/// cursor's current column; subsequent lines start at column 0.
126+
fn clear_down(&mut self, out: &mut String, target_row: usize) {
127+
let mut col = self.col;
128+
for current_row in self.row..=target_row {
129+
self.move_to(out, col, current_row);
130+
out.push_str("\x1b[0K");
131+
col = 0;
132+
}
133+
}
134+
}
135+
136+
#[derive(Clone)]
137+
struct Line {
138+
raw: String,
139+
row: usize,
140+
length: usize,
141+
height: usize,
142+
remainder: usize,
143+
newline: bool,
144+
}
145+
146+
impl Line {
147+
fn new(text: &str, row: usize, newline: bool, width: usize) -> Self {
148+
let length = visible_width(text);
149+
let (height, remainder) = match width {
150+
0 => (0, length),
151+
term_width => {
152+
let line_height = length / term_width;
153+
let line_remainder = length % term_width;
154+
if line_height > 0 && line_remainder == 0 {
155+
(line_height - 1, term_width)
156+
} else {
157+
(line_height, line_remainder)
158+
}
159+
}
160+
};
161+
Line { raw: text.to_string(), row, length, height, remainder, newline }
162+
}
163+
164+
fn split(input: &str, width: usize) -> Vec<Self> {
165+
let parts: Vec<&str> = input.split('\n').collect();
166+
let count = parts.len();
167+
let mut row_offset = 0;
168+
parts
169+
.into_iter()
170+
.enumerate()
171+
.map(|(idx, text)| {
172+
let newline = idx < count - 1;
173+
let line = Line::new(text, row_offset, newline, width);
174+
row_offset += line.height + u8::from(newline) as usize;
175+
line
176+
})
177+
.collect()
178+
}
179+
180+
/// Inline diff: if only a few characters changed, write just those
181+
/// instead of the whole line. Only attempted on lines without ANSI
182+
/// escape codes (plain text like progress lines).
183+
fn try_inline_diff(
184+
&self,
185+
other: &Self,
186+
out: &mut String,
187+
col: &mut usize,
188+
row: &mut usize,
189+
width: usize,
190+
) -> bool {
191+
if self.length != other.length
192+
|| self.row != other.row
193+
|| !self.newline
194+
|| !other.newline
195+
|| self.raw.contains('\u{1b}')
196+
|| other.raw.contains('\u{1b}')
197+
{
198+
return false;
199+
}
200+
let self_chars: Vec<char> = self.raw.chars().collect();
201+
let other_chars: Vec<char> = other.raw.chars().collect();
202+
let left = self_chars.iter().zip(&other_chars).take_while(|(ca, cb)| ca == cb).count();
203+
let right = self_chars
204+
.iter()
205+
.rev()
206+
.zip(other_chars.iter().rev())
207+
.take_while(|(ca, cb)| ca == cb)
208+
.count();
209+
let changed_len = self_chars.len().saturating_sub(left + right);
210+
if left + right <= 4 || left + changed_len >= width.saturating_sub(1) {
211+
return false;
212+
}
213+
move_to(out, col, row, left, self.row);
214+
let changed: String = self_chars[left..left + changed_len].iter().collect();
215+
out.push_str(&changed);
216+
*col = left + changed_len;
217+
true
218+
}
219+
}
220+
221+
fn move_to(
222+
out: &mut String,
223+
col: &mut usize,
224+
row: &mut usize,
225+
target_col: usize,
226+
target_row: usize,
227+
) {
228+
if target_col > *col {
229+
let _ = write!(out, "\x1b[{}C", target_col - *col);
230+
} else if target_col < *col {
231+
let _ = write!(out, "\x1b[{}D", *col - target_col);
232+
}
233+
if target_row > *row {
234+
let _ = write!(out, "\x1b[{}B", target_row - *row);
235+
} else if target_row < *row {
236+
let _ = write!(out, "\x1b[{}A", *row - target_row);
237+
}
238+
*col = target_col;
239+
*row = target_row;
240+
}
241+
242+
#[cfg(test)]
243+
mod tests;

0 commit comments

Comments
 (0)