heddle-cli 0.4.0

An AI-native version control system
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
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
// SPDX-License-Identifier: Apache-2.0
//! Output formatting for diff command.

use std::{
    collections::BTreeMap,
    io::{IsTerminal, Write},
    process::{Command, Stdio},
};

use objects::object::FileMode;

use super::{
    diff_compute::trim_added_decorations_for_display,
    diff_types::{
        DiffOutput, FileChange, LineDiff, SemanticChangeEntry, should_render_modified_pair,
    },
};
use crate::cli::style;

const PAGER_LINE_THRESHOLD: usize = 200;
const SIGNATURE_CHANGE_SEPARATOR: &str = "\u{1f}";

pub(crate) fn print_stat(output: &DiffOutput) {
    for change in &output.changes {
        match change.kind.as_str() {
            "added" => {
                // Status glyph is the carrier; colour only the +/M/-
                // prefix and let path text stay neutral so long path
                // lists scan as a column rather than a lightshow.
                println!(" {} {} | added", style::accent("+"), change.path);
            }
            "modified" => {
                println!(" {} {} | modified", style::warn("M"), change.path);
            }
            "deleted" => {
                println!(" {} {} | deleted", style::error("-"), change.path);
            }
            "renamed" => {
                let old_path = change.old_path.as_deref().unwrap_or("?");
                println!(
                    " {} {} -> {} | renamed",
                    style::accent("R"),
                    old_path,
                    change.path
                );
            }
            _ => {}
        }
    }

    if let Some(ref semantic) = output.semantic_changes {
        for change in semantic {
            if change.change_type == "file_renamed" {
                println!(
                    " {} -> {} | renamed",
                    change.from_path.as_deref().unwrap_or("?"),
                    change.to_path.as_deref().unwrap_or("?")
                );
            }
        }
    }

    println!();
    println!(
        " {} files changed, {} additions, {} modifications, {} deletions, {} renames",
        output.stats.files_changed,
        output.stats.additions,
        output.stats.modifications,
        output.stats.deletions,
        output.stats.renames
    );
}

/// Render the diff as standard unified-diff text — no gutter, no
/// inline-edit `~` lines, no ANSI styling. Output targets a clean
/// `git apply` round-trip; `patch(1)` compatibility is best-effort (it
/// does not consume git's extended headers, so type changes and empty
/// add/delete hunks are git-apply-only). Each line is `prefix + content`
/// because the hunk-header `LineDiff` already encodes the second `@`
/// (prefix=`@`, content=`@ -a,b +c,d @@`), so concatenation yields the
/// canonical `@@ -a,b +c,d @@` shape.
///
/// Output is `Vec<u8>`, not `String`, because a symlink's target — which
/// git stores as the link's git blob and the patch carries verbatim in the
/// hunk body — is an arbitrary byte sequence on Unix and need not be valid
/// UTF-8. This is the single byte-preserving patch path; the lossy
/// `render_diff_patch` (used for the JSON `.patch` field) is derived from it.
///
/// Four cases require git's extended header block to round-trip:
///
/// * **Added files** get `diff --git ... / new file mode <mode> /
///   --- /dev/null`. Without it, `git apply` (and `patch -p1`) demand
///   that `b/<path>` already exist on the target side, which defeats
///   the whole point of an add hunk. `<mode>` reflects the real file
///   type (`100755` for an executable, `120000` for a symlink) so the
///   round-trip preserves it.
/// * **Deleted files** get `diff --git ... / deleted file mode <mode> /
///   +++ /dev/null`. `git apply --check` tolerates the bare `+++ b/<path>`
///   shape, but actually applying it leaves an empty file behind instead
///   of removing the path — the `+++ /dev/null` + deleted-mode header is
///   what tells git to unlink it.
/// * **Renames** get `diff --git a/old b/new / similarity index N% /
///   rename from old / rename to new`. Pure renames (no edits) emit
///   the extended headers and stop; rename-with-edit appends the
///   usual `--- a/old / +++ b/new` + hunk body.
/// * **Symlinks** (`120000`) carry their target bytes as the hunk body —
///   a symlink's git blob is exactly its raw target. Every symlink change
///   (add/delete/edit/rename) is rendered by `render_symlink_change`
///   straight from `change.symlink`, never through `change.lines` (which a
///   non-UTF-8 target cannot populate) and never as a binary marker (which
///   `git apply` rejects for a `120000` entry), so a non-UTF-8 link target
///   round-trips byte-for-byte.
///
/// Every rendered file also opens with a `diff --git a/<p> b/<p>` line,
/// including a plain content modify (which carries no extended-mode
/// block). The header is what delimits one file's stanza from the next:
/// a bare `--- a/<path>` is ambiguous, and git binds it to the preceding
/// `diff --git` stanza when one is still open (a header-only empty-add or
/// mode-only change just above), misattributing this file's hunk. The
/// explicit per-file header makes ordering irrelevant.
///
/// An empty-file add/delete is still a real patch: git emits the
/// extended header with no hunk body (and `git apply` creates/unlinks
/// the path from that alone), so we emit the header-only form rather
/// than skipping the change. A modify with no hunk body is only skipped
/// when it is a genuine no-op — a trailing-newline-only change carries a
/// synthesized tail hunk (see `unified_hunks`) and is rendered, and a
/// mode-only modify (chmod) emits a header-only `diff --git` +
/// `old mode`/`new mode` block so the permission change round-trips.
pub(crate) fn render_diff_patch_bytes(output: &DiffOutput) -> Vec<u8> {
    let mut buf: Vec<u8> = Vec::new();
    for change in &output.changes {
        // A symlink change carries its raw target bytes in `change.symlink`,
        // which on Unix need not be valid UTF-8. Render it byte-exact so a
        // non-UTF-8 link target round-trips through `git apply`; every other
        // change is UTF-8 text and is appended as its bytes.
        if change.symlink.is_some() {
            render_symlink_change(change, &mut buf);
        } else {
            let mut text = String::new();
            render_text_change(change, &mut text);
            buf.extend_from_slice(text.as_bytes());
        }
    }
    buf
}

/// Lossy String view of the byte-exact patch (`render_diff_patch_bytes`),
/// for the JSON `.patch` field and String-based callers/tests. Only a
/// non-UTF-8 symlink target (Unix-only) differs from the byte render; JSON
/// strings cannot carry raw bytes, so a lossy view is the best a String
/// surface can do. The round-trip surface (`heddle diff --patch`) writes the
/// bytes directly via `render_diff_patch_bytes`, so its byte fidelity is
/// never reduced here.
pub(crate) fn render_diff_patch(output: &DiffOutput) -> String {
    String::from_utf8_lossy(&render_diff_patch_bytes(output)).into_owned()
}

