move-diff 0.3.0

Render a git diff with extra markers for moved and reformatted code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
//! Annotates a unified diff with extra markers for moved and reformatted
//! code, on top of the usual `+`/`-` lines, to make large mechanical
//! refactors easier to review.
//!
//! Marker legend:
//! - `' '` context  (unchanged)
//! - `'+'` addition (green)   — genuinely new content
//! - `'-'` removal  (red)     — genuinely removed content
//! - `'>'` moved out (cyan)   — this line left its old spot
//! - `'<'` moved in  (blue)   — this line arrived from elsewhere
//! - `'x'` reformat (magenta) — same content, only whitespace/layout changed;
//!   only the new side is shown (the old side would be a whitespace-only
//!   duplicate, so it's dropped rather than printed twice)
//!
//! Detection runs in three passes over each hunk's "change blocks" (a run of
//! consecutive removed lines immediately followed by a run of consecutive
//! added lines):
//!
//! 1. Whole-block reformat: if a block's removed lines and added lines are
//!    identical once all whitespace is stripped, the entire block is a pure
//!    reflow (handles reindentation and a linter wrapping/joining lines)
//!    and gets `x`.
//! 2. Global move detection: lines left over after pass 1 are matched,
//!    whitespace-normalized, against lines in *other* blocks (any file). A
//!    match seeds an anchor that is then extended line-by-line in both
//!    directions within its block; forward extension tolerates a small
//!    reflow window (so a moved line that was also split/joined still
//!    counts as moved) and a configurable number of lines that differ for
//!    real — an edit made during the move — before giving up. The
//!    resulting run is only accepted as a move once it totals at least
//!    `MIN_MOVE_ALNUM_CHARS` alphanumeric characters — the same rule
//!    `git diff --color-moved`'s `blocks`/`zebra` modes use — otherwise
//!    it's left as plain `+`/`-` and the next matching candidate (if any)
//!    is tried instead.
//! 3. Local leftover reconciliation: whatever remains unconsumed within a
//!    single block is re-paired against the rest of that same block
//!    (whitespace-normalized) to catch an in-place reformat sitting right
//!    next to a move or a genuine addition. Anything still unpaired is a
//!    plain addition/removal.

use std::collections::HashMap;
use std::fmt;
use std::ops::Range;
use std::str::FromStr;

use anyhow::Result;
use patch::{Line as PatchLine, Patch};

use crate::diff_parse::{parse_patches_safely, split_file_diffs};

/// Minimum number of non-whitespace characters a line needs before it's
/// trusted as a move *anchor* on its own. Short/common lines (`}`, `{`,
/// blank lines) are too likely to collide; they can still be swept into a
/// moved block once extension reaches them from a trustworthy anchor.
const MIN_ANCHOR_LEN: usize = 8;

/// Minimum number of alphanumeric characters a matched run must contain,
/// summed across every line it ends up covering, before it's accepted as
/// a move rather than left as plain `+`/`-`.
///
/// Mirrors `git diff --color-moved`'s `blocks`/`zebra` modes exactly: same
/// threshold, same metric (letters + digits only — punctuation and
/// whitespace don't count), same hardcoded, unconfigurable constant. Below
/// this, a match is indistinguishable from a coincidentally-duplicated
/// short/common line sitting inside an unrelated block of real edits.
const MIN_MOVE_ALNUM_CHARS: usize = 20;

/// How many lines we're willing to try merging/splitting on either side
/// when checking whether a mismatch during block extension is actually a
/// pure reflow (e.g. a linter wrapping a long line into several).
const MAX_REFLOW_WINDOW: usize = 10;

/// How many real content changes are tolerated inside an otherwise-moved
/// block before move detection gives up extending into that block (lines
/// beyond this fall back to plain `+`/`-`).
///
/// Accepts either an absolute line count or a fraction/percentage of the
/// remaining block length in whichever direction extension is currently
/// going — a flat count under-tolerates large moved blocks that picked up
/// a handful of real edits, while a fraction scales with the block.
///
/// Parsed from a string: a trailing `%` means relative (`"10%"` → 0.10), a
/// bare value `< 1` is also relative (`"0.1"` is the same as `"10%"`), and
/// a bare value `>= 1` is an absolute count (`"2"` → tolerate 2 lines).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum MoveGap {
    Absolute(usize),
    Relative(f64),
}

