Skip to main content

move_diff/
annotate_diff.rs

1//! Annotates a unified diff with extra markers for moved and reformatted
2//! code, on top of the usual `+`/`-` lines, to make large mechanical
3//! refactors easier to review.
4//!
5//! Marker legend:
6//! - `' '` context  (unchanged)
7//! - `'+'` addition (green)   — genuinely new content
8//! - `'-'` removal  (red)     — genuinely removed content
9//! - `'>'` moved out (cyan)   — this line left its old spot
10//! - `'<'` moved in  (blue)   — this line arrived from elsewhere
11//! - `'x'` reformat (magenta) — same content, only whitespace/layout changed;
12//!   only the new side is shown (the old side would be a whitespace-only
13//!   duplicate, so it's dropped rather than printed twice)
14//!
15//! Detection runs in three passes over each hunk's "change blocks" (a run of
16//! consecutive removed lines immediately followed by a run of consecutive
17//! added lines):
18//!
19//! 1. Whole-block reformat: if a block's removed lines and added lines are
20//!    identical once all whitespace is stripped, the entire block is a pure
21//!    reflow (handles reindentation and a linter wrapping/joining lines)
22//!    and gets `x`.
23//! 2. Global move detection: lines left over after pass 1 are matched,
24//!    whitespace-normalized, against lines in *other* blocks (any file). A
25//!    match seeds an anchor that is then extended line-by-line in both
26//!    directions within its block; forward extension tolerates a small
27//!    reflow window (so a moved line that was also split/joined still
28//!    counts as moved) and a configurable number of lines that differ for
29//!    real — an edit made during the move — before giving up. The
30//!    resulting run is only accepted as a move once it totals at least
31//!    `MIN_MOVE_ALNUM_CHARS` alphanumeric characters — the same rule
32//!    `git diff --color-moved`'s `blocks`/`zebra` modes use — otherwise
33//!    it's left as plain `+`/`-` and the next matching candidate (if any)
34//!    is tried instead.
35//! 3. Local leftover reconciliation: whatever remains unconsumed within a
36//!    single block is re-paired against the rest of that same block
37//!    (whitespace-normalized) to catch an in-place reformat sitting right
38//!    next to a move or a genuine addition. Anything still unpaired is a
39//!    plain addition/removal.
40
41use std::collections::HashMap;
42use std::fmt;
43use std::ops::Range;
44use std::str::FromStr;
45
46use anyhow::Result;
47use patch::{Line as PatchLine, Patch};
48
49use crate::diff_parse::{parse_patches_safely, split_file_diffs};
50
51/// Minimum number of non-whitespace characters a line needs before it's
52/// trusted as a move *anchor* on its own. Short/common lines (`}`, `{`,
53/// blank lines) are too likely to collide; they can still be swept into a
54/// moved block once extension reaches them from a trustworthy anchor.
55const MIN_ANCHOR_LEN: usize = 8;
56
57/// Minimum number of alphanumeric characters a matched run must contain,
58/// summed across every line it ends up covering, before it's accepted as
59/// a move rather than left as plain `+`/`-`.
60///
61/// Mirrors `git diff --color-moved`'s `blocks`/`zebra` modes exactly: same
62/// threshold, same metric (letters + digits only — punctuation and
63/// whitespace don't count), same hardcoded, unconfigurable constant. Below
64/// this, a match is indistinguishable from a coincidentally-duplicated
65/// short/common line sitting inside an unrelated block of real edits.
66const MIN_MOVE_ALNUM_CHARS: usize = 20;
67
68/// How many lines we're willing to try merging/splitting on either side
69/// when checking whether a mismatch during block extension is actually a
70/// pure reflow (e.g. a linter wrapping a long line into several).
71const MAX_REFLOW_WINDOW: usize = 10;
72
73/// How many real content changes are tolerated inside an otherwise-moved
74/// block before move detection gives up extending into that block (lines
75/// beyond this fall back to plain `+`/`-`).
76///
77/// Accepts either an absolute line count or a fraction/percentage of the
78/// remaining block length in whichever direction extension is currently
79/// going — a flat count under-tolerates large moved blocks that picked up
80/// a handful of real edits, while a fraction scales with the block.
81///
82/// Parsed from a string: a trailing `%` means relative (`"10%"` → 0.10), a
83/// bare value `< 1` is also relative (`"0.1"` is the same as `"10%"`), and
84/// a bare value `>= 1` is an absolute count (`"2"` → tolerate 2 lines).
85#[derive(Debug, Clone, Copy, PartialEq)]
86pub enum MoveGap {
87    Absolute(usize),
88    Relative(f64),
89}
90
91impl MoveGap {
92    /// The tolerance budget for a direction with `remaining_len` lines left
93    /// before the enclosing block's boundary.
94    fn budget_for(&self, remaining_len: usize) -> usize {
95        match self {
96            MoveGap::Absolute(n) => *n,
97            // `ceil` means any ratio > 0 yields a budget >= 1 as soon as
98            // there's at least one line left to extend into, with no need
99            // for a separate hardcoded floor — while an explicit ratio of
100            // exactly 0 still means exactly zero tolerance.
101            MoveGap::Relative(ratio) => (ratio * remaining_len as f64).ceil() as usize,
102        }
103    }
104}
105
106impl FromStr for MoveGap {
107    type Err = String;
108
109    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
110        let s = s.trim();
111        if let Some(pct) = s.strip_suffix('%') {
112            let v: f64 = pct
113                .trim()
114                .parse()
115                .map_err(|_| format!("invalid percentage: {s}"))?;
116            if v < 0.0 {
117                return Err(format!("percentage must be >= 0: {s}"));
118            }
119            return Ok(MoveGap::Relative(v / 100.0));
120        }
121        let v: f64 = s.parse().map_err(|_| format!("invalid number: {s}"))?;
122        if v < 0.0 {
123            return Err(format!("value must be >= 0: {s}"));
124        }
125        if v >= 1.0 {
126            Ok(MoveGap::Absolute(v.round() as usize))
127        } else {
128            Ok(MoveGap::Relative(v))
129        }
130    }
131}
132
133impl fmt::Display for MoveGap {
134    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
135        match self {
136            MoveGap::Absolute(n) => write!(f, "{n}"),
137            MoveGap::Relative(ratio) => write!(f, "{}%", ratio * 100.0),
138        }
139    }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143enum Marker {
144    Add,
145    Remove,
146    MovedOut,
147    MovedIn,
148    Reformat,
149}
150
151/// One changed (non-context) line inside a hunk.
152#[derive(Debug, Clone)]
153struct ChangedLine {
154    text: String,
155    marker: Marker,
156    /// Index into the global `blocks` vector.
157    block: usize,
158}
159
160/// A maximal run of consecutive removed lines immediately followed by a
161/// maximal run of consecutive added lines, inside a single hunk.
162#[derive(Debug, Clone)]
163struct Block {
164    removes: Range<usize>,
165    adds: Range<usize>,
166}
167
168/// One element of a file's rendered hunk, in original diff order.
169enum RenderLine {
170    Context(String),
171    Removed(usize),
172    Added(usize),
173}
174
175struct FileHunks {
176    old_path: String,
177    new_path: String,
178    hunks: Vec<(String, Vec<RenderLine>)>,
179}
180
181/// One entry of the top-level diff, in original order: either a
182/// successfully parsed file (indexing into the parallel `files`/patch
183/// vectors) or the raw, unparsed text of a file whose entry couldn't be
184/// parsed (binary diff, mode-only change, pure rename, ...).
185enum Unit<'a> {
186    Parsed(usize),
187    Raw(&'a str),
188}
189
190fn normalize(s: &str) -> String {
191    s.chars().filter(|c| !c.is_whitespace()).collect()
192}
193
194fn is_anchor_eligible(s: &str) -> bool {
195    normalize(s).chars().count() >= MIN_ANCHOR_LEN
196}
197
198fn alnum_len(s: &str) -> usize {
199    s.chars().filter(|c| c.is_alphanumeric()).count()
200}
201
202/// Render `diff_text` (as produced by `git diff`) with move/reformat
203/// annotations.
204///
205/// `max_move_gap` bounds how many real (non-reflow) content changes are
206/// tolerated inside an otherwise-moved block before extension gives up.
207/// `color` enables ANSI colors.
208///
209/// Falls back to printing a file's own diff entry unannotated (with a
210/// warning on stderr) if that entry can't be parsed (e.g. a binary diff,
211/// mode-only change, or pure rename), rather than failing outright or
212/// discarding annotations for the rest of the diff — this is best-effort
213/// tooling on top of `git diff`, and one file's parser limitation
214/// shouldn't make every other file's diff unreadable.
215pub fn render(diff_text: &str, max_move_gap: MoveGap, color: bool) -> Result<String> {
216    // `git::local_diff` captures output via `duct`'s `.read()`, which (like
217    // shell `$()`) strips the trailing newline — but the `patch` crate's
218    // parser requires every line, including the last, to be newline
219    // terminated and *panics* (via an internal `assert!`, not a `Result`)
220    // if it isn't. Restoring the newline here fixes the overwhelmingly
221    // common case (any diff ending in a context line, which is most of
222    // them with the default 3-line context).
223    let diff_text = if diff_text.ends_with('\n') {
224        diff_text.to_string()
225    } else {
226        format!("{diff_text}\n")
227    };
228
229    let patches: Vec<Patch<'_>>;
230    let mut units: Vec<Unit<'_>> = Vec::new();
231    {
232        let mut collected = Vec::new();
233        for chunk in split_file_diffs(&diff_text) {
234            match parse_patches_safely(chunk) {
235                Ok(parsed) => {
236                    for p in parsed {
237                        units.push(Unit::Parsed(collected.len()));
238                        collected.push(p);
239                    }
240                }
241                Err(msg) => {
242                    eprintln!("warning: move-diff: {msg}; showing this file's plain diff instead");
243                    units.push(Unit::Raw(chunk));
244                }
245            }
246        }
247        patches = collected;
248    }
249
250    let mut removes: Vec<ChangedLine> = Vec::new();
251    let mut adds: Vec<ChangedLine> = Vec::new();
252    let mut blocks: Vec<Block> = Vec::new();
253    let mut files: Vec<FileHunks> = Vec::new();
254
255    for patch in &patches {
256        let mut hunks_out = Vec::new();
257
258        for hunk in &patch.hunks {
259            let mut render_lines: Vec<RenderLine> = Vec::new();
260
261            let mut pend_remove_start: Option<usize> = None;
262            let mut pend_add_start: Option<usize> = None;
263            let mut seen_add_in_block = false;
264
265            for line in &hunk.lines {
266                match line {
267                    PatchLine::Context(text) => {
268                        flush_block(
269                            &mut pend_remove_start,
270                            &mut pend_add_start,
271                            &mut seen_add_in_block,
272                            &mut removes,
273                            &mut adds,
274                            &mut blocks,
275                        );
276                        render_lines.push(RenderLine::Context(format!(" {text}")));
277                    }
278                    PatchLine::Remove(text) => {
279                        if seen_add_in_block {
280                            // A new remove run started without a context
281                            // line separating it from the previous block's
282                            // adds: treat it as a new block.
283                            flush_block(
284                                &mut pend_remove_start,
285                                &mut pend_add_start,
286                                &mut seen_add_in_block,
287                                &mut removes,
288                                &mut adds,
289                                &mut blocks,
290                            );
291                        }
292                        if pend_remove_start.is_none() {
293                            pend_remove_start = Some(removes.len());
294                        }
295                        render_lines.push(RenderLine::Removed(removes.len()));
296                        removes.push(ChangedLine {
297                            text: text.to_string(),
298                            marker: Marker::Remove,
299                            block: usize::MAX,
300                        });
301                    }
302                    PatchLine::Add(text) => {
303                        if pend_add_start.is_none() {
304                            pend_add_start = Some(adds.len());
305                        }
306                        seen_add_in_block = true;
307                        render_lines.push(RenderLine::Added(adds.len()));
308                        adds.push(ChangedLine {
309                            text: text.to_string(),
310                            marker: Marker::Add,
311                            block: usize::MAX,
312                        });
313                    }
314                }
315            }
316            flush_block(
317                &mut pend_remove_start,
318                &mut pend_add_start,
319                &mut seen_add_in_block,
320                &mut removes,
321                &mut adds,
322                &mut blocks,
323            );
324
325            hunks_out.push((
326                format!(
327                    "@@ -{} +{} @@{}",
328                    hunk.old_range, hunk.new_range, hunk.range_hint
329                ),
330                render_lines,
331            ));
332        }
333
334        files.push(FileHunks {
335            old_path: patch.old.to_string(),
336            new_path: patch.new.to_string(),
337            hunks: hunks_out,
338        });
339    }
340
341    // Pass 1: whole-block reformat.
342    for block in &blocks {
343        if block.removes.is_empty() || block.adds.is_empty() {
344            continue;
345        }
346        let old_sig: String = removes[block.removes.clone()]
347            .iter()
348            .map(|l| normalize(&l.text))
349            .collect();
350        let new_sig: String = adds[block.adds.clone()]
351            .iter()
352            .map(|l| normalize(&l.text))
353            .collect();
354        if old_sig == new_sig {
355            for l in removes[block.removes.clone()].iter_mut() {
356                l.marker = Marker::Reformat;
357            }
358            for l in adds[block.adds.clone()].iter_mut() {
359                l.marker = Marker::Reformat;
360            }
361        }
362    }
363
364    // Pass 2: global move detection (anchor + extend).
365    detect_moves(&mut removes, &mut adds, &blocks, max_move_gap);
366
367    // Pass 3: local leftover reconciliation.
368    for block in &blocks {
369        reconcile_leftovers(
370            &mut removes,
371            block.removes.clone(),
372            &mut adds,
373            block.adds.clone(),
374        );
375    }
376
377    Ok(render_output(&units, &files, &removes, &adds, color))
378}
379
380fn flush_block(
381    pend_remove_start: &mut Option<usize>,
382    pend_add_start: &mut Option<usize>,
383    seen_add_in_block: &mut bool,
384    removes: &mut [ChangedLine],
385    adds: &mut [ChangedLine],
386    blocks: &mut Vec<Block>,
387) {
388    // A block exists as soon as there's *either* a pending remove run or a
389    // pending add run — a run of pure additions (no removes before it) is
390    // just as much a block as a run with both sides.
391    if pend_remove_start.is_some() || pend_add_start.is_some() {
392        let rs = pend_remove_start.take().unwrap_or(removes.len());
393        let as_ = pend_add_start.take().unwrap_or(adds.len());
394        let r_range = rs..removes.len();
395        let a_range = as_..adds.len();
396        let block_idx = blocks.len();
397        for r in removes[r_range.clone()].iter_mut() {
398            r.block = block_idx;
399        }
400        for a in adds[a_range.clone()].iter_mut() {
401            a.block = block_idx;
402        }
403        blocks.push(Block {
404            removes: r_range,
405            adds: a_range,
406        });
407    }
408    *seen_add_in_block = false;
409}
410
411fn try_reflow(
412    removes: &[ChangedLine],
413    r_end: usize,
414    ri: usize,
415    adds: &[ChangedLine],
416    a_end: usize,
417    ai: usize,
418) -> Option<(usize, usize)> {
419    for total in 2..=(MAX_REFLOW_WINDOW * 2) {
420        let ro_max = MAX_REFLOW_WINDOW.min(total - 1);
421        for ro in 1..=ro_max {
422            let ao = total - ro;
423            if ao == 0 || ao > MAX_REFLOW_WINDOW {
424                continue;
425            }
426            if ri + ro > r_end || ai + ao > a_end {
427                continue;
428            }
429            if removes[ri..ri + ro]
430                .iter()
431                .any(|l| l.marker != Marker::Remove)
432                || adds[ai..ai + ao].iter().any(|l| l.marker != Marker::Add)
433            {
434                continue;
435            }
436            let old_sig: String = removes[ri..ri + ro]
437                .iter()
438                .map(|l| normalize(&l.text))
439                .collect();
440            let new_sig: String = adds[ai..ai + ao]
441                .iter()
442                .map(|l| normalize(&l.text))
443                .collect();
444            if old_sig == new_sig {
445                return Some((ro, ao));
446            }
447        }
448    }
449    None
450}
451
452fn detect_moves(
453    removes: &mut [ChangedLine],
454    adds: &mut [ChangedLine],
455    blocks: &[Block],
456    max_move_gap: MoveGap,
457) {
458    // Index every added line by its whitespace-normalized text once, up
459    // front, instead of rescanning the whole `adds` slice from scratch for
460    // every anchor attempt (that used to make this O(matches × R × A)). A
461    // stale entry (pointing at a line already consumed elsewhere) is cheap
462    // to detect per-candidate via the marker check below, so there's no
463    // need to prune the index as lines get consumed.
464    let mut add_index: HashMap<String, Vec<usize>> = HashMap::new();
465    for (j, a) in adds.iter().enumerate() {
466        add_index.entry(normalize(&a.text)).or_default().push(j);
467    }
468
469    // A single forward pass over `removes`: once visited here (whether it
470    // became an anchor or not), a line never needs revisiting — markers
471    // only ever move away from `Remove`, never back to it, so a line that
472    // wasn't eligible (or whose candidates all got rejected) now can't
473    // become eligible on some later, repeated pass.
474    for r_anchor in 0..removes.len() {
475        if removes[r_anchor].marker != Marker::Remove
476            || !is_anchor_eligible(&removes[r_anchor].text)
477        {
478            continue;
479        }
480        let key = normalize(&removes[r_anchor].text);
481        let r_block_idx = removes[r_anchor].block;
482        let Some(candidates) = add_index.get(&key) else {
483            continue;
484        };
485
486        for &a_anchor in candidates {
487            if adds[a_anchor].marker != Marker::Add || adds[a_anchor].block == r_block_idx {
488                continue;
489            }
490
491            let r_block = blocks[r_block_idx].clone();
492            let a_block = blocks[adds[a_anchor].block].clone();
493
494            // Measure the run first, without mutating anything, so a run
495            // that doesn't clear MIN_MOVE_ALNUM_CHARS can be left exactly
496            // as-is and the next candidate (if any) tried instead.
497            let mut moved_r = vec![r_anchor];
498            let mut moved_a = vec![a_anchor];
499
500            // Extend forward.
501            let mut ri = r_anchor + 1;
502            let mut ai = a_anchor + 1;
503            let fwd_remaining = (r_block.removes.end - ri).min(a_block.adds.end.saturating_sub(ai));
504            let mut gap_budget = max_move_gap.budget_for(fwd_remaining);
505            while ri < r_block.removes.end && ai < a_block.adds.end {
506                if removes[ri].marker != Marker::Remove || adds[ai].marker != Marker::Add {
507                    break;
508                }
509                if normalize(&removes[ri].text) == normalize(&adds[ai].text) {
510                    moved_r.push(ri);
511                    moved_a.push(ai);
512                    ri += 1;
513                    ai += 1;
514                    continue;
515                }
516                if let Some((rn, an)) =
517                    try_reflow(removes, r_block.removes.end, ri, adds, a_block.adds.end, ai)
518                {
519                    moved_r.extend(ri..ri + rn);
520                    moved_a.extend(ai..ai + an);
521                    ri += rn;
522                    ai += an;
523                    continue;
524                }
525                if gap_budget == 0 {
526                    break;
527                }
528                gap_budget -= 1;
529                ri += 1;
530                ai += 1;
531            }
532
533            // Extend backward (exact matches only — a reflow at the start
534            // of a moved block is rare enough that tracking variable-size
535            // backward windows isn't worth the complexity for v1).
536            let mut ri = r_anchor;
537            let mut ai = a_anchor;
538            let back_remaining =
539                (ri - r_block.removes.start).min(ai.saturating_sub(a_block.adds.start));
540            let mut gap_budget = max_move_gap.budget_for(back_remaining);
541            while ri > r_block.removes.start && ai > a_block.adds.start {
542                let pri = ri - 1;
543                let pai = ai - 1;
544                if removes[pri].marker != Marker::Remove || adds[pai].marker != Marker::Add {
545                    break;
546                }
547                if normalize(&removes[pri].text) == normalize(&adds[pai].text) {
548                    moved_r.push(pri);
549                    moved_a.push(pai);
550                    ri = pri;
551                    ai = pai;
552                    continue;
553                }
554                if gap_budget == 0 {
555                    break;
556                }
557                gap_budget -= 1;
558                ri = pri;
559                ai = pai;
560            }
561
562            // Same rule as `git diff --color-moved`'s `blocks`/`zebra`
563            // modes: a matched run is only painted as moved once it
564            // totals at least MIN_MOVE_ALNUM_CHARS alphanumeric
565            // characters. Below that, it's indistinguishable from a
566            // coincidentally-duplicated short/common line sitting inside
567            // an unrelated block of real edits — try the next candidate
568            // add for this same anchor (if any) instead of committing.
569            let total_alnum: usize = moved_r.iter().map(|&i| alnum_len(&removes[i].text)).sum();
570            if total_alnum < MIN_MOVE_ALNUM_CHARS {
571                continue;
572            }
573
574            for &i in &moved_r {
575                removes[i].marker = Marker::MovedOut;
576            }
577            for &j in &moved_a {
578                adds[j].marker = Marker::MovedIn;
579            }
580            break;
581        }
582    }
583}
584
585fn reconcile_leftovers(
586    removes: &mut [ChangedLine],
587    r_range: Range<usize>,
588    adds: &mut [ChangedLine],
589    a_range: Range<usize>,
590) {
591    let add_indices: Vec<usize> = a_range.collect();
592    let mut used = vec![false; add_indices.len()];
593
594    for ri in r_range {
595        if removes[ri].marker != Marker::Remove {
596            continue;
597        }
598        let key = normalize(&removes[ri].text);
599        if let Some(pos) = add_indices.iter().enumerate().position(|(k, &ai)| {
600            !used[k] && adds[ai].marker == Marker::Add && normalize(&adds[ai].text) == key
601        }) {
602            used[pos] = true;
603            removes[ri].marker = Marker::Reformat;
604            adds[add_indices[pos]].marker = Marker::Reformat;
605        }
606    }
607}
608
609fn render_output(
610    units: &[Unit<'_>],
611    files: &[FileHunks],
612    removes: &[ChangedLine],
613    adds: &[ChangedLine],
614    color: bool,
615) -> String {
616    let mut out = String::new();
617    for unit in units {
618        match unit {
619            Unit::Raw(text) => out.push_str(text),
620            Unit::Parsed(idx) => render_file(&mut out, &files[*idx], removes, adds, color),
621        }
622    }
623    out
624}
625
626fn render_file(
627    out: &mut String,
628    file: &FileHunks,
629    removes: &[ChangedLine],
630    adds: &[ChangedLine],
631    color: bool,
632) {
633    out.push_str(&format!("--- {}\n", file.old_path));
634    out.push_str(&format!("+++ {}\n", file.new_path));
635    for (header, lines) in &file.hunks {
636        out.push_str(header);
637        out.push('\n');
638        for rl in lines {
639            match rl {
640                RenderLine::Context(text) => {
641                    out.push_str(text);
642                    out.push('\n');
643                }
644                RenderLine::Removed(i) => {
645                    let line = &removes[*i];
646                    // A reformat's removed side is a whitespace-only
647                    // duplicate of its added side (that's the definition of
648                    // `Marker::Reformat`); printing both would show the same
649                    // content twice, so only the added/new side is kept.
650                    if line.marker != Marker::Reformat {
651                        render_changed_line(out, line, color);
652                    }
653                }
654                RenderLine::Added(i) => render_changed_line(out, &adds[*i], color),
655            }
656        }
657    }
658}
659
660fn render_changed_line(out: &mut String, line: &ChangedLine, color: bool) {
661    let (ch, code) = match line.marker {
662        Marker::Remove => ('-', "31"),
663        Marker::Add => ('+', "32"),
664        Marker::MovedOut => ('>', "36"),
665        Marker::MovedIn => ('<', "34"),
666        Marker::Reformat => ('x', "35"),
667    };
668    if color {
669        out.push_str(&format!("\x1b[{code}m{ch}{}\x1b[0m\n", line.text));
670    } else {
671        out.push_str(&format!("{ch}{}\n", line.text));
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    fn strip_ansi(s: &str) -> String {
680        let mut out = String::new();
681        let mut chars = s.chars();
682        while let Some(c) = chars.next() {
683            if c == '\x1b' {
684                for n in chars.by_ref() {
685                    if n == 'm' {
686                        break;
687                    }
688                }
689                continue;
690            }
691            out.push(c);
692        }
693        out
694    }
695
696    fn markers_only(rendered: &str) -> Vec<char> {
697        strip_ansi(rendered)
698            .lines()
699            .filter(|l| !l.starts_with("---") && !l.starts_with("+++") && !l.starts_with("@@"))
700            .map(|l| l.chars().next().unwrap_or(' '))
701            .collect()
702    }
703
704    const GAP1: MoveGap = MoveGap::Absolute(1);
705
706    #[test]
707    fn plain_add_remove() {
708        let diff = "--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n-foo bar baz\n+quux bar baz\n context\n";
709        let out = render(diff, GAP1, false).unwrap();
710        assert_eq!(markers_only(&out), vec!['-', '+', ' ']);
711    }
712
713    #[test]
714    fn in_hunk_reformat_single_line() {
715        let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-    if order.total>0.0 {\n+    if order.total > 0.0 {\n";
716        let out = render(diff, GAP1, false).unwrap();
717        // The removed side is a whitespace-only duplicate of the added
718        // side, so only the added side is rendered (as `x`).
719        assert_eq!(markers_only(&out), vec!['x']);
720    }
721
722    #[test]
723    fn in_hunk_reformat_line_wrap() {
724        let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,2 @@\n-    println!(\"a {} b {}\", x, y);\n+    println!(\"a {} b {}\",\n+        x, y);\n";
725        let out = render(diff, GAP1, false).unwrap();
726        // Same here: the single removed line is dropped, leaving only the
727        // two wrapped added lines, both `x`.
728        assert_eq!(markers_only(&out), vec!['x', 'x']);
729    }
730
731    #[test]
732    fn cross_hunk_move_same_file() {
733        let diff = "--- a/f\n+++ b/f\n@@ -1,3 +1,2 @@\n-    long_distinctive_call_one();\n context_a\n@@ -10,2 +9,3 @@\n context_b\n+    long_distinctive_call_one();\n";
734        let out = render(diff, GAP1, false).unwrap();
735        assert_eq!(markers_only(&out), vec!['>', ' ', ' ', '<']);
736    }
737
738    #[test]
739    fn move_with_real_change_inside() {
740        let diff = concat!(
741            "--- a/f\n",
742            "+++ b/f\n",
743            "@@ -1,4 +1,2 @@\n",
744            "-    if order.items.is_empty() {\n",
745            "-        return Err(anyhow!(\"empty order\"));\n",
746            "-    }\n",
747            " context_a\n",
748            "@@ -10,1 +8,4 @@\n",
749            " context_b\n",
750            "+    if order.items.is_empty() {\n",
751            "+        return Err(anyhow!(\"order has no items\"));\n",
752            "+    }\n",
753        );
754        let out = render(diff, GAP1, false).unwrap();
755        // The matched run ("if order.items.is_empty() {" + "}") totals
756        // only 19 alphanumeric characters — just under
757        // MIN_MOVE_ALNUM_CHARS (20) — so it's left as plain `-`/`+`
758        // rather than tagged as a move.
759        assert_eq!(
760            markers_only(&out),
761            vec!['-', '-', '-', ' ', ' ', '+', '+', '+']
762        );
763    }
764
765    #[test]
766    fn move_with_real_change_exceeding_gap_is_not_linked() {
767        let diff = concat!(
768            "--- a/f\n",
769            "+++ b/f\n",
770            "@@ -1,5 +1,2 @@\n",
771            "-    if order.items.is_empty() {\n",
772            "-        totally different line one\n",
773            "-        totally different line two\n",
774            "-    }\n",
775            " context_a\n",
776            "@@ -10,1 +8,5 @@\n",
777            " context_b\n",
778            "+    if order.items.is_empty() {\n",
779            "+        something else entirely one\n",
780            "+        something else entirely two\n",
781            "+    }\n",
782        );
783        // max_move_gap = 1: two consecutive real changes in a row should
784        // stop extension before reaching the closing brace. The anchor
785        // alone totals only 19 alphanumeric characters — under
786        // MIN_MOVE_ALNUM_CHARS (20) — so it's left as plain `-`/`+`.
787        let out = render(diff, GAP1, false).unwrap();
788        assert_eq!(
789            markers_only(&out),
790            vec!['-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+']
791        );
792    }
793
794    #[test]
795    fn relative_gap_scales_with_block_size() {
796        // A 10-line moved block with 1 real change in the middle: an
797        // absolute gap of 1 would also allow this, but a relative gap large
798        // enough (50%) should too, while a tiny relative gap (5%, which
799        // ceils to 1 for a remaining length of ~4-5) still should — this
800        // mainly checks that Relative actually gets threaded through and
801        // produces a sane (non-zero) budget rather than panicking/always
802        // rejecting.
803        let diff = concat!(
804            "--- a/f\n",
805            "+++ b/f\n",
806            "@@ -1,6 +1,2 @@\n",
807            "-    line_one_in_the_block();\n",
808            "-    line_two_in_the_block();\n",
809            "-    totally_different_line();\n",
810            "-    line_four_in_the_block();\n",
811            "-    line_five_in_the_block();\n",
812            " context_a\n",
813            "@@ -20,1 +15,6 @@\n",
814            " context_b\n",
815            "+    line_one_in_the_block();\n",
816            "+    line_two_in_the_block();\n",
817            "+    something_else_entirely();\n",
818            "+    line_four_in_the_block();\n",
819            "+    line_five_in_the_block();\n",
820        );
821        let out = render(diff, MoveGap::Relative(0.5), false).unwrap();
822        assert_eq!(
823            markers_only(&out),
824            vec!['>', '>', '-', '>', '>', ' ', ' ', '<', '<', '+', '<', '<']
825        );
826    }
827
828    #[test]
829    fn zero_gap_means_no_tolerance() {
830        let diff = concat!(
831            "--- a/f\n",
832            "+++ b/f\n",
833            "@@ -1,3 +1,2 @@\n",
834            "-    line_one_in_the_block();\n",
835            "-    totally_different_line();\n",
836            " context_a\n",
837            "@@ -20,1 +15,3 @@\n",
838            " context_b\n",
839            "+    line_one_in_the_block();\n",
840            "+    something_else_entirely();\n",
841        );
842        let out = render(diff, MoveGap::Absolute(0), false).unwrap();
843        // Anchor-only match ("line_one_in_the_block();", 17 alphanumeric
844        // characters) stays under MIN_MOVE_ALNUM_CHARS (20), so it's left
845        // as plain `-`/`+` regardless of the zero gap tolerance.
846        assert_eq!(markers_only(&out), vec!['-', '-', ' ', ' ', '+', '+']);
847    }
848
849    #[test]
850    fn coincidental_short_line_in_a_large_edit_block_is_not_tagged_as_moved() {
851        // A block of 10 genuinely-rewritten lines where exactly one
852        // removed line happens to also appear, verbatim, among 10
853        // unrelated added lines elsewhere — the "single line moved in a
854        // block of 10 removals" false positive this threshold exists to
855        // suppress. "return false;" is anchor-eligible (12 non-whitespace
856        // chars) but only 11 alphanumeric characters, under
857        // MIN_MOVE_ALNUM_CHARS (20), and none of its neighbors match
858        // anything either, so extension can't grow the run. It must stay
859        // plain `-`/`+`, not `>`/`<`.
860        let diff = concat!(
861            "--- a/f\n",
862            "+++ b/f\n",
863            "@@ -1,10 +1,2 @@\n",
864            "-    validate_order_header(&order);\n",
865            "-    validate_order_items(&order);\n",
866            "-    validate_order_total(&order);\n",
867            "-    validate_order_address(&order);\n",
868            "-    return false;\n",
869            "-    validate_order_payment(&order);\n",
870            "-    validate_order_shipping(&order);\n",
871            "-    validate_order_discount(&order);\n",
872            "-    validate_order_customer(&order);\n",
873            "-    validate_order_metadata(&order);\n",
874            " context_a\n",
875            "@@ -20,1 +15,10 @@\n",
876            " context_b\n",
877            "+    check_header_valid(&order);\n",
878            "+    check_items_valid(&order);\n",
879            "+    check_total_valid(&order);\n",
880            "+    return false;\n",
881            "+    check_address_valid(&order);\n",
882            "+    check_payment_valid(&order);\n",
883            "+    check_shipping_valid(&order);\n",
884            "+    check_discount_valid(&order);\n",
885            "+    check_customer_valid(&order);\n",
886            "+    check_metadata_valid(&order);\n",
887        );
888        let out = render(diff, GAP1, false).unwrap();
889        assert_eq!(
890            markers_only(&out),
891            vec![
892                '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+',
893                '+', '+', '+', '+', '+', '+',
894            ]
895        );
896    }
897
898    #[test]
899    fn long_enough_single_line_in_a_large_edit_block_is_still_tagged_as_moved() {
900        // Same shape as the test above — one matching line surrounded by
901        // 9 unrelated real edits on each side, no extension possible —
902        // but the matching line itself is long enough on its own
903        // (`log_security_audit_violation(&order);`, 25 alphanumeric
904        // characters) to clear MIN_MOVE_ALNUM_CHARS (20). This confirms
905        // the threshold is purely about match length, not about whether
906        // the surrounding block is otherwise "pure": a sufficiently
907        // distinctive single-line match is still a real move signal even
908        // inside a block of unrelated changes.
909        let diff = concat!(
910            "--- a/f\n",
911            "+++ b/f\n",
912            "@@ -1,10 +1,2 @@\n",
913            "-    validate_order_header(&order);\n",
914            "-    validate_order_items(&order);\n",
915            "-    validate_order_total(&order);\n",
916            "-    log_security_audit_violation(&order);\n",
917            "-    validate_order_payment(&order);\n",
918            "-    validate_order_shipping(&order);\n",
919            "-    validate_order_discount(&order);\n",
920            "-    validate_order_customer(&order);\n",
921            "-    validate_order_metadata(&order);\n",
922            "-    validate_order_currency(&order);\n",
923            " context_a\n",
924            "@@ -20,1 +15,10 @@\n",
925            " context_b\n",
926            "+    check_header_valid(&order);\n",
927            "+    check_items_valid(&order);\n",
928            "+    check_total_valid(&order);\n",
929            "+    check_address_valid(&order);\n",
930            "+    check_payment_valid(&order);\n",
931            "+    check_shipping_valid(&order);\n",
932            "+    log_security_audit_violation(&order);\n",
933            "+    check_discount_valid(&order);\n",
934            "+    check_customer_valid(&order);\n",
935            "+    check_metadata_valid(&order);\n",
936        );
937        let out = render(diff, GAP1, false).unwrap();
938        assert_eq!(
939            markers_only(&out),
940            vec![
941                '-', '-', '-', '>', '-', '-', '-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+',
942                '+', '+', '<', '+', '+', '+',
943            ]
944        );
945    }
946
947    #[test]
948    fn parse_absolute_integer() {
949        assert_eq!("1".parse::<MoveGap>().unwrap(), MoveGap::Absolute(1));
950        assert_eq!("2".parse::<MoveGap>().unwrap(), MoveGap::Absolute(2));
951        assert_eq!("0".parse::<MoveGap>().unwrap(), MoveGap::Relative(0.0));
952    }
953
954    #[test]
955    fn parse_relative_percentage() {
956        match "10%".parse::<MoveGap>().unwrap() {
957            MoveGap::Relative(r) => assert!((r - 0.10).abs() < f64::EPSILON),
958            other => panic!("expected Relative, got {other:?}"),
959        }
960    }
961
962    #[test]
963    fn parse_relative_fraction() {
964        match "0.1".parse::<MoveGap>().unwrap() {
965            MoveGap::Relative(r) => assert!((r - 0.1).abs() < f64::EPSILON),
966            other => panic!("expected Relative, got {other:?}"),
967        }
968    }
969
970    #[test]
971    fn parse_rejects_negative_and_garbage() {
972        assert!("-1".parse::<MoveGap>().is_err());
973        assert!("abc".parse::<MoveGap>().is_err());
974        assert!("-5%".parse::<MoveGap>().is_err());
975    }
976
977    #[test]
978    fn missing_trailing_newline_does_not_panic() {
979        // `git::local_diff` strips the trailing newline (duct's `.read()`
980        // behaves like shell `$()`); the `patch` crate's parser panics on
981        // that unless we restore it. Regression test for that fix.
982        let diff = "--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n-old\n+new\n trailing context, no newline after this";
983        let out = render(diff, GAP1, false).unwrap();
984        assert_eq!(markers_only(&out), vec!['-', '+', ' ']);
985    }
986
987    #[test]
988    fn unparseable_input_falls_back_to_plain_text_instead_of_erroring() {
989        let not_a_diff = "this is not a unified diff at all\njust some text\n";
990        let out = render(not_a_diff, GAP1, false).unwrap();
991        assert_eq!(out, not_a_diff);
992    }
993
994    #[test]
995    fn one_unparseable_file_falls_back_without_losing_annotations_for_others() {
996        // A normal text-hunk file followed by a binary file, each with its
997        // own `diff --git` header as real `git diff` output would produce.
998        // Regression test for "one bad file nukes annotations for the
999        // whole diff": the binary entry should fall back to its raw text
1000        // while the text file is still fully annotated.
1001        let diff = concat!(
1002            "diff --git a/f b/f\n",
1003            "--- a/f\n",
1004            "+++ b/f\n",
1005            "@@ -1,2 +1,2 @@\n",
1006            "-foo bar baz\n",
1007            "+quux bar baz\n",
1008            " context\n",
1009            "diff --git a/img.png b/img.png\n",
1010            "index 111..222 100644\n",
1011            "Binary files a/img.png and b/img.png differ\n",
1012        );
1013        let out = render(diff, GAP1, false).unwrap();
1014        // The text file is still parsed and annotated normally (not just
1015        // echoed verbatim): its hunk header is reconstructed by the
1016        // `patch` crate's `Display` impl rather than preserved byte-for-
1017        // byte.
1018        assert!(out.contains("-foo bar baz\n"), "got: {out}");
1019        assert!(out.contains("+quux bar baz\n"), "got: {out}");
1020        // The binary file's entry is preserved verbatim since it can't be
1021        // parsed into annotated hunks.
1022        assert!(
1023            out.contains("Binary files a/img.png and b/img.png differ\n"),
1024            "got: {out}"
1025        );
1026    }
1027
1028    #[test]
1029    fn single_chunk_with_no_git_header_still_recovers_from_parser_panic() {
1030        // Without a `diff --git` separator between the hunk and the binary
1031        // marker, this whole input is one unparseable chunk (see
1032        // `diff_parse::tests::parse_patches_safely_catches_parser_panic_on_binary_file_entry`).
1033        // `render` must still recover via `catch_unwind` and fall back to
1034        // the raw text instead of crashing.
1035        let diff = concat!(
1036            "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
1037            "Binary files a/img.png and b/img.png differ\n",
1038        );
1039        let out = render(diff, GAP1, false).unwrap();
1040        assert_eq!(out, diff);
1041    }
1042}