/// Render one non-symlink change as unified-diff text into `buf`. Symlink
/// changes never reach here — `render_diff_patch_bytes` routes them to
/// `render_symlink_change`, which preserves a non-UTF-8 target — so a symlink
/// target is never forced through `change.lines` (which a non-UTF-8 target
/// cannot populate) or `render_binary_change`.
fn render_text_change(change: &FileChange, buf: &mut String) {
    let lines_ref = change.lines.as_deref();
    let has_hunk_body = lines_ref.is_some_and(|lines| lines.iter().any(|line| line.prefix != " "));
    let old_path = change.old_path.as_deref().unwrap_or(&change.path);
    let is_rename = change
        .old_path
        .as_deref()
        .is_some_and(|old| old != change.path);
    let is_added = change.kind == "added";
    let is_deleted = change.kind == "deleted";
    let is_modified = !is_rename && !is_added && !is_deleted;
    // A mode-only modify (chmod / exec-bit flip / type swap) has no
    // hunk body but is still a real change: git records it as
    // `old mode`/`new mode` extended headers and `git apply`
    // reproduces the permission change from those alone.
    let mode_changed = is_modified
        && matches!((change.old_mode, change.mode), (Some(old), Some(new)) if old != new);
    // `lines: None` is the binary / unreadable case — there is no
    // text body to render, so it never produces a patch regardless
    // of kind. `lines: Some(_)` (even empty) means we have a
    // readable text side.
    let has_text = change.lines.is_some();

    // A binary *content* change (add/delete/modify of a file heddle
    // cannot diff as text). heddle has no git binary delta to emit
    // (its blob hashes are not git SHAs), and silently dropping the
    // change would let `git apply` "succeed" while the binary content
    // stays stale — the false round-trip cid 3319484747 flagged. Emit
    // git's `Binary files … differ` marker with a *placeholder* index
    // line: that index line is what makes `git apply` recognize a
    // binary patch and refuse the *whole* patch ("without full index
    // line") instead of skipping the block. Without the index line git
    // treats the marker as an empty patch and silently ignores it. A
    // content-identical mode-only change is never `binary` (the diff
    // readers short-circuit it to an empty text body), so this only
    // fires on a real binary content change, never a chmod.
    if change.binary && !is_rename {
        render_binary_change(change, is_added, is_deleted, mode_changed, buf);
        return;
    }

    // Decide whether this change emits anything at all:
    // * renames always do (the extended headers carry the move even
    //   for identical content);
    // * add/delete do whenever there's a readable text side — the
    //   empty-file case renders header-only;
    // * a modify renders only when it has a real hunk body. A modify
    //   with no body and matching EOL is a no-op; the
    //   trailing-newline-only case is handled upstream in
    //   `unified_hunks`, which synthesizes a tail hunk so this
    //   branch sees `has_hunk_body == true`.
    let should_render = if is_rename {
        true
    } else if is_added || is_deleted {
        has_text
    } else {
        has_hunk_body || mode_changed
    };
    if !should_render {
        return;
    }

    if is_rename {
        buf.push_str(&format!(
            "diff --git {} {}\n",
            quote_path_for_patch("a/", old_path),
            quote_path_for_patch("b/", &change.path)
        ));
        // A rename paired with a chmod/type change (`old.sh` renamed
        // to `new.sh` and made executable) carries both modes; emit
        // the `old mode`/`new mode` pair before `similarity index`,
        // matching `git diff`, so `git apply` reproduces the
        // permission change as well as the move.
        if let (Some(old), Some(new)) = (change.old_mode, change.mode)
            && old != new
        {
            buf.push_str(&format!("old mode {}\n", mode_str(change.old_mode)));
            buf.push_str(&format!("new mode {}\n", mode_str(change.mode)));
        }
        let pct = (change.similarity_score.unwrap_or(1.0).clamp(0.0, 1.0) * 100.0).round() as u32;
        buf.push_str(&format!("similarity index {pct}%\n"));
        buf.push_str(&format!(
            "rename from {}\n",
            quote_path_for_patch("", old_path)
        ));
        buf.push_str(&format!(
            "rename to {}\n",
            quote_path_for_patch("", &change.path)
        ));
        // Pure rename — extended headers alone suffice; emitting
        // `--- a/old / +++ b/new` without hunks would tell git to
        // apply an empty patch and warn about a stray header.
        if !has_hunk_body {
            return;
        }
    } else if is_added {
        buf.push_str(&format!(
            "diff --git {} {}\n",
            quote_path_for_patch("a/", &change.path),
            quote_path_for_patch("b/", &change.path)
        ));
        buf.push_str(&format!("new file mode {}\n", mode_str(change.mode)));
    } else if is_deleted {
        buf.push_str(&format!(
            "diff --git {} {}\n",
            quote_path_for_patch("a/", &change.path),
            quote_path_for_patch("b/", &change.path)
        ));
        buf.push_str(&format!("deleted file mode {}\n", mode_str(change.mode)));
    } else if mode_changed {
        // A modify whose mode changed (with or without a content
        // hunk). Emit the `diff --git` + `old mode`/`new mode`
        // header pair.
        buf.push_str(&format!(
            "diff --git {} {}\n",
            quote_path_for_patch("a/", &change.path),
            quote_path_for_patch("b/", &change.path)
        ));
        buf.push_str(&format!("old mode {}\n", mode_str(change.old_mode)));
        buf.push_str(&format!("new mode {}\n", mode_str(change.mode)));
    } else {
        // A plain content modify. Emit the `diff --git` header so
        // every file stanza is self-delimiting. A bare `--- a/<path>`
        // is ambiguous: git's parser binds it to the *preceding*
        // `diff --git` stanza when one is still open — e.g. a
        // header-only empty-add (`diff --git ... / new file mode`) or
        // a mode-only change immediately above — and misreads this
        // file's `---` as the prior file's source side, corrupting the
        // patch ("expected /dev/null"). The explicit header closes the
        // prior stanza and opens this one. (cid 3319484717 ordering.)
        buf.push_str(&format!(
            "diff --git {} {}\n",
            quote_path_for_patch("a/", &change.path),
            quote_path_for_patch("b/", &change.path)
        ));
    }

    // An empty-file add/delete (text side present but zero lines)
    // has no hunk body. git stops after the `new/deleted file mode`
    // header in that case and `git apply` still creates/unlinks the
    // path — emitting `--- /+++/@@` with no `@@` body would be a
    // malformed hunk, so we stop here too.
    if (is_added || is_deleted) && !has_hunk_body {
        return;
    }
    // A mode-only modify carries no content hunk: the `old mode`/
    // `new mode` header pair is the entire patch, so stop before the
    // `--- /+++` line-diff headers (which would be a malformed
    // empty hunk).
    if is_modified && !has_hunk_body {
        return;
    }

    if is_added {
        buf.push_str("--- /dev/null\n");
    } else {
        buf.push_str(&format!("--- {}\n", quote_path_for_patch("a/", old_path)));
    }
    if is_deleted {
        buf.push_str("+++ /dev/null\n");
    } else {
        buf.push_str(&format!(
            "+++ {}\n",
            quote_path_for_patch("b/", &change.path)
        ));
    }
    if let Some(lines) = lines_ref {
        render_patch_hunks(change, lines, buf);
    }
}

/// Render a symlink change (add / delete / target-edit / rename) byte-exact.
///
/// A symlink's git blob is its raw target bytes, which on Unix need not be
/// valid UTF-8 — so the hunk body is emitted straight from `change.symlink`
/// (the single byte-preserving symlink path) rather than `change.lines`,
/// which a non-UTF-8 target cannot populate. Marking such a change `binary`
/// (the old behaviour) emitted a placeholder-binary stanza that `git apply`
/// rejects for a `120000` entry; emitting the target as a text hunk is what
/// git itself does and round-trips. The extended headers mirror
/// `render_text_change`'s (add/delete/rename), and the mode is always
/// `120000` so a rename never needs an `old mode`/`new mode` pair unless the
/// two sides genuinely differ.
fn render_symlink_change(change: &FileChange, buf: &mut Vec<u8>) {
    let Some(sym) = change.symlink.as_ref() else {
        return;
    };
    let push = |buf: &mut Vec<u8>, text: &str| buf.extend_from_slice(text.as_bytes());
    let old_path = change.old_path.as_deref().unwrap_or(&change.path);
    let is_rename = change
        .old_path
        .as_deref()
        .is_some_and(|old| old != change.path);
    let is_added = change.kind == "added";
    let is_deleted = change.kind == "deleted";

    if is_rename {
        push(
            buf,
            &format!(
                "diff --git {} {}\n",
                quote_path_for_patch("a/", old_path),
                quote_path_for_patch("b/", &change.path)
            ),
        );
        if let (Some(old), Some(new)) = (change.old_mode, change.mode)
            && old != new
        {
            push(buf, &format!("old mode {}\n", mode_str(change.old_mode)));
            push(buf, &format!("new mode {}\n", mode_str(change.mode)));
        }
        let pct = (change.similarity_score.unwrap_or(1.0).clamp(0.0, 1.0) * 100.0).round() as u32;
        push(buf, &format!("similarity index {pct}%\n"));
        push(
            buf,
            &format!("rename from {}\n", quote_path_for_patch("", old_path)),
        );
        push(
            buf,
            &format!("rename to {}\n", quote_path_for_patch("", &change.path)),
        );
        // Pure rename (identical target) — the extended headers alone carry
        // the move, exactly like a text rename with no hunk body.
        if sym.old == sym.new {
            return;
        }
        push(
            buf,
            &format!("--- {}\n", quote_path_for_patch("a/", old_path)),
        );
        push(
            buf,
            &format!("+++ {}\n", quote_path_for_patch("b/", &change.path)),
        );
    } else if is_added {
        push(
            buf,
            &format!(
                "diff --git {} {}\n",
                quote_path_for_patch("a/", &change.path),
                quote_path_for_patch("b/", &change.path)
            ),
        );
        push(buf, &format!("new file mode {}\n", mode_str(change.mode)));
        push(buf, "--- /dev/null\n");
        push(
            buf,
            &format!("+++ {}\n", quote_path_for_patch("b/", &change.path)),
        );
    } else if is_deleted {
        push(
            buf,
            &format!(
                "diff --git {} {}\n",
                quote_path_for_patch("a/", &change.path),
                quote_path_for_patch("b/", &change.path)
            ),
        );
        push(
            buf,
            &format!("deleted file mode {}\n", mode_str(change.mode)),
        );
        push(
            buf,
            &format!("--- {}\n", quote_path_for_patch("a/", &change.path)),
        );
        push(buf, "+++ /dev/null\n");
    } else {
        // A symlink target-edit. The mode is unchanged (`120000` → `120000`),
        // so no `old mode`/`new mode` block — just the file header. An
        // identical target would be a no-op and is never emitted by the diff
        // backends, but guard it so an accidental empty hunk can't form.
        if sym.old == sym.new {
            return;
        }
        push(
            buf,
            &format!(
                "diff --git {} {}\n",
                quote_path_for_patch("a/", &change.path),
                quote_path_for_patch("b/", &change.path)
            ),
        );
        push(
            buf,
            &format!("--- {}\n", quote_path_for_patch("a/", &change.path)),
        );
        push(
            buf,
            &format!("+++ {}\n", quote_path_for_patch("b/", &change.path)),
        );
    }

    render_symlink_hunk(sym.old.as_deref(), sym.new.as_deref(), buf);
}

/// Emit the unified-diff hunk for a symlink's target bytes. A symlink's git
/// blob has no trailing newline, so each side normally collapses to a single
/// line carrying the `\ No newline at end of file` marker; a target that
/// embeds a `\n` (pathological but representable) splits into multiple lines.
/// The `@@` header mirrors `unified_hunks`'s `@@ -s,c +s,c @@` shape (counts
/// always written, even `,1`), which `git apply` accepts.
fn render_symlink_hunk(old: Option<&[u8]>, new: Option<&[u8]>, buf: &mut Vec<u8>) {
    let old_lines = split_target_lines(old);
    let new_lines = split_target_lines(new);
    let old_count = old_lines.len();
    let new_count = new_lines.len();
    let old_start = if old_count == 0 { 0 } else { 1 };
    let new_start = if new_count == 0 { 0 } else { 1 };
    buf.extend_from_slice(
        format!("@@ -{old_start},{old_count} +{new_start},{new_count} @@\n").as_bytes(),
    );
    let old_no_eol = !target_has_trailing_newline(old);
    let new_no_eol = !target_has_trailing_newline(new);
    for (idx, line) in old_lines.iter().enumerate() {
        buf.push(b'-');
        buf.extend_from_slice(line);
        buf.push(b'\n');
        if old_no_eol && idx + 1 == old_count {
            buf.extend_from_slice(NO_NEWLINE_MARKER.as_bytes());
        }
    }
    for (idx, line) in new_lines.iter().enumerate() {
        buf.push(b'+');
        buf.extend_from_slice(line);
        buf.push(b'\n');
        if new_no_eol && idx + 1 == new_count {
            buf.extend_from_slice(NO_NEWLINE_MARKER.as_bytes());
        }
    }
}