impl MoveGap {
    /// The tolerance budget for a direction with `remaining_len` lines left
    /// before the enclosing block's boundary.
    fn budget_for(&self, remaining_len: usize) -> usize {
        match self {
            MoveGap::Absolute(n) => *n,
            // `ceil` means any ratio > 0 yields a budget >= 1 as soon as
            // there's at least one line left to extend into, with no need
            // for a separate hardcoded floor — while an explicit ratio of
            // exactly 0 still means exactly zero tolerance.
            MoveGap::Relative(ratio) => (ratio * remaining_len as f64).ceil() as usize,
        }
    }
}

impl FromStr for MoveGap {
    type Err = String;

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        let s = s.trim();
        if let Some(pct) = s.strip_suffix('%') {
            let v: f64 = pct
                .trim()
                .parse()
                .map_err(|_| format!("invalid percentage: {s}"))?;
            if v < 0.0 {
                return Err(format!("percentage must be >= 0: {s}"));
            }
            return Ok(MoveGap::Relative(v / 100.0));
        }
        let v: f64 = s.parse().map_err(|_| format!("invalid number: {s}"))?;
        if v < 0.0 {
            return Err(format!("value must be >= 0: {s}"));
        }
        if v >= 1.0 {
            Ok(MoveGap::Absolute(v.round() as usize))
        } else {
            Ok(MoveGap::Relative(v))
        }
    }
}