/// Split a symlink target's raw bytes into unified-diff lines. An absent side
/// (`None`) or an empty blob yields no lines; a trailing `\n` is the line
/// terminator (dropped here, surfaced via `target_has_trailing_newline`)
/// rather than an extra empty line, matching how text blobs are line-counted.
fn split_target_lines(target: Option<&[u8]>) -> Vec<&[u8]> {
    let Some(bytes) = target else {
        return Vec::new();
    };
    if bytes.is_empty() {
        return Vec::new();
    }
    let mut lines: Vec<&[u8]> = bytes.split(|&byte| byte == b'\n').collect();
    if bytes.ends_with(b"\n") {
        lines.pop();
    }
    lines
}

fn target_has_trailing_newline(target: Option<&[u8]>) -> bool {
    target.is_some_and(|bytes| bytes.ends_with(b"\n"))
}

/// Render a binary content change (add / delete / plain modify / modify
/// with a mode change) as git's `Binary files … differ` marker.
///
/// heddle cannot emit a git binary delta — its blob hashes are not git
/// SHAs — so the marker is the most faithful thing it can produce. The
/// catch (cid 3319484747): a bare `Binary files … differ` marker with no
/// `index` header is treated by `git apply` as an empty patch and
/// *silently skipped*, which would let the apply "succeed" while the
/// binary content stays stale. Emitting a *placeholder* `index
/// 0000000..0000000` line flips git into binary-patch mode, where it
/// refuses the whole patch ("cannot apply binary patch … without full
/// index line") rather than ignoring it. That refusal is the correct
/// outcome: heddle has no delta to apply, so the honest result is a hard
/// failure, never a false round-trip.
fn render_binary_change(
    change: &FileChange,
    is_added: bool,
    is_deleted: bool,
    mode_changed: bool,
    buf: &mut String,
) {
    let path = &change.path;
    buf.push_str(&format!(
        "diff --git {} {}\n",
        quote_path_for_patch("a/", path),
        quote_path_for_patch("b/", path)
    ));
    if is_added {
        buf.push_str(&format!("new file mode {}\n", mode_str(change.mode)));
        buf.push_str("index 0000000..0000000\n");
    } else if is_deleted {
        buf.push_str(&format!("deleted file mode {}\n", mode_str(change.mode)));
        buf.push_str("index 0000000..0000000\n");
    } else if mode_changed {
        buf.push_str(&format!("old mode {}\n", mode_str(change.old_mode)));
        buf.push_str(&format!("new mode {}\n", mode_str(change.mode)));
        buf.push_str("index 0000000..0000000\n");
    } else {
        // Plain binary modify: git stamps the mode at the end of the
        // index line (`index <old>..<new> 100644`).
        buf.push_str(&format!(
            "index 0000000..0000000 {}\n",
            mode_str(change.mode)
        ));
    }
    let (a, b) = if is_added {
        ("/dev/null".to_string(), quote_path_for_patch("b/", path))
    } else if is_deleted {
        (quote_path_for_patch("a/", path), "/dev/null".to_string())
    } else {
        (
            quote_path_for_patch("a/", path),
            quote_path_for_patch("b/", path),
        )
    };
    buf.push_str(&format!("Binary files {a} and {b} differ\n"));
}

/// Map a tracked file mode to the git unified-diff mode string. `None`
/// (mode not resolved) and the regular-file case both render `100644`.
fn mode_str(mode: Option<FileMode>) -> &'static str {
    match mode {
        Some(FileMode::Executable) => "100755",
        Some(FileMode::Symlink) => "120000",
        Some(FileMode::Normal) | None => "100644",
    }
}

/// Quote a patch-header path the way `git diff` does (C-style quoting,
/// `core.quotePath` defaults to true). A path containing a tab, newline,
/// double-quote, backslash, control byte, or non-ASCII byte is wrapped in
/// double quotes with the bytes escaped; a "simple" path is emitted bare.
///
/// `prefix` is the in-quote prefix git stamps on `diff --git`/`--- `/`+++ `
/// headers (`a/`, `b/`) — git puts the prefix *inside* the quotes
/// (`"a/tab\there"`), so it is escaped alongside the path. `rename from`/
/// `rename to` pass an empty prefix (git quotes the bare path there).
///
/// Verified byte-for-byte against `git diff` for tab, newline, quote,
/// backslash, and non-ASCII (UTF-8 → per-byte octal) paths.
fn quote_path_for_patch(prefix: &str, path: &str) -> String {
    if !needs_c_quoting(prefix) && !needs_c_quoting(path) {
        return format!("{prefix}{path}");
    }
    let mut out = String::with_capacity(prefix.len() + path.len() + 2);
    out.push('"');
    push_c_quoted(&mut out, prefix);
    push_c_quoted(&mut out, path);
    out.push('"');
    out
}

fn needs_c_quoting(s: &str) -> bool {
    s.bytes().any(byte_needs_escape)
}

/// git escapes any byte below 0x20, the DEL byte and everything above it
/// (0x7f..=0xff — `core.quotePath` octal-escapes non-ASCII), plus the two
/// in-quote metacharacters `"` and `\`.
fn byte_needs_escape(byte: u8) -> bool {
    matches!(byte, b'"' | b'\\') || !(0x20..0x7f).contains(&byte)
}

fn push_c_quoted(out: &mut String, s: &str) {
    for byte in s.bytes() {
        match byte {
            b'"' => out.push_str("\\\""),
            b'\\' => out.push_str("\\\\"),
            0x07 => out.push_str("\\a"),
            0x08 => out.push_str("\\b"),
            0x09 => out.push_str("\\t"),
            0x0a => out.push_str("\\n"),
            0x0b => out.push_str("\\v"),
            0x0c => out.push_str("\\f"),
            0x0d => out.push_str("\\r"),
            0x20..=0x7e => out.push(byte as char),
            other => out.push_str(&format!("\\{other:03o}")),
        }
    }
}

const NO_NEWLINE_MARKER: &str = "\\ No newline at end of file\n";

/// Walk the rendered hunks once and emit each line, splicing in the
/// `\ No newline at end of file` marker after the line that holds the
/// file's tail on a side whose source bytes lacked a trailing `\n`.
///
/// The diff backend strips line terminators, so per-line equality
/// collapses `hello` and `hello\n` into the same `LineDiff`. To match
/// `git diff`'s output (which `git apply --check` accepts), a context
/// line that sits on the no-newline side's tail has to be split into
/// a `-` + `+` pair, with the marker attached to the side that lacks
/// the terminator. The 4-case matrix is in `render_patch_hunks`'s
/// context-line branch.
fn render_patch_hunks(change: &FileChange, lines: &[LineDiff], buf: &mut String) {
    let old_no_eol = !change.eol.old_has_final_newline;
    let new_no_eol = !change.eol.new_has_final_newline;
    let old_tail_idx = if old_no_eol && change.eol.old_line_count > 0 {
        find_side_tail_idx(lines, Side::Old, change.eol.old_line_count)
    } else {
        None
    };
    let new_tail_idx = if new_no_eol && change.eol.new_line_count > 0 {
        find_side_tail_idx(lines, Side::New, change.eol.new_line_count)
    } else {
        None
    };

    for (idx, line) in lines.iter().enumerate() {
        let is_old_tail = Some(idx) == old_tail_idx;
        let is_new_tail = Some(idx) == new_tail_idx;
        let needs_old_marker = is_old_tail && old_no_eol;
        let needs_new_marker = is_new_tail && new_no_eol;

        if line.prefix == " " && (needs_old_marker || needs_new_marker) {
            if is_old_tail && is_new_tail && needs_old_marker && needs_new_marker {
                // Both sides' tail lands on this context line and both
                // lack a trailing newline — emit the line once, then
                // a single marker that applies to both sides.
                emit_line(buf, line);
                buf.push_str(NO_NEWLINE_MARKER);
            } else {
                // Mixed state: at least one side needs the marker and
                // the other shouldn't be tagged. Split the context
                // line into a `-content` / `+content` pair so each
                // side's marker (or its absence) is unambiguous.
                buf.push('-');
                buf.push_str(&line.content);
                buf.push('\n');
                if needs_old_marker {
                    buf.push_str(NO_NEWLINE_MARKER);
                }
                buf.push('+');
                buf.push_str(&line.content);
                buf.push('\n');
                if needs_new_marker {
                    buf.push_str(NO_NEWLINE_MARKER);
                }
            }
            continue;
        }

        emit_line(buf, line);
        if needs_old_marker && line.prefix == "-" {
            buf.push_str(NO_NEWLINE_MARKER);
        }
        if needs_new_marker && line.prefix == "+" {
            buf.push_str(NO_NEWLINE_MARKER);
        }
    }
}

#[derive(Clone, Copy)]
enum Side {
    Old,
    New,
}

fn find_side_tail_idx(lines: &[LineDiff], side: Side, target: usize) -> Option<usize> {
    lines.iter().enumerate().rev().find_map(|(idx, line)| {
        let (on_side, line_number) = match side {
            Side::Old => (line.prefix == "-" || line.prefix == " ", line.old_line),
            Side::New => (line.prefix == "+" || line.prefix == " ", line.new_line),
        };
        if on_side && line_number == Some(target) {
            Some(idx)
        } else {
            None
        }
    })
}

fn emit_line(buf: &mut String, line: &LineDiff) {
    buf.push_str(&line.prefix);
    buf.push_str(&line.content);
    buf.push('\n');
}

pub(crate) fn print_diff_patch(output: &DiffOutput) {
    // Write the raw patch BYTES, not `output.patch` (a lossy String): a
    // symlink's target can be non-UTF-8, and the round-trip surface
    // (`heddle diff --patch | git apply`) must carry those bytes verbatim.
    // `output.patch` exists only to feed the JSON `.patch` field, where bytes
    // can't live; rendering bytes fresh here keeps stdout byte-exact.
    let rendered = render_diff_patch_bytes(output);
    let _ = std::io::stdout().write_all(&rendered);
}

pub(crate) fn print_diff(output: &DiffOutput) {
    let mut rendered = String::new();
    for change in &output.changes {
        // File-header rows: `--- a/...` / `+++ b/...` are dim;
        // they're navigation, not data.
        let old_path = change.old_path.as_deref().unwrap_or(&change.path);
        rendered.push_str(&style::dim(&format!("--- a/{old_path}")));
        rendered.push('\n');
        rendered.push_str(&style::dim(&format!("+++ b/{}", change.path)));
        rendered.push('\n');
        if change.kind == "renamed" {
            rendered.push_str(&style::dim(&format!("rename from {old_path}")));
            rendered.push('\n');
            rendered.push_str(&style::dim(&format!("rename to {}", change.path)));
            rendered.push('\n');
        }

        if let Some(lines) = &change.lines {
            // Decoration trimming is a pretty-display-only nicety; the
            // canonical `change.lines` stays untrimmed for the
            // `--patch`/JSON path (cid 3320364905). Apply it here, for
            // human rendering, against a local copy.
            let lines = trim_added_decorations_for_display(lines);
            let mut index = 0;
            while index < lines.len() {
                let line = &lines[index];
                if line.prefix == "-"
                    && let Some(next) = lines.get(index + 1)
                    && next.prefix == "+"
                {
                    if style::color_enabled()
                        && should_render_modified_pair(&line.content, &next.content)
                    {
                        rendered.push_str(&paint_modified_pair(line, next));
                        rendered.push('\n');
                    } else {
                        rendered.push_str(&paint_line(line));
                        rendered.push('\n');
                        rendered.push_str(&paint_line(next));
                        rendered.push('\n');
                    }
                    index += 2;
                    continue;
                }

                rendered.push_str(&paint_line(line));
                rendered.push('\n');
                index += 1;
            }
        } else {
            let summary = if change.binary {
                format!("Binary file changed: {}", change.path)
            } else {
                format!("File changed; line diff unavailable: {}", change.path)
            };
            rendered.push_str(&style::dim(&summary));
            rendered.push('\n');
        }

        rendered.push('\n');
    }
    write_diff_text(&rendered);
}

fn paint_line(line: &LineDiff) -> String {
    let body = paint_body(&line.prefix, &line.content);
    format!("{}{}", number_gutter(line.old_line, line.new_line), body)
}

fn write_diff_text(rendered: &str) {
    if should_page(rendered)
        && let Ok(mut child) = pager_command().stdin(Stdio::piped()).spawn()
    {
        if let Some(stdin) = child.stdin.as_mut() {
            let _ = stdin.write_all(rendered.as_bytes());
        }
        let _ = child.wait();
        return;
    }

    print!("{rendered}");
}

fn should_page(rendered: &str) -> bool {
    std::io::stdout().is_terminal()
        && std::env::var_os("HEDDLE_NO_PAGER").is_none()
        && rendered.lines().count() > PAGER_LINE_THRESHOLD
}

fn pager_command() -> Command {
    let pager = std::env::var("PAGER").unwrap_or_else(|_| "less -R -M".to_string());
    let mut parts = pager.split_whitespace();
    let executable = parts.next().unwrap_or("less");
    let mut command = Command::new(executable);
    for arg in parts {
        command.arg(arg);
    }
    if executable == "less" && std::env::var_os("PAGER").is_some() {
        command.arg("-R").arg("-M");
    }
    command
}

fn paint_body(prefix: &str, content: &str) -> String {
    let combined = format!("{prefix}{content}");
    match prefix {
        "+" => style::accent(&combined),
        "-" => style::error(&combined),
        "@" => style::dim(&combined),
        _ => combined,
    }
}

fn number_gutter(old_line: Option<usize>, new_line: Option<usize>) -> String {
    match (old_line, new_line) {
        (None, None) => String::new(),
        _ => style::dim(&format!(
            "{:>4} {:>4} | ",
            old_line
                .map(format_line_number)
                .unwrap_or_else(|| " ".to_string()),
            new_line
                .map(format_line_number)
                .unwrap_or_else(|| " ".to_string()),
        )),
    }
}

fn format_line_number(line: usize) -> String {
    line.to_string()
}

fn paint_modified_pair(removed: &LineDiff, added: &LineDiff) -> String {
    format!(
        "{}{}",
        number_gutter(removed.old_line, added.new_line),
        paint_modified_body(&removed.content, &added.content),
    )
}

fn paint_modified_body(removed: &str, added: &str) -> String {
    let tokens = aligned_added_tokens(removed, added);
    let mut rendered = style::warn("~");
    for token in tokens {
        if token.changed {
            rendered.push_str(&style::accent(token.text));
        } else {
            rendered.push_str(&style::warn(token.text));
        }
    }
    rendered
}

#[derive(Debug, PartialEq, Eq)]
struct PaintedToken<'a> {
    text: &'a str,
    changed: bool,
}

fn aligned_added_tokens<'a>(removed: &str, added: &'a str) -> Vec<PaintedToken<'a>> {
    let old_tokens = tokenize_inline(removed);
    let new_tokens = tokenize_inline(added);

    let mut prefix_len = 0usize;
    while prefix_len < old_tokens.len()
        && prefix_len < new_tokens.len()
        && old_tokens[prefix_len] == new_tokens[prefix_len]
    {
        prefix_len += 1;
    }

    let mut suffix_len = 0usize;
    while suffix_len < old_tokens.len().saturating_sub(prefix_len)
        && suffix_len < new_tokens.len().saturating_sub(prefix_len)
        && old_tokens[old_tokens.len() - 1 - suffix_len]
            == new_tokens[new_tokens.len() - 1 - suffix_len]
    {
        suffix_len += 1;
    }

    let old_middle = &old_tokens[prefix_len..old_tokens.len().saturating_sub(suffix_len)];
    let new_middle = &new_tokens[prefix_len..new_tokens.len().saturating_sub(suffix_len)];
    let old_len = old_middle.len();
    let new_len = new_middle.len();
    let mut aligned = vec![false; new_tokens.len()];
    for slot in aligned.iter_mut().take(prefix_len) {
        *slot = true;
    }
    for slot in aligned.iter_mut().rev().take(suffix_len) {
        *slot = true;
    }

    let mut table = vec![vec![0usize; new_len + 1]; old_len + 1];

    for old_index in (0..old_len).rev() {
        for new_index in (0..new_len).rev() {
            table[old_index][new_index] = if old_middle[old_index] == new_middle[new_index] {
                table[old_index + 1][new_index + 1] + 1
            } else {
                table[old_index + 1][new_index].max(table[old_index][new_index + 1])
            };
        }
    }

    let (mut old_index, mut new_index) = (0usize, 0usize);
    while old_index < old_len && new_index < new_len {
        if old_middle[old_index] == new_middle[new_index] {
            aligned[prefix_len + new_index] = true;
            old_index += 1;
            new_index += 1;
        } else if table[old_index + 1][new_index] >= table[old_index][new_index + 1] {
            old_index += 1;
        } else {
            new_index += 1;
        }
    }

    new_tokens
        .into_iter()
        .enumerate()
        .map(|(index, text)| PaintedToken {
            text,
            changed: !aligned[index],
        })
        .collect()
}