impl fmt::Display for MoveGap {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MoveGap::Absolute(n) => write!(f, "{n}"),
            MoveGap::Relative(ratio) => write!(f, "{}%", ratio * 100.0),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Marker {
    Add,
    Remove,
    MovedOut,
    MovedIn,
    Reformat,
}

/// One changed (non-context) line inside a hunk.
#[derive(Debug, Clone)]
struct ChangedLine {
    text: String,
    marker: Marker,
    /// Index into the global `blocks` vector.
    block: usize,
}

/// A maximal run of consecutive removed lines immediately followed by a
/// maximal run of consecutive added lines, inside a single hunk.
#[derive(Debug, Clone)]
struct Block {
    removes: Range<usize>,
    adds: Range<usize>,
}

/// One element of a file's rendered hunk, in original diff order.
enum RenderLine {
    Context(String),
    Removed(usize),
    Added(usize),
}

struct FileHunks {
    old_path: String,
    new_path: String,
    hunks: Vec<(String, Vec<RenderLine>)>,
}

/// One entry of the top-level diff, in original order: either a
/// successfully parsed file (indexing into the parallel `files`/patch
/// vectors) or the raw, unparsed text of a file whose entry couldn't be
/// parsed (binary diff, mode-only change, pure rename, ...).
enum Unit<'a> {
    Parsed(usize),
    Raw(&'a str),
}

fn normalize(s: &str) -> String {
    s.chars().filter(|c| !c.is_whitespace()).collect()
}

fn is_anchor_eligible(s: &str) -> bool {
    normalize(s).chars().count() >= MIN_ANCHOR_LEN
}

fn alnum_len(s: &str) -> usize {
    s.chars().filter(|c| c.is_alphanumeric()).count()
}

/// Render `diff_text` (as produced by `git diff`) with move/reformat
/// annotations.
///
/// `max_move_gap` bounds how many real (non-reflow) content changes are
/// tolerated inside an otherwise-moved block before extension gives up.
/// `color` enables ANSI colors.
///
/// Falls back to printing a file's own diff entry unannotated (with a
/// warning on stderr) if that entry can't be parsed (e.g. a binary diff,
/// mode-only change, or pure rename), rather than failing outright or
/// discarding annotations for the rest of the diff — this is best-effort
/// tooling on top of `git diff`, and one file's parser limitation
/// shouldn't make every other file's diff unreadable.
pub fn render(diff_text: &str, max_move_gap: MoveGap, color: bool) -> Result<String> {
    // `git::local_diff` captures output via `duct`'s `.read()`, which (like
    // shell `$()`) strips the trailing newline — but the `patch` crate's
    // parser requires every line, including the last, to be newline
    // terminated and *panics* (via an internal `assert!`, not a `Result`)
    // if it isn't. Restoring the newline here fixes the overwhelmingly
    // common case (any diff ending in a context line, which is most of
    // them with the default 3-line context).
    let diff_text = if diff_text.ends_with('\n') {
        diff_text.to_string()
    } else {
        format!("{diff_text}\n")
    };

    let patches: Vec<Patch<'_>>;
    let mut units: Vec<Unit<'_>> = Vec::new();
    {
        let mut collected = Vec::new();
        for chunk in split_file_diffs(&diff_text) {
            match parse_patches_safely(chunk) {
                Ok(parsed) => {
                    for p in parsed {
                        units.push(Unit::Parsed(collected.len()));
                        collected.push(p);
                    }
                }
                Err(msg) => {
                    eprintln!("warning: move-diff: {msg}; showing this file's plain diff instead");
                    units.push(Unit::Raw(chunk));
                }
            }
        }
        patches = collected;
    }

    let mut removes: Vec<ChangedLine> = Vec::new();
    let mut adds: Vec<ChangedLine> = Vec::new();
    let mut blocks: Vec<Block> = Vec::new();
    let mut files: Vec<FileHunks> = Vec::new();

    for patch in &patches {
        let mut hunks_out = Vec::new();

        for hunk in &patch.hunks {
            let mut render_lines: Vec<RenderLine> = Vec::new();

            let mut pend_remove_start: Option<usize> = None;
            let mut pend_add_start: Option<usize> = None;
            let mut seen_add_in_block = false;

            for line in &hunk.lines {
                match line {
                    PatchLine::Context(text) => {
                        flush_block(
                            &mut pend_remove_start,
                            &mut pend_add_start,
                            &mut seen_add_in_block,
                            &mut removes,
                            &mut adds,
                            &mut blocks,
                        );
                        render_lines.push(RenderLine::Context(format!(" {text}")));
                    }
                    PatchLine::Remove(text) => {
                        if seen_add_in_block {
                            // A new remove run started without a context
                            // line separating it from the previous block's
                            // adds: treat it as a new block.
                            flush_block(
                                &mut pend_remove_start,
                                &mut pend_add_start,
                                &mut seen_add_in_block,
                                &mut removes,
                                &mut adds,
                                &mut blocks,
                            );
                        }
                        if pend_remove_start.is_none() {
                            pend_remove_start = Some(removes.len());
                        }
                        render_lines.push(RenderLine::Removed(removes.len()));
                        removes.push(ChangedLine {
                            text: text.to_string(),
                            marker: Marker::Remove,
                            block: usize::MAX,
                        });
                    }
                    PatchLine::Add(text) => {
                        if pend_add_start.is_none() {
                            pend_add_start = Some(adds.len());
                        }
                        seen_add_in_block = true;
                        render_lines.push(RenderLine::Added(adds.len()));
                        adds.push(ChangedLine {
                            text: text.to_string(),
                            marker: Marker::Add,
                            block: usize::MAX,
                        });
                    }
                }
            }
            flush_block(
                &mut pend_remove_start,
                &mut pend_add_start,
                &mut seen_add_in_block,
                &mut removes,
                &mut adds,
                &mut blocks,
            );

            hunks_out.push((
                format!(
                    "@@ -{} +{} @@{}",
                    hunk.old_range, hunk.new_range, hunk.range_hint
                ),
                render_lines,
            ));
        }

        files.push(FileHunks {
            old_path: patch.old.to_string(),
            new_path: patch.new.to_string(),
            hunks: hunks_out,
        });
    }

    // Pass 1: whole-block reformat.
    for block in &blocks {
        if block.removes.is_empty() || block.adds.is_empty() {
            continue;
        }
        let old_sig: String = removes[block.removes.clone()]
            .iter()
            .map(|l| normalize(&l.text))
            .collect();
        let new_sig: String = adds[block.adds.clone()]
            .iter()
            .map(|l| normalize(&l.text))
            .collect();
        if old_sig == new_sig {
            for l in removes[block.removes.clone()].iter_mut() {
                l.marker = Marker::Reformat;
            }
            for l in adds[block.adds.clone()].iter_mut() {
                l.marker = Marker::Reformat;
            }
        }
    }

    // Pass 2: global move detection (anchor + extend).
    detect_moves(&mut removes, &mut adds, &blocks, max_move_gap);

    // Pass 3: local leftover reconciliation.
    for block in &blocks {
        reconcile_leftovers(
            &mut removes,
            block.removes.clone(),
            &mut adds,
            block.adds.clone(),
        );
    }

    Ok(render_output(&units, &files, &removes, &adds, color))
}

fn flush_block(
    pend_remove_start: &mut Option<usize>,
    pend_add_start: &mut Option<usize>,
    seen_add_in_block: &mut bool,
    removes: &mut [ChangedLine],
    adds: &mut [ChangedLine],
    blocks: &mut Vec<Block>,
) {
    // A block exists as soon as there's *either* a pending remove run or a
    // pending add run — a run of pure additions (no removes before it) is
    // just as much a block as a run with both sides.
    if pend_remove_start.is_some() || pend_add_start.is_some() {
        let rs = pend_remove_start.take().unwrap_or(removes.len());
        let as_ = pend_add_start.take().unwrap_or(adds.len());
        let r_range = rs..removes.len();
        let a_range = as_..adds.len();
        let block_idx = blocks.len();
        for r in removes[r_range.clone()].iter_mut() {
            r.block = block_idx;
        }
        for a in adds[a_range.clone()].iter_mut() {
            a.block = block_idx;
        }
        blocks.push(Block {
            removes: r_range,
            adds: a_range,
        });
    }
    *seen_add_in_block = false;
}

fn try_reflow(
    removes: &[ChangedLine],
    r_end: usize,
    ri: usize,
    adds: &[ChangedLine],
    a_end: usize,
    ai: usize,
) -> Option<(usize, usize)> {
    for total in 2..=(MAX_REFLOW_WINDOW * 2) {
        let ro_max = MAX_REFLOW_WINDOW.min(total - 1);
        for ro in 1..=ro_max {
            let ao = total - ro;
            if ao == 0 || ao > MAX_REFLOW_WINDOW {
                continue;
            }
            if ri + ro > r_end || ai + ao > a_end {
                continue;
            }
            if removes[ri..ri + ro]
                .iter()
                .any(|l| l.marker != Marker::Remove)
                || adds[ai..ai + ao].iter().any(|l| l.marker != Marker::Add)
            {
                continue;
            }
            let old_sig: String = removes[ri..ri + ro]
                .iter()
                .map(|l| normalize(&l.text))
                .collect();
            let new_sig: String = adds[ai..ai + ao]
                .iter()
                .map(|l| normalize(&l.text))
                .collect();
            if old_sig == new_sig {
                return Some((ro, ao));
            }
        }
    }
    None
}

fn detect_moves(
    removes: &mut [ChangedLine],
    adds: &mut [ChangedLine],
    blocks: &[Block],
    max_move_gap: MoveGap,
) {
    // Index every added line by its whitespace-normalized text once, up
    // front, instead of rescanning the whole `adds` slice from scratch for
    // every anchor attempt (that used to make this O(matches × R × A)). A
    // stale entry (pointing at a line already consumed elsewhere) is cheap
    // to detect per-candidate via the marker check below, so there's no
    // need to prune the index as lines get consumed.
    let mut add_index: HashMap<String, Vec<usize>> = HashMap::new();
    for (j, a) in adds.iter().enumerate() {
        add_index.entry(normalize(&a.text)).or_default().push(j);
    }

    // A single forward pass over `removes`: once visited here (whether it
    // became an anchor or not), a line never needs revisiting — markers
    // only ever move away from `Remove`, never back to it, so a line that
    // wasn't eligible (or whose candidates all got rejected) now can't
    // become eligible on some later, repeated pass.
    for r_anchor in 0..removes.len() {
        if removes[r_anchor].marker != Marker::Remove
            || !is_anchor_eligible(&removes[r_anchor].text)
        {
            continue;
        }
        let key = normalize(&removes[r_anchor].text);
        let r_block_idx = removes[r_anchor].block;
        let Some(candidates) = add_index.get(&key) else {
            continue;
        };

        for &a_anchor in candidates {
            if adds[a_anchor].marker != Marker::Add || adds[a_anchor].block == r_block_idx {
                continue;
            }

            let r_block = blocks[r_block_idx].clone();
            let a_block = blocks[adds[a_anchor].block].clone();

            // Measure the run first, without mutating anything, so a run
            // that doesn't clear MIN_MOVE_ALNUM_CHARS can be left exactly
            // as-is and the next candidate (if any) tried instead.
            let mut moved_r = vec![r_anchor];
            let mut moved_a = vec![a_anchor];

            // Extend forward.
            let mut ri = r_anchor + 1;
            let mut ai = a_anchor + 1;
            let fwd_remaining = (r_block.removes.end - ri).min(a_block.adds.end.saturating_sub(ai));
            let mut gap_budget = max_move_gap.budget_for(fwd_remaining);
            while ri < r_block.removes.end && ai < a_block.adds.end {
                if removes[ri].marker != Marker::Remove || adds[ai].marker != Marker::Add {
                    break;
                }
                if normalize(&removes[ri].text) == normalize(&adds[ai].text) {
                    moved_r.push(ri);
                    moved_a.push(ai);
                    ri += 1;
                    ai += 1;
                    continue;
                }
                if let Some((rn, an)) =
                    try_reflow(removes, r_block.removes.end, ri, adds, a_block.adds.end, ai)
                {
                    moved_r.extend(ri..ri + rn);
                    moved_a.extend(ai..ai + an);
                    ri += rn;
                    ai += an;
                    continue;
                }
                if gap_budget == 0 {
                    break;
                }
                gap_budget -= 1;
                ri += 1;
                ai += 1;
            }

            // Extend backward (exact matches only — a reflow at the start
            // of a moved block is rare enough that tracking variable-size
            // backward windows isn't worth the complexity for v1).
            let mut ri = r_anchor;
            let mut ai = a_anchor;
            let back_remaining =
                (ri - r_block.removes.start).min(ai.saturating_sub(a_block.adds.start));
            let mut gap_budget = max_move_gap.budget_for(back_remaining);
            while ri > r_block.removes.start && ai > a_block.adds.start {
                let pri = ri - 1;
                let pai = ai - 1;
                if removes[pri].marker != Marker::Remove || adds[pai].marker != Marker::Add {
                    break;
                }
                if normalize(&removes[pri].text) == normalize(&adds[pai].text) {
                    moved_r.push(pri);
                    moved_a.push(pai);
                    ri = pri;
                    ai = pai;
                    continue;
                }
                if gap_budget == 0 {
                    break;
                }
                gap_budget -= 1;
                ri = pri;
                ai = pai;
            }

            // Same rule as `git diff --color-moved`'s `blocks`/`zebra`
            // modes: a matched run is only painted as moved once it
            // totals at least MIN_MOVE_ALNUM_CHARS alphanumeric
            // characters. Below that, it's indistinguishable from a
            // coincidentally-duplicated short/common line sitting inside
            // an unrelated block of real edits — try the next candidate
            // add for this same anchor (if any) instead of committing.
            let total_alnum: usize = moved_r.iter().map(|&i| alnum_len(&removes[i].text)).sum();
            if total_alnum < MIN_MOVE_ALNUM_CHARS {
                continue;
            }

            for &i in &moved_r {
                removes[i].marker = Marker::MovedOut;
            }
            for &j in &moved_a {
                adds[j].marker = Marker::MovedIn;
            }
            break;
        }
    }
}

fn reconcile_leftovers(
    removes: &mut [ChangedLine],
    r_range: Range<usize>,
    adds: &mut [ChangedLine],
    a_range: Range<usize>,
) {
    let add_indices: Vec<usize> = a_range.collect();
    let mut used = vec![false; add_indices.len()];

    for ri in r_range {
        if removes[ri].marker != Marker::Remove {
            continue;
        }
        let key = normalize(&removes[ri].text);
        if let Some(pos) = add_indices.iter().enumerate().position(|(k, &ai)| {
            !used[k] && adds[ai].marker == Marker::Add && normalize(&adds[ai].text) == key
        }) {
            used[pos] = true;
            removes[ri].marker = Marker::Reformat;
            adds[add_indices[pos]].marker = Marker::Reformat;
        }
    }
}

fn render_output(
    units: &[Unit<'_>],
    files: &[FileHunks],
    removes: &[ChangedLine],
    adds: &[ChangedLine],
    color: bool,
) -> String {
    let mut out = String::new();
    for unit in units {
        match unit {
            Unit::Raw(text) => out.push_str(text),
            Unit::Parsed(idx) => render_file(&mut out, &files[*idx], removes, adds, color),
        }
    }
    out
}

fn render_file(
    out: &mut String,
    file: &FileHunks,
    removes: &[ChangedLine],
    adds: &[ChangedLine],
    color: bool,
) {
    out.push_str(&format!("--- {}\n", file.old_path));
    out.push_str(&format!("+++ {}\n", file.new_path));
    for (header, lines) in &file.hunks {
        out.push_str(header);
        out.push('\n');
        for rl in lines {
            match rl {
                RenderLine::Context(text) => {
                    out.push_str(text);
                    out.push('\n');
                }
                RenderLine::Removed(i) => {
                    let line = &removes[*i];
                    // A reformat's removed side is a whitespace-only
                    // duplicate of its added side (that's the definition of
                    // `Marker::Reformat`); printing both would show the same
                    // content twice, so only the added/new side is kept.
                    if line.marker != Marker::Reformat {
                        render_changed_line(out, line, color);
                    }
                }
                RenderLine::Added(i) => render_changed_line(out, &adds[*i], color),
            }
        }
    }
}

fn render_changed_line(out: &mut String, line: &ChangedLine, color: bool) {
    let (ch, code) = match line.marker {
        Marker::Remove => ('-', "31"),
        Marker::Add => ('+', "32"),
        Marker::MovedOut => ('>', "36"),
        Marker::MovedIn => ('<', "34"),
        Marker::Reformat => ('x', "35"),
    };
    if color {
        out.push_str(&format!("\x1b[{code}m{ch}{}\x1b[0m\n", line.text));
    } else {
        out.push_str(&format!("{ch}{}\n", line.text));
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strip_ansi(s: &str) -> String {
        let mut out = String::new();
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            if c == '\x1b' {
                for n in chars.by_ref() {
                    if n == 'm' {
                        break;
                    }
                }
                continue;
            }
            out.push(c);
        }
        out
    }

    fn markers_only(rendered: &str) -> Vec<char> {
        strip_ansi(rendered)
            .lines()
            .filter(|l| !l.starts_with("---") && !l.starts_with("+++") && !l.starts_with("@@"))
            .map(|l| l.chars().next().unwrap_or(' '))
            .collect()
    }

    const GAP1: MoveGap = MoveGap::Absolute(1);

    #[test]
    fn plain_add_remove() {
        let diff = "--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n-foo bar baz\n+quux bar baz\n context\n";
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(markers_only(&out), vec!['-', '+', ' ']);
    }

    #[test]
    fn in_hunk_reformat_single_line() {
        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";
        let out = render(diff, GAP1, false).unwrap();
        // The removed side is a whitespace-only duplicate of the added
        // side, so only the added side is rendered (as `x`).
        assert_eq!(markers_only(&out), vec!['x']);
    }

    #[test]
    fn in_hunk_reformat_line_wrap() {
        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";
        let out = render(diff, GAP1, false).unwrap();
        // Same here: the single removed line is dropped, leaving only the
        // two wrapped added lines, both `x`.
        assert_eq!(markers_only(&out), vec!['x', 'x']);
    }

    #[test]
    fn cross_hunk_move_same_file() {
        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";
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(markers_only(&out), vec!['>', ' ', ' ', '<']);
    }

    #[test]
    fn move_with_real_change_inside() {
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,4 +1,2 @@\n",
            "-    if order.items.is_empty() {\n",
            "-        return Err(anyhow!(\"empty order\"));\n",
            "-    }\n",
            " context_a\n",
            "@@ -10,1 +8,4 @@\n",
            " context_b\n",
            "+    if order.items.is_empty() {\n",
            "+        return Err(anyhow!(\"order has no items\"));\n",
            "+    }\n",
        );
        let out = render(diff, GAP1, false).unwrap();
        // The matched run ("if order.items.is_empty() {" + "}") totals
        // only 19 alphanumeric characters — just under
        // MIN_MOVE_ALNUM_CHARS (20) — so it's left as plain `-`/`+`
        // rather than tagged as a move.
        assert_eq!(
            markers_only(&out),
            vec!['-', '-', '-', ' ', ' ', '+', '+', '+']
        );
    }

    #[test]
    fn move_with_real_change_exceeding_gap_is_not_linked() {
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,5 +1,2 @@\n",
            "-    if order.items.is_empty() {\n",
            "-        totally different line one\n",
            "-        totally different line two\n",
            "-    }\n",
            " context_a\n",
            "@@ -10,1 +8,5 @@\n",
            " context_b\n",
            "+    if order.items.is_empty() {\n",
            "+        something else entirely one\n",
            "+        something else entirely two\n",
            "+    }\n",
        );
        // max_move_gap = 1: two consecutive real changes in a row should
        // stop extension before reaching the closing brace. The anchor
        // alone totals only 19 alphanumeric characters — under
        // MIN_MOVE_ALNUM_CHARS (20) — so it's left as plain `-`/`+`.
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(
            markers_only(&out),
            vec!['-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+']
        );
    }