fn tokenize_inline(s: &str) -> Vec<&str> {
    let mut tokens = Vec::new();
    let mut start = 0usize;
    let mut previous_kind: Option<TokenKind> = None;

    for (index, ch) in s.char_indices() {
        let kind = TokenKind::for_char(ch);
        if kind == TokenKind::Punctuation {
            if start < index {
                tokens.push(&s[start..index]);
            }
            let end = index + ch.len_utf8();
            tokens.push(&s[index..end]);
            start = end;
            previous_kind = None;
            continue;
        }
        if let Some(previous) = previous_kind
            && previous != kind
        {
            tokens.push(&s[start..index]);
            start = index;
        }
        previous_kind = Some(kind);
    }

    if start < s.len() {
        tokens.push(&s[start..]);
    }
    tokens
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum TokenKind {
    Word,
    Whitespace,
    Punctuation,
}

impl TokenKind {
    fn for_char(ch: char) -> Self {
        if ch.is_alphanumeric() || ch == '_' {
            Self::Word
        } else if ch.is_whitespace() {
            Self::Whitespace
        } else {
            Self::Punctuation
        }
    }
}

pub(crate) fn print_context(output: &DiffOutput) {
    if let Some(guidance) = &output.broader_guidance
        && !guidance.is_empty()
    {
        println!("Broader Guidance:");
        println!("-----------------");
        for annotation in guidance {
            println!(
                "  [{}] {} ({} rev{})",
                annotation.kind,
                annotation.content,
                annotation.revision_count,
                if annotation.revision_count == 1 {
                    ""
                } else {
                    "s"
                }
            );
        }
        println!();
    }

    if let Some(entries) = &output.context {
        let mut printed_header = false;
        for entry in entries {
            if entry.annotations.is_empty() {
                continue;
            }
            if !printed_header {
                println!("Applicable Context:");
                println!("-------------------");
                printed_header = true;
            }
            println!("{}", entry.path);
            for annotation in &entry.annotations {
                println!(
                    "  [{}] {} ({} rev{})",
                    annotation.kind,
                    annotation.content,
                    annotation.revision_count,
                    if annotation.revision_count == 1 {
                        ""
                    } else {
                        "s"
                    }
                );
            }
            println!();
        }
    }
}

pub(crate) fn print_semantic_changes(changes: &[SemanticChangeEntry]) {
    if changes.is_empty() {
        return;
    }

    println!("{}", style::bold("Semantic Changes:"));
    println!("{}", style::dim("----------------"));

    let grouped = group_semantic_changes(changes);
    for file in grouped.files.values() {
        println!("{}", style::dim(&file.path));
        for (label, items) in &file.groups {
            println!("  {}:", paint_semantic_label(label));
            for item in items {
                for line in paint_semantic_item_lines(label, item) {
                    println!("    {line}");
                }
            }
        }
        println!();
    }

    if !grouped.dependencies.is_empty() {
        println!("{}", style::bold("Dependencies:"));
        for (label, items) in &grouped.dependencies {
            println!("  {}:", paint_semantic_label(label));
            for item in items {
                println!("    {} {}", style::accent("-"), item);
            }
        }
        println!();
    }

    if !grouped.other.is_empty() {
        println!("{}", style::bold("Other:"));
        for item in &grouped.other {
            println!("  {} {item}", style::accent("-"));
        }
        println!();
    }
}

fn paint_semantic_label(label: &str) -> String {
    match label {
        "Function deleted" | "Removed" => style::error(label),
        "Function modified" | "Signature changed" => style::warn(label),
        "Function added" | "Function extracted" | "Function renamed" | "Function moved"
        | "Added" => style::accent(label),
        _ => style::bold(label),
    }
}

fn paint_semantic_item(label: &str, item: &str) -> String {
    match label {
        "Function extracted" => paint_extracted_item(item),
        _ => item.to_string(),
    }
}

fn paint_semantic_item_lines(label: &str, item: &str) -> Vec<String> {
    if label == "Signature changed" {
        return paint_signature_change_item_lines(item);
    }
    vec![format!(
        "{} {}",
        style::accent("-"),
        paint_semantic_item(label, item)
    )]
}

fn paint_extracted_item(item: &str) -> String {
    let Some((name, source)) = item.split_once(" from ") else {
        return style::accent(item);
    };
    format!(
        "{} {} {}",
        style::accent(name),
        style::dim("from"),
        style::warn(source)
    )
}

fn paint_signature_change_item_lines(item: &str) -> Vec<String> {
    let Some((old, new)) = item.split_once(SIGNATURE_CHANGE_SEPARATOR) else {
        return vec![format!("{} {item}", style::accent("-"))];
    };
    paint_signature_change_lines(old, new)
}

#[cfg(test)]
fn signature_change_display_segments(item: &str) -> Vec<(&str, bool)> {
    let Some((old, new)) = item.split_once(SIGNATURE_CHANGE_SEPARATOR) else {
        return vec![(item, false)];
    };
    aligned_added_tokens(old, new)
        .into_iter()
        .map(|token| (token.text, token.changed))
        .collect()
}

fn paint_signature_change_lines(old: &str, new: &str) -> Vec<String> {
    if !old.contains('\n') && !new.contains('\n') {
        return vec![paint_signature_change_line(old, new)];
    }

    let old_lines = old.lines().collect::<Vec<_>>();
    let new_lines = new.lines().collect::<Vec<_>>();
    signature_line_diff(&old_lines, &new_lines)
        .into_iter()
        .map(paint_signature_line_diff)
        .collect()
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SignatureLineDiff<'a> {
    Context(&'a str),
    Added(&'a str),
    Removed(&'a str),
}

fn signature_line_diff<'a>(
    old_lines: &[&'a str],
    new_lines: &[&'a str],
) -> Vec<SignatureLineDiff<'a>> {
    let old_len = old_lines.len();
    let new_len = new_lines.len();
    let mut table = vec![vec![0usize; new_len + 1]; old_len + 1];

    for old_index in (0..old_len).rev() {
        for new_index in (0..new_len).rev() {
            table[old_index][new_index] = if old_lines[old_index] == new_lines[new_index] {
                table[old_index + 1][new_index + 1] + 1
            } else {
                table[old_index + 1][new_index].max(table[old_index][new_index + 1])
            };
        }
    }

    let mut diff = Vec::new();
    let (mut old_index, mut new_index) = (0usize, 0usize);
    while old_index < old_len && new_index < new_len {
        if old_lines[old_index] == new_lines[new_index] {
            diff.push(SignatureLineDiff::Context(new_lines[new_index]));
            old_index += 1;
            new_index += 1;
        } else if table[old_index + 1][new_index] >= table[old_index][new_index + 1] {
            diff.push(SignatureLineDiff::Removed(old_lines[old_index]));
            old_index += 1;
        } else {
            diff.push(SignatureLineDiff::Added(new_lines[new_index]));
            new_index += 1;
        }
    }
    while old_index < old_len {
        diff.push(SignatureLineDiff::Removed(old_lines[old_index]));
        old_index += 1;
    }
    while new_index < new_len {
        diff.push(SignatureLineDiff::Added(new_lines[new_index]));
        new_index += 1;
    }
    diff
}

fn paint_signature_line_diff(line: SignatureLineDiff<'_>) -> String {
    match line {
        SignatureLineDiff::Context(line) => format!("{} {}", style::warn("~"), style::warn(line)),
        SignatureLineDiff::Added(line) => format!("{} {}", style::accent("+"), style::accent(line)),
        SignatureLineDiff::Removed(line) => format!("{} {}", style::error("-"), style::error(line)),
    }
}

fn paint_signature_change_line(old: &str, new: &str) -> String {
    let tokens = aligned_added_tokens(old, new);
    let mut rendered = style::warn("~ ");
    for token in tokens {
        if token.changed {
            rendered.push_str(&style::accent(token.text));
        } else {
            rendered.push_str(&style::warn(token.text));
        }
    }
    rendered
}

#[derive(Default)]
struct SemanticGroups {
    files: BTreeMap<String, FileSemanticGroups>,
    dependencies: Vec<(&'static str, Vec<String>)>,
    other: Vec<String>,
}

struct FileSemanticGroups {
    path: String,
    groups: Vec<(&'static str, Vec<String>)>,
}

impl FileSemanticGroups {
    fn new(path: String) -> Self {
        Self {
            path,
            groups: Vec::new(),
        }
    }

    fn push(&mut self, label: &'static str, item: String) {
        if let Some((_, items)) = self
            .groups
            .iter_mut()
            .find(|(existing, _)| *existing == label)
        {
            items.push(item);
        } else {
            self.groups.push((label, vec![item]));
        }
    }
}

fn group_semantic_changes(changes: &[SemanticChangeEntry]) -> SemanticGroups {
    let mut grouped = SemanticGroups::default();
    for change in changes {
        let kind = change.change_type.as_str();
        match kind {
            "file_added" => push_file_change(&mut grouped, change, "File", "added"),
            "file_deleted" => push_file_change(&mut grouped, change, "File", "deleted"),
            kind if kind.starts_with("file_modified") => {
                push_file_change(&mut grouped, change, "File", "modified")
            }
            "file_renamed" => push_file_rename(&mut grouped, change),
            "function_added" => push_function_change(&mut grouped, change, "Function added"),
            "function_extracted" => push_function_extracted(&mut grouped, change),
            "function_deleted" => push_function_change(&mut grouped, change, "Function deleted"),
            "function_renamed" => push_function_rename(&mut grouped, change),
            "function_modified" => push_function_change(&mut grouped, change, "Function modified"),
            "function_moved" => push_function_change(&mut grouped, change, "Function moved"),
            "signature_changed" => push_signature_change(&mut grouped, change),
            "dependency_added" => push_dependency_change(&mut grouped, "Added", change),
            "dependency_removed" => push_dependency_change(&mut grouped, "Removed", change),
            _ => grouped.other.push(change.description.clone()),
        }
    }
    grouped
}

fn push_file_change(
    grouped: &mut SemanticGroups,
    change: &SemanticChangeEntry,
    label: &'static str,
    item: &str,
) {
    let path = semantic_path(change);
    grouped
        .files
        .entry(path.clone())
        .or_insert_with(|| FileSemanticGroups::new(path))
        .push(label, item.to_string());
}

fn push_file_rename(grouped: &mut SemanticGroups, change: &SemanticChangeEntry) {
    let to_path = semantic_path(change);
    let item = change
        .from_path
        .as_ref()
        .map(|from| format!("{from} -> {to_path}"))
        .unwrap_or_else(|| change.description.clone());
    grouped
        .files
        .entry(to_path.clone())
        .or_insert_with(|| FileSemanticGroups::new(to_path))
        .push("File", item);
}

fn push_function_change(
    grouped: &mut SemanticGroups,
    change: &SemanticChangeEntry,
    label: &'static str,
) {
    let path = semantic_path(change);
    let item = change
        .new_name
        .as_deref()
        .or(change.old_name.as_deref())
        .map(str::to_string)
        .unwrap_or_else(|| change.description.clone());
    grouped
        .files
        .entry(path.clone())
        .or_insert_with(|| FileSemanticGroups::new(path))
        .push(label, item);
}

fn push_function_extracted(grouped: &mut SemanticGroups, change: &SemanticChangeEntry) {
    let path = semantic_path(change);
    let item = match (&change.new_name, &change.old_name) {
        (Some(name), Some(source)) => {
            let source = match change.from_path.as_deref() {
                Some(source_path) if source_path != path => format!("{source} ({source_path})"),
                _ => source.clone(),
            };
            format!("{name} from {source}")
        }
        (Some(name), None) => name.clone(),
        _ => change.description.clone(),
    };
    grouped
        .files
        .entry(path.clone())
        .or_insert_with(|| FileSemanticGroups::new(path))
        .push("Function extracted", item);
}

fn push_function_rename(grouped: &mut SemanticGroups, change: &SemanticChangeEntry) {
    let path = semantic_path(change);
    let item = match (&change.old_name, &change.new_name) {
        (Some(old), Some(new)) => format!("{old}{SIGNATURE_CHANGE_SEPARATOR}{new}"),
        _ => change.description.clone(),
    };
    grouped
        .files
        .entry(path.clone())
        .or_insert_with(|| FileSemanticGroups::new(path))
        .push("Function renamed", item);
}

fn push_signature_change(grouped: &mut SemanticGroups, change: &SemanticChangeEntry) {
    let path = semantic_path(change);
    let item = match (&change.old_name, &change.new_name) {
        (Some(old), Some(new)) => format!("{old}{SIGNATURE_CHANGE_SEPARATOR}{new}"),
        _ => change.description.clone(),
    };
    grouped
        .files
        .entry(path.clone())
        .or_insert_with(|| FileSemanticGroups::new(path))
        .push("Signature changed", item);
}

fn push_dependency_change(
    grouped: &mut SemanticGroups,
    label: &'static str,
    change: &SemanticChangeEntry,
) {
    if let Some((_, items)) = grouped
        .dependencies
        .iter_mut()
        .find(|(existing, _)| *existing == label)
    {
        items.push(change.description.clone());
    } else {
        grouped
            .dependencies
            .push((label, vec![change.description.clone()]));
    }
}

fn semantic_path(change: &SemanticChangeEntry) -> String {
    change
        .path
        .as_ref()
        .or(change.to_path.as_ref())
        .or(change.from_path.as_ref())
        .cloned()
        .unwrap_or_else(|| "(unknown path)".to_string())
}

#[cfg(test)]
mod tests {
    use objects::object::FileMode;

    use super::{
        SIGNATURE_CHANGE_SEPARATOR, aligned_added_tokens, group_semantic_changes, paint_line,
        paint_signature_change_item_lines, quote_path_for_patch, render_diff_patch,
        render_diff_patch_bytes, signature_change_display_segments,
    };
    use crate::cli::commands::diff::diff_types::{
        DiffOutput, FileChange, FileEolState, LineDiff, SemanticChangeEntry, change_line_counts,
        should_render_modified_pair,
    };

    fn modified_change_with_eol(path: &str, lines: Vec<LineDiff>, eol: FileEolState) -> FileChange {
        FileChange {
            path: path.to_string(),
            kind: "modified".to_string(),
            lines: Some(lines),
            eol,
            ..Default::default()
        }
    }

    fn diff_output_with(changes: Vec<FileChange>) -> DiffOutput {
        DiffOutput::new(None, None, changes, None, None, None)
    }

    #[cfg(unix)]
    fn hermetic_git_command(dir: &std::path::Path, args: &[&str]) -> std::process::Command {
        let mut command = std::process::Command::new("git");
        command
            .args(args)
            .current_dir(dir)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("GIT_AUTHOR_NAME", "Heddle Test")
            .env("GIT_AUTHOR_EMAIL", "heddle@example.com")
            .env("GIT_COMMITTER_NAME", "Heddle Test")
            .env("GIT_COMMITTER_EMAIL", "heddle@example.com");
        command
    }

    #[cfg(unix)]
    fn hermetic_git(dir: &std::path::Path, args: &[&str]) {
        let status = hermetic_git_command(dir, args)
            .status()
            .unwrap_or_else(|err| panic!("git {args:?} should spawn: {err}"));
        assert!(status.success(), "git {args:?} should succeed");
    }

    #[cfg(unix)]
    fn pipe_git_apply(dir: &std::path::Path, args: &[&str], patch: &[u8]) -> std::process::Output {
        use std::{io::Write, process::Stdio};

        let mut child = hermetic_git_command(dir, args)
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .unwrap_or_else(|err| panic!("git {args:?} should spawn: {err}"));
        child.stdin.as_mut().unwrap().write_all(patch).unwrap();
        child
            .wait_with_output()
            .unwrap_or_else(|err| panic!("git {args:?} should finish: {err}"))
    }

    #[cfg(unix)]
    #[test]
    fn render_diff_patch_bytes_applies_non_utf8_symlink_target_byte_exactly() {
        use std::os::unix::ffi::OsStrExt;

        use crate::cli::commands::diff::diff_types::SymlinkChange;

        let target = b"target-\xff\xfe";
        let change = FileChange {
            path: "linky".to_string(),
            kind: "added".to_string(),
            mode: Some(FileMode::Symlink),
            symlink: Some(SymlinkChange {
                old: None,
                new: Some(target.to_vec()),
            }),
            ..Default::default()
        };
        let patch = render_diff_patch_bytes(&diff_output_with(vec![change]));
        assert!(
            patch.windows(target.len()).any(|window| window == target),
            "patch must carry the raw non-UTF-8 target bytes:\n{}",
            String::from_utf8_lossy(&patch)
        );

        let scratch = tempfile::TempDir::new().unwrap();
        hermetic_git(scratch.path(), &["init", "-q"]);
        hermetic_git(scratch.path(), &["checkout", "-q", "-b", "main"]);

        let check = pipe_git_apply(scratch.path(), &["apply", "--check"], &patch);
        assert!(
            check.status.success(),
            "git apply --check rejected patch;\nstderr={}\npatch=\n{}",
            String::from_utf8_lossy(&check.stderr),
            String::from_utf8_lossy(&patch)
        );
        let applied = pipe_git_apply(scratch.path(), &["apply"], &patch);
        assert!(
            applied.status.success(),
            "git apply rejected patch;\nstderr={}\npatch=\n{}",
            String::from_utf8_lossy(&applied.stderr),
            String::from_utf8_lossy(&patch)
        );

        let applied_target = std::fs::read_link(scratch.path().join("linky")).unwrap();
        assert_eq!(
            applied_target.as_os_str().as_bytes(),
            target,
            "applied symlink target must be byte-exact"
        );
    }

    /// A mode-only modify (exec-bit flip, no content change) must render
    /// as a header-only `diff --git` + `old mode`/`new mode` block with
    /// no `@@` hunk. Regressing this drops the chmod from the patch so
    /// `git apply` can't reproduce the permission change (cid 3318629228).
    #[test]
    fn render_diff_patch_emits_mode_only_header_for_chmod() {
        let change = FileChange {
            path: "run.sh".to_string(),
            kind: "modified".to_string(),
            lines: Some(Vec::new()),
            old_mode: Some(FileMode::Normal),
            mode: Some(FileMode::Executable),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![change]));
        assert!(
            rendered.contains("diff --git a/run.sh b/run.sh"),
            "chmod-only must emit the `diff --git` header:\n{rendered}"
        );
        assert!(
            rendered.contains("old mode 100644") && rendered.contains("new mode 100755"),
            "chmod-only must emit `old mode`/`new mode`:\n{rendered}"
        );
        assert!(
            !rendered.contains("@@") && !rendered.contains("--- a/"),
            "chmod-only is header-only — no hunk body:\n{rendered}"
        );
    }

    /// A modify that changes BOTH content and mode emits the mode-header
    /// pair AND the usual `--- /+++` line-diff body.
    #[test]
    fn render_diff_patch_emits_mode_headers_with_content_hunk() {
        let change = FileChange {
            path: "run.sh".to_string(),
            kind: "modified".to_string(),
            lines: Some(vec![
                LineDiff::with_lines("@", "@ -1,1 +1,1 @@", None, None),
                LineDiff::with_lines("-", "echo old", Some(1), None),
                LineDiff::with_lines("+", "echo new", None, Some(1)),
            ]),
            old_mode: Some(FileMode::Normal),
            mode: Some(FileMode::Executable),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![change]));
        assert!(
            rendered.contains("old mode 100644") && rendered.contains("new mode 100755"),
            "content+mode change must still emit the mode headers:\n{rendered}"
        );
        assert!(
            rendered.contains("--- a/run.sh")
                && rendered.contains("+++ b/run.sh")
                && rendered.contains("+echo new"),
            "content+mode change must still emit the line-diff body:\n{rendered}"
        );
    }

    /// An unchanged mode on a modify with no hunk body is a genuine
    /// no-op and must emit nothing — guards against the mode branch
    /// firing when `old_mode == mode`.
    #[test]
    fn render_diff_patch_skips_modify_with_same_mode_and_no_body() {
        let change = FileChange {
            path: "run.sh".to_string(),
            kind: "modified".to_string(),
            lines: Some(Vec::new()),
            old_mode: Some(FileMode::Normal),
            mode: Some(FileMode::Normal),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![change]));
        assert!(
            rendered.is_empty(),
            "no-op modify (same mode, no body) must emit nothing:\n{rendered}"
        );
    }

    /// A binary content modify (`binary: true`, `lines: None`) must emit
    /// git's `Binary files … differ` marker with a *placeholder* index
    /// line. Silently dropping it would let `git apply` "succeed" while
    /// the binary content stayed stale (cid 3319484747); the index line
    /// flips git into binary-patch mode so it refuses the whole patch
    /// instead of skipping the block.
    #[test]
    fn render_diff_patch_binary_modify_emits_marker_with_index() {
        let change = FileChange {
            path: "binary.bin".to_string(),
            kind: "modified".to_string(),
            binary: true,
            lines: None,
            mode: Some(FileMode::Normal),
            old_mode: Some(FileMode::Normal),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![change]));
        assert!(
            rendered.contains("diff --git a/binary.bin b/binary.bin"),
            "binary modify must emit a diff header:\n{rendered}"
        );
        assert!(
            rendered.contains("index 0000000..0000000 100644"),
            "binary modify must emit a placeholder index line:\n{rendered}"
        );
        assert!(
            rendered.contains("Binary files a/binary.bin and b/binary.bin differ"),
            "binary modify must emit the binary marker:\n{rendered}"
        );
        assert!(
            !rendered.contains("--- a/binary.bin"),
            "binary modify must not emit a text hunk header:\n{rendered}"
        );
    }

    /// A binary modify whose mode *also* changed emits the
    /// `old mode`/`new mode` pair (so the chmod is recorded) followed by
    /// the placeholder index + binary marker — never a mode-only chmod
    /// patch that git apply would accept while leaving stale binary
    /// content (cid 3319484747).
    #[test]
    fn render_diff_patch_binary_modify_with_mode_change_keeps_marker() {
        let change = FileChange {
            path: "binary.bin".to_string(),
            kind: "modified".to_string(),
            binary: true,
            lines: None,
            old_mode: Some(FileMode::Normal),
            mode: Some(FileMode::Executable),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![change]));
        assert!(
            rendered.contains("old mode 100644") && rendered.contains("new mode 100755"),
            "binary+mode change must still record the chmod:\n{rendered}"
        );
        assert!(
            rendered.contains("index 0000000..0000000"),
            "binary+mode change must emit the placeholder index line:\n{rendered}"
        );
        assert!(
            rendered.contains("Binary files a/binary.bin and b/binary.bin differ"),
            "binary+mode change must still emit the binary marker:\n{rendered}"
        );
    }

    /// A binary add emits `new file mode` + placeholder index + marker;
    /// a binary delete mirrors it with `deleted file mode`.
    #[test]
    fn render_diff_patch_binary_add_and_delete_emit_markers() {
        let added = FileChange {
            path: "added.bin".to_string(),
            kind: "added".to_string(),
            binary: true,
            lines: None,
            mode: Some(FileMode::Normal),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![added]));
        assert!(
            rendered.contains("new file mode 100644")
                && rendered.contains("index 0000000..0000000")
                && rendered.contains("Binary files /dev/null and b/added.bin differ"),
            "binary add marker:\n{rendered}"
        );

        let deleted = FileChange {
            path: "gone.bin".to_string(),
            kind: "deleted".to_string(),
            binary: true,
            lines: None,
            mode: Some(FileMode::Normal),
            ..Default::default()
        };
        let rendered = render_diff_patch(&diff_output_with(vec![deleted]));
        assert!(
            rendered.contains("deleted file mode 100644")
                && rendered.contains("index 0000000..0000000")
                && rendered.contains("Binary files a/gone.bin and /dev/null differ"),
            "binary delete marker:\n{rendered}"
        );
    }

    /// A change whose `lines` vector is present but empty must also
    /// be skipped — the file path is known but there's no hunk body
    /// to render. Mixed batches (one renderable, one empty) must keep
    /// rendering the renderable change.
    #[test]
    fn render_diff_patch_skips_change_with_empty_lines() {
        let empty = FileChange {
            path: "empty.txt".to_string(),
            kind: "modified".to_string(),
            lines: Some(Vec::new()),
            ..Default::default()
        };
        let real = modified_change_with_eol(
            "real.txt",
            vec![
                LineDiff::with_lines("@", "@ -1,1 +1,1 @@", None, None),
                LineDiff::with_lines("-", "old", Some(1), None),
                LineDiff::with_lines("+", "new", None, Some(1)),
            ],
            FileEolState::default(),
        );
        let rendered = render_diff_patch(&diff_output_with(vec![empty, real]));
        assert!(
            !rendered.contains("empty.txt"),
            "skipped change must not emit a header: {rendered}"
        );
        assert!(
            rendered.contains("--- a/real.txt"),
            "renderable change must still be emitted: {rendered}"
        );
    }

    /// When both sides lack a trailing newline AND their tails land on
    /// the same context line, the renderer emits the line once and a
    /// single `\ No newline at end of file` marker that documents both
    /// sides' state. `git diff` does the same — two markers in a row
    /// would be a corruption.
    #[test]
    fn render_diff_patch_collapses_both_side_no_eol_marker_on_shared_tail() {
        // `more` is the tail for both sides; the change is on the line
        // above (hello -> world). Both blobs end without `\n`.
        let lines = vec![
            LineDiff::with_lines("@", "@ -1,2 +1,2 @@", None, None),
            LineDiff::with_lines("-", "hello", Some(1), None),
            LineDiff::with_lines("+", "world", None, Some(1)),
            LineDiff::with_lines(" ", "more", Some(2), Some(2)),
        ];
        let eol = FileEolState {
            old_has_final_newline: false,
            new_has_final_newline: false,
            old_line_count: 2,
            new_line_count: 2,
        };
        let change = modified_change_with_eol("tail.txt", lines, eol);
        let rendered = render_diff_patch(&diff_output_with(vec![change]));

        let marker_count = rendered.matches("\\ No newline at end of file").count();
        assert_eq!(
            marker_count, 1,
            "shared-tail double-no-eol must emit exactly one marker, got:\n{rendered}"
        );
        // The context line must NOT be split into `-more`/`+more` —
        // that's the wrong branch and would confuse `git apply` about
        // whether the line is being modified.
        assert!(
            !rendered.contains("-more\n"),
            "context tail must not be split when both sides agree:\n{rendered}"
        );
        assert!(
            !rendered.contains("+more\n"),
            "context tail must not be split when both sides agree:\n{rendered}"
        );
        assert!(
            rendered.contains(" more\n\\ No newline at end of file\n"),
            "marker must sit immediately after the shared context line:\n{rendered}"
        );
    }

    /// When only the OLD side lacks a trailing newline and its tail is
    /// a context line, the renderer must split that line into a
    /// `-content` (with the marker after it) + `+content` pair so the
    /// patch unambiguously documents that the OLD file ends without
    /// `\n` while the NEW file ends with one.
    #[test]
    fn render_diff_patch_splits_context_tail_when_only_old_lacks_newline() {
        // Diff for OLD `hello` (no eol) -> NEW `hello\nmore\n`:
        // ` hello` is the old tail; `+more` is the trailing addition.
        let lines = vec![
            LineDiff::with_lines("@", "@ -1,1 +1,2 @@", None, None),
            LineDiff::with_lines(" ", "hello", Some(1), Some(1)),
            LineDiff::with_lines("+", "more", None, Some(2)),
        ];
        let eol = FileEolState {
            old_has_final_newline: false,
            new_has_final_newline: true,
            old_line_count: 1,
            new_line_count: 2,
        };
        let change = modified_change_with_eol("old.txt", lines, eol);
        let rendered = render_diff_patch(&diff_output_with(vec![change]));

        assert!(
            rendered.contains("-hello\n\\ No newline at end of file\n+hello\n"),
            "OLD-side context-tail split must emit `-hello` + marker + `+hello`:\n{rendered}"
        );
        // Only the OLD side carries a marker — the NEW side ends with
        // `\n` so its tail line must NOT be followed by a marker.
        let marker_count = rendered.matches("\\ No newline at end of file").count();
        assert_eq!(
            marker_count, 1,
            "exactly one marker expected (OLD side only):\n{rendered}"
        );
    }

    /// Mirror of the OLD-only case: when only the NEW side lacks a
    /// trailing newline and its tail is a shared context line, the
    /// split emits `-content` + `+content` + marker so the patch
    /// states "the file ends without `\n` after applying".
    #[test]
    fn render_diff_patch_splits_context_tail_when_only_new_lacks_newline() {
        // Diff for OLD `hello\nmore\n` -> NEW `hello` (no eol):
        // ` hello` is the new tail; `-more` is the removal.
        let lines = vec![
            LineDiff::with_lines("@", "@ -1,2 +1,1 @@", None, None),
            LineDiff::with_lines(" ", "hello", Some(1), Some(1)),
            LineDiff::with_lines("-", "more", Some(2), None),
        ];
        let eol = FileEolState {
            old_has_final_newline: true,
            new_has_final_newline: false,
            old_line_count: 2,
            new_line_count: 1,
        };
        let change = modified_change_with_eol("new.txt", lines, eol);
        let rendered = render_diff_patch(&diff_output_with(vec![change]));

        assert!(
            rendered.contains("-hello\n+hello\n\\ No newline at end of file\n"),
            "NEW-side context-tail split must emit `-hello` + `+hello` + marker:\n{rendered}"
        );
        let marker_count = rendered.matches("\\ No newline at end of file").count();
        assert_eq!(
            marker_count, 1,
            "exactly one marker expected (NEW side only):\n{rendered}"
        );
    }

    /// When the tail is a `-` (deletion) on the OLD side and the OLD
    /// blob lacked a trailing newline, the marker goes right after the
    /// `-line` — same as `git diff` for a delete-the-last-line patch
    /// against a no-eol source. The `+` branch is the mirror.
    #[test]
    fn render_diff_patch_marker_after_minus_line_when_old_tail_is_deletion() {
        // OLD has 2 lines (no eol on `tail`), NEW has 1 line (`only`,
        // with eol). The diff is two replacements; the second `-tail`
        // is the OLD tail.
        let lines = vec![
            LineDiff::with_lines("@", "@ -1,2 +1,1 @@", None, None),
            LineDiff::with_lines("-", "only", Some(1), None),
            LineDiff::with_lines("-", "tail", Some(2), None),
            LineDiff::with_lines("+", "only", None, Some(1)),
        ];
        let eol = FileEolState {
            old_has_final_newline: false,
            new_has_final_newline: true,
            old_line_count: 2,
            new_line_count: 1,
        };
        let change = modified_change_with_eol("del.txt", lines, eol);
        let rendered = render_diff_patch(&diff_output_with(vec![change]));

        assert!(
            rendered.contains("-tail\n\\ No newline at end of file\n"),
            "marker must follow the OLD tail deletion line:\n{rendered}"
        );
    }

    /// Pin git's C-style path quoting byte-for-byte. The conformance
    /// harness round-trips the common classes through real `git apply`;
    /// this covers the exact escape spellings (including the `\a \b \v \f
    /// \r` controls and octal fallback) the integration cells don't reach.
    #[test]
    fn quote_path_matches_git_c_style() {
        // Simple paths — and spaces, which git leaves bare — emit unquoted.
        assert_eq!(quote_path_for_patch("a/", "src/main.rs"), "a/src/main.rs");
        assert_eq!(
            quote_path_for_patch("a/", "with space.txt"),
            "a/with space.txt"
        );
        // Tab/newline/quote/backslash force quoting; the prefix is escaped
        // inside the quotes, matching git's `quote_two`.
        assert_eq!(quote_path_for_patch("a/", "tab\there"), "\"a/tab\\there\"");
        assert_eq!(
            quote_path_for_patch("b/", "line\nbreak"),
            "\"b/line\\nbreak\""
        );
        assert_eq!(quote_path_for_patch("a/", "quo\"te"), "\"a/quo\\\"te\"");
        assert_eq!(
            quote_path_for_patch("a/", "back\\slash"),
            "\"a/back\\\\slash\""
        );
        // Non-ASCII (UTF-8 é = 0xC3 0xA9) → per-byte octal.
        assert_eq!(quote_path_for_patch("a/", "café"), "\"a/caf\\303\\251\"");
        // `rename from`/`rename to` quote the bare path (empty prefix).
        assert_eq!(quote_path_for_patch("", "x\ty"), "\"x\\ty\"");
        // The remaining named C-escapes plus a low control byte (octal).
        assert_eq!(
            quote_path_for_patch("", "\u{07}\u{08}\u{0b}\u{0c}\r\u{01}"),
            "\"\\a\\b\\v\\f\\r\\001\""
        );
    }

    #[test]
    fn modified_pair_compacts_only_when_lines_share_context() {
        assert!(should_render_modified_pair(
            "    let value = 41;",
            "    let value = 42;"
        ));
        assert!(should_render_modified_pair(
            "    object::{Blob, ContentHash, EntryType, FileMode, Tree, TreeEntry},",
            "    object::{Blob, ContentHash, EntryType, FileMode, SemanticChange, Tree, TreeEntry},"
        ));
    }

    #[test]
    fn unrelated_adjacent_delete_add_lines_do_not_compact() {
        assert!(!should_render_modified_pair(
            "        return get_blob_recursive(store, &subtree, &parts[1..]);",
            "fn put_blob(store: &InMemoryStore, content: &str) -> ContentHash {"
        ));
        assert!(!should_render_modified_pair("    Ok(None)", "fn put_tree("));
    }

    #[test]
    fn modified_pair_aligns_insertions_around_existing_tokens() {
        let tokens = aligned_added_tokens(
            "    collections::HashMap,",
            "    collections::{HashMap, HashSet},",
        );
        let mut rendered = String::new();
        let mut in_changed_span = false;
        for token in tokens {
            if token.changed && !in_changed_span {
                rendered.push('[');
                in_changed_span = true;
            } else if !token.changed && in_changed_span {
                rendered.push(']');
                in_changed_span = false;
            }
            rendered.push_str(token.text);
        }
        if in_changed_span {
            rendered.push(']');
        }

        assert_eq!(rendered, "    collections::[{]HashMap[, HashSet}],");
    }

    #[test]
    fn line_renderer_shows_old_and_new_line_numbers() {
        let line = LineDiff::with_lines(" ", "let value = 42;", Some(7), Some(8));

        let rendered = paint_line(&line);
        assert!(rendered.contains("   7    8 | "));
        assert!(rendered.ends_with(" let value = 42;"));
    }

    #[test]
    fn stat_counts_pure_insertions_as_additions() {
        let lines = vec![
            LineDiff::with_lines("@", "@ -1,1 +1,2 @@", None, None),
            LineDiff::with_lines(" ", "base", Some(1), Some(1)),
            LineDiff::with_lines("+", "added", None, Some(2)),
        ];

        let counts = change_line_counts(Some(&lines));
        assert_eq!(counts.added, 1);
        assert_eq!(counts.modified, 0);
        assert_eq!(counts.deleted, 0);
    }

    #[test]
    fn semantic_changes_group_by_file_then_type() {
        let changes = vec![
            semantic_entry(
                "function_extracted",
                "src/lib.rs",
                Some("render_diff"),
                Some("is_blank_or_visual_decoration"),
            ),
            semantic_entry(
                "function_extracted",
                "src/lib.rs",
                None,
                Some("is_visual_decoration_line"),
            ),
            semantic_entry("function_deleted", "src/lib.rs", Some("old_helper"), None),
        ];

        let grouped = group_semantic_changes(&changes);
        let file = grouped.files.get("src/lib.rs").unwrap();

        assert_eq!(file.groups[0].0, "Function extracted");
        assert_eq!(
            file.groups[0].1,
            vec![
                "is_blank_or_visual_decoration from render_diff".to_string(),
                "is_visual_decoration_line".to_string()
            ]
        );
        assert_eq!(file.groups[1].0, "Function deleted");
        assert_eq!(file.groups[1].1, vec!["old_helper".to_string()]);
    }

    #[test]
    fn semantic_changes_show_cross_file_extraction_source() {
        let mut change = semantic_entry(
            "function_extracted",
            "src/new.rs",
            Some("render_diff"),
            Some("is_blank_or_visual_decoration"),
        );
        change.from_path = Some("src/old.rs".to_string());

        let grouped = group_semantic_changes(&[change]);
        let file = grouped.files.get("src/new.rs").unwrap();

        assert_eq!(
            file.groups[0].1,
            vec!["is_blank_or_visual_decoration from render_diff (src/old.rs)".to_string()]
        );
    }

    #[test]
    fn semantic_signature_change_segments_changed_signature_once() {
        let item = format!(
            "fn parse(input: &str) -> Result<()>{SIGNATURE_CHANGE_SEPARATOR}fn parse(input: &str, mode: Mode) -> Result<()>"
        );
        let segments = signature_change_display_segments(&item);
        let mut rendered = String::new();
        let mut in_changed_span = false;
        for (text, changed) in segments {
            if changed && !in_changed_span {
                rendered.push('[');
                in_changed_span = true;
            } else if !changed && in_changed_span {
                rendered.push(']');
                in_changed_span = false;
            }
            rendered.push_str(text);
        }
        if in_changed_span {
            rendered.push(']');
        }

        assert_eq!(
            rendered,
            "fn parse(input: &str[, mode: Mode]) -> Result<()>"
        );
    }

    #[test]
    fn semantic_multiline_signature_change_marks_inserted_lines() {
        let item = format!(
            "cmd_diff (\n    cli: &Cli,\n    show_context: bool,\n){SIGNATURE_CHANGE_SEPARATOR}cmd_diff (\n    cli: &Cli,\n    unified: usize,\n    show_context: bool,\n)"
        );

        let rendered = paint_signature_change_item_lines(&item)
            .into_iter()
            .map(|line| strip_ansi(&line))
            .collect::<Vec<_>>();

        assert_eq!(
            rendered,
            vec![
                "~ cmd_diff (",
                "~     cli: &Cli,",
                "+     unified: usize,",
                "~     show_context: bool,",
                "~ )",
            ]
        );
    }

    #[test]
    fn semantic_multiline_signature_change_preserves_removed_lines() {
        let item = format!(
            "get_blob_recursive <S: ObjectStore + ?Sized> (\n    store: &S,\n    tree: &Tree,\n    parts: &[&str],\n){SIGNATURE_CHANGE_SEPARATOR}get_blob_recursive (\n        &self,\n        tree: &Tree,\n        parts: &[&str],\n    )"
        );

        let rendered = paint_signature_change_item_lines(&item)
            .into_iter()
            .map(|line| strip_ansi(&line))
            .collect::<Vec<_>>();

        assert_eq!(
            rendered,
            vec![
                "- get_blob_recursive <S: ObjectStore + ?Sized> (",
                "-     store: &S,",
                "-     tree: &Tree,",
                "-     parts: &[&str],",
                "- )",
                "+ get_blob_recursive (",
                "+         &self,",
                "+         tree: &Tree,",
                "+         parts: &[&str],",
                "+     )",
            ]
        );
    }

    #[test]
    fn semantic_signature_group_uses_internal_separator_for_rendering() {
        let changes = vec![semantic_entry(
            "signature_changed",
            "src/lib.rs",
            Some("fn run(a: A)"),
            Some("fn run(a: A, b: B)"),
        )];

        let grouped = group_semantic_changes(&changes);
        let file = grouped.files.get("src/lib.rs").unwrap();

        assert_eq!(file.groups[0].0, "Signature changed");
        assert_eq!(
            file.groups[0].1,
            vec![format!(
                "fn run(a: A){SIGNATURE_CHANGE_SEPARATOR}fn run(a: A, b: B)"
            )]
        );
    }

    #[test]
    fn semantic_changes_keep_dependencies_out_of_file_groups() {
        let mut dependency = semantic_entry("dependency_added", "Cargo.toml", None, None);
        dependency.description = "Dependency added: serde@1".to_string();

        let grouped = group_semantic_changes(&[dependency]);

        assert!(grouped.files.is_empty());
        assert_eq!(grouped.dependencies[0].0, "Added");
        assert_eq!(
            grouped.dependencies[0].1,
            vec!["Dependency added: serde@1".to_string()]
        );
    }

    fn semantic_entry(
        change_type: &str,
        path: &str,
        old_name: Option<&str>,
        new_name: Option<&str>,
    ) -> SemanticChangeEntry {
        SemanticChangeEntry {
            change_type: change_type.to_string(),
            description: format!("{change_type}: {path}"),
            path: Some(path.to_string()),
            from_path: None,
            to_path: None,
            old_name: old_name.map(ToString::to_string),
            new_name: new_name.map(ToString::to_string),
            importance: None,
        }
    }

    fn strip_ansi(s: &str) -> String {
        let mut stripped = String::new();
        let mut chars = s.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '\u{1b}' && chars.peek() == Some(&'[') {
                chars.next();
                for ch in chars.by_ref() {
                    if ch == 'm' {
                        break;
                    }
                }
            } else {
                stripped.push(ch);
            }
        }
        stripped
    }
}