    #[test]
    fn relative_gap_scales_with_block_size() {
        // A 10-line moved block with 1 real change in the middle: an
        // absolute gap of 1 would also allow this, but a relative gap large
        // enough (50%) should too, while a tiny relative gap (5%, which
        // ceils to 1 for a remaining length of ~4-5) still should — this
        // mainly checks that Relative actually gets threaded through and
        // produces a sane (non-zero) budget rather than panicking/always
        // rejecting.
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,6 +1,2 @@\n",
            "-    line_one_in_the_block();\n",
            "-    line_two_in_the_block();\n",
            "-    totally_different_line();\n",
            "-    line_four_in_the_block();\n",
            "-    line_five_in_the_block();\n",
            " context_a\n",
            "@@ -20,1 +15,6 @@\n",
            " context_b\n",
            "+    line_one_in_the_block();\n",
            "+    line_two_in_the_block();\n",
            "+    something_else_entirely();\n",
            "+    line_four_in_the_block();\n",
            "+    line_five_in_the_block();\n",
        );
        let out = render(diff, MoveGap::Relative(0.5), false).unwrap();
        assert_eq!(
            markers_only(&out),
            vec!['>', '>', '-', '>', '>', ' ', ' ', '<', '<', '+', '<', '<']
        );
    }

    #[test]
    fn zero_gap_means_no_tolerance() {
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,3 +1,2 @@\n",
            "-    line_one_in_the_block();\n",
            "-    totally_different_line();\n",
            " context_a\n",
            "@@ -20,1 +15,3 @@\n",
            " context_b\n",
            "+    line_one_in_the_block();\n",
            "+    something_else_entirely();\n",
        );
        let out = render(diff, MoveGap::Absolute(0), false).unwrap();
        // Anchor-only match ("line_one_in_the_block();", 17 alphanumeric
        // characters) stays under MIN_MOVE_ALNUM_CHARS (20), so it's left
        // as plain `-`/`+` regardless of the zero gap tolerance.
        assert_eq!(markers_only(&out), vec!['-', '-', ' ', ' ', '+', '+']);
    }

    #[test]
    fn coincidental_short_line_in_a_large_edit_block_is_not_tagged_as_moved() {
        // A block of 10 genuinely-rewritten lines where exactly one
        // removed line happens to also appear, verbatim, among 10
        // unrelated added lines elsewhere — the "single line moved in a
        // block of 10 removals" false positive this threshold exists to
        // suppress. "return false;" is anchor-eligible (12 non-whitespace
        // chars) but only 11 alphanumeric characters, under
        // MIN_MOVE_ALNUM_CHARS (20), and none of its neighbors match
        // anything either, so extension can't grow the run. It must stay
        // plain `-`/`+`, not `>`/`<`.
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,10 +1,2 @@\n",
            "-    validate_order_header(&order);\n",
            "-    validate_order_items(&order);\n",
            "-    validate_order_total(&order);\n",
            "-    validate_order_address(&order);\n",
            "-    return false;\n",
            "-    validate_order_payment(&order);\n",
            "-    validate_order_shipping(&order);\n",
            "-    validate_order_discount(&order);\n",
            "-    validate_order_customer(&order);\n",
            "-    validate_order_metadata(&order);\n",
            " context_a\n",
            "@@ -20,1 +15,10 @@\n",
            " context_b\n",
            "+    check_header_valid(&order);\n",
            "+    check_items_valid(&order);\n",
            "+    check_total_valid(&order);\n",
            "+    return false;\n",
            "+    check_address_valid(&order);\n",
            "+    check_payment_valid(&order);\n",
            "+    check_shipping_valid(&order);\n",
            "+    check_discount_valid(&order);\n",
            "+    check_customer_valid(&order);\n",
            "+    check_metadata_valid(&order);\n",
        );
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(
            markers_only(&out),
            vec![
                '-', '-', '-', '-', '-', '-', '-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+',
                '+', '+', '+', '+', '+', '+',
            ]
        );
    }

    #[test]
    fn long_enough_single_line_in_a_large_edit_block_is_still_tagged_as_moved() {
        // Same shape as the test above — one matching line surrounded by
        // 9 unrelated real edits on each side, no extension possible —
        // but the matching line itself is long enough on its own
        // (`log_security_audit_violation(&order);`, 25 alphanumeric
        // characters) to clear MIN_MOVE_ALNUM_CHARS (20). This confirms
        // the threshold is purely about match length, not about whether
        // the surrounding block is otherwise "pure": a sufficiently
        // distinctive single-line match is still a real move signal even
        // inside a block of unrelated changes.
        let diff = concat!(
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,10 +1,2 @@\n",
            "-    validate_order_header(&order);\n",
            "-    validate_order_items(&order);\n",
            "-    validate_order_total(&order);\n",
            "-    log_security_audit_violation(&order);\n",
            "-    validate_order_payment(&order);\n",
            "-    validate_order_shipping(&order);\n",
            "-    validate_order_discount(&order);\n",
            "-    validate_order_customer(&order);\n",
            "-    validate_order_metadata(&order);\n",
            "-    validate_order_currency(&order);\n",
            " context_a\n",
            "@@ -20,1 +15,10 @@\n",
            " context_b\n",
            "+    check_header_valid(&order);\n",
            "+    check_items_valid(&order);\n",
            "+    check_total_valid(&order);\n",
            "+    check_address_valid(&order);\n",
            "+    check_payment_valid(&order);\n",
            "+    check_shipping_valid(&order);\n",
            "+    log_security_audit_violation(&order);\n",
            "+    check_discount_valid(&order);\n",
            "+    check_customer_valid(&order);\n",
            "+    check_metadata_valid(&order);\n",
        );
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(
            markers_only(&out),
            vec![
                '-', '-', '-', '>', '-', '-', '-', '-', '-', '-', ' ', ' ', '+', '+', '+', '+',
                '+', '+', '<', '+', '+', '+',
            ]
        );
    }

    #[test]
    fn parse_absolute_integer() {
        assert_eq!("1".parse::<MoveGap>().unwrap(), MoveGap::Absolute(1));
        assert_eq!("2".parse::<MoveGap>().unwrap(), MoveGap::Absolute(2));
        assert_eq!("0".parse::<MoveGap>().unwrap(), MoveGap::Relative(0.0));
    }

    #[test]
    fn parse_relative_percentage() {
        match "10%".parse::<MoveGap>().unwrap() {
            MoveGap::Relative(r) => assert!((r - 0.10).abs() < f64::EPSILON),
            other => panic!("expected Relative, got {other:?}"),
        }
    }

    #[test]
    fn parse_relative_fraction() {
        match "0.1".parse::<MoveGap>().unwrap() {
            MoveGap::Relative(r) => assert!((r - 0.1).abs() < f64::EPSILON),
            other => panic!("expected Relative, got {other:?}"),
        }
    }

    #[test]
    fn parse_rejects_negative_and_garbage() {
        assert!("-1".parse::<MoveGap>().is_err());
        assert!("abc".parse::<MoveGap>().is_err());
        assert!("-5%".parse::<MoveGap>().is_err());
    }

    #[test]
    fn missing_trailing_newline_does_not_panic() {
        // `git::local_diff` strips the trailing newline (duct's `.read()`
        // behaves like shell `$()`); the `patch` crate's parser panics on
        // that unless we restore it. Regression test for that fix.
        let diff = "--- a/f\n+++ b/f\n@@ -1,2 +1,2 @@\n-old\n+new\n trailing context, no newline after this";
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(markers_only(&out), vec!['-', '+', ' ']);
    }

    #[test]
    fn unparseable_input_falls_back_to_plain_text_instead_of_erroring() {
        let not_a_diff = "this is not a unified diff at all\njust some text\n";
        let out = render(not_a_diff, GAP1, false).unwrap();
        assert_eq!(out, not_a_diff);
    }

    #[test]
    fn one_unparseable_file_falls_back_without_losing_annotations_for_others() {
        // A normal text-hunk file followed by a binary file, each with its
        // own `diff --git` header as real `git diff` output would produce.
        // Regression test for "one bad file nukes annotations for the
        // whole diff": the binary entry should fall back to its raw text
        // while the text file is still fully annotated.
        let diff = concat!(
            "diff --git a/f b/f\n",
            "--- a/f\n",
            "+++ b/f\n",
            "@@ -1,2 +1,2 @@\n",
            "-foo bar baz\n",
            "+quux bar baz\n",
            " context\n",
            "diff --git a/img.png b/img.png\n",
            "index 111..222 100644\n",
            "Binary files a/img.png and b/img.png differ\n",
        );
        let out = render(diff, GAP1, false).unwrap();
        // The text file is still parsed and annotated normally (not just
        // echoed verbatim): its hunk header is reconstructed by the
        // `patch` crate's `Display` impl rather than preserved byte-for-
        // byte.
        assert!(out.contains("-foo bar baz\n"), "got: {out}");
        assert!(out.contains("+quux bar baz\n"), "got: {out}");
        // The binary file's entry is preserved verbatim since it can't be
        // parsed into annotated hunks.
        assert!(
            out.contains("Binary files a/img.png and b/img.png differ\n"),
            "got: {out}"
        );
    }

    #[test]
    fn single_chunk_with_no_git_header_still_recovers_from_parser_panic() {
        // Without a `diff --git` separator between the hunk and the binary
        // marker, this whole input is one unparseable chunk (see
        // `diff_parse::tests::parse_patches_safely_catches_parser_panic_on_binary_file_entry`).
        // `render` must still recover via `catch_unwind` and fall back to
        // the raw text instead of crashing.
        let diff = concat!(
            "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
            "Binary files a/img.png and b/img.png differ\n",
        );
        let out = render(diff, GAP1, false).unwrap();
        assert_eq!(out, diff);
    }
}