ocomment 0.1.0

Fast, byte-preserving comment checker and remover
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
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
use crate::{
    config::PolicyTrace,
    files::{NO_LANGUAGE, STDIN_PATH, SkippedFile},
};
use anyhow::Result;
use clap::ValueEnum;
#[cfg(test)]
use ocomment_core::TransformResult;
use ocomment_core::{
    ByteSpan, Comment, CommentKind, Disposition, DispositionExplanation, DispositionPatterns, Edit,
    Language, Policy, ScanOptions, ScanReport, SourceMap, TransformPlan, explain_comment_with,
};
use serde::{Serialize, Serializer, ser::SerializeSeq};
use serde_json::{Value, json};
use similar::{Algorithm, ChangeTag, capture_diff_slices, group_diff_ops};
use std::{
    collections::BTreeMap,
    io::{self, BufWriter, Write},
    path::{Component, Path, PathBuf},
};
use unicode_width::UnicodeWidthChar;

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
pub enum OutputFormat {
    #[default]
    Human,
    Json,
    Jsonl,
    Sarif,
    Github,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operation {
    Check,
    Scan,
    Diff,
    Fix,
}

#[derive(Clone, Copy, Debug, Default)]
pub struct Presentation {
    pub color: bool,
    pub hyperlinks: bool,
}

/// How much of the human report a run is allowed to write.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Verbosity {
    /// Only errors and diagnostics.
    Quiet,
    #[default]
    Normal,
    /// Everything, including the per-kind breakdown and every skipped file.
    Verbose,
}

/// Everything the renderer needs besides the results themselves.
#[derive(Clone, Copy, Debug)]
pub struct RenderOptions {
    pub format: OutputFormat,
    pub operation: Operation,
    pub presentation: Presentation,
    pub verbosity: Verbosity,
    /// Human lines carry a one-line rendering of the comment text.
    pub preview: bool,
    /// Human `check` and `scan` lines carry every comment, kept ones included,
    /// each under an indented line naming the rule that decided it.
    pub explain: bool,
    /// The run is `fix --dry-run`: it produces the diff but speaks the
    /// vocabulary of the `fix` it is standing in for.
    pub dry_run: bool,
    /// `--force-invalid` was in effect, so a file that fails to scan still had
    /// its provably safe edits applied.
    pub force_invalid: bool,
    /// The run reached the disk. A `fix` blocked by invalid syntax or an I/O
    /// error leaves this false and must not claim any removal.
    pub applied: bool,
    /// The policy the run was asked for. Only `all` promises to take every
    /// comment out, so only `all` owes an explanation for the ones it keeps.
    pub policy: Policy,
}

/// What one run found, counted once for the end-of-run summary.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Summary {
    pub files_scanned: usize,
    pub files_with_removable: usize,
    pub removable_comments: usize,
    pub kept_comments: usize,
    pub files_changed: usize,
    pub comments_removed: usize,
    pub invalid_files: usize,
    /// Non-error skips met while walking, counted under a short stable label
    /// rather than the raw reason, which can carry a configured byte limit.
    /// A path named on the command line is deliberately absent: it already has
    /// its own line on standard output and must not be counted twice.
    pub skipped_by_reason: BTreeMap<String, usize>,
    /// Non-error skips whose path was named on the command line.
    pub named_skips: usize,
    pub io_errors: usize,
}

impl Summary {
    pub fn compute(files: &[ProcessedFile], skipped: &[SkippedFile], operation: Operation) -> Self {
        let mut summary = Self {
            files_scanned: files.len(),
            ..Self::default()
        };
        for file in files {
            let removable = removable_count(file);
            summary.removable_comments += removable;
            summary.kept_comments += file.result.report.comments.len() - removable;
            if removable > 0 {
                summary.files_with_removable += 1;
            }
            if !file.result.report.valid {
                summary.invalid_files += 1;
            }
            if file.result.changed() {
                summary.files_changed += 1;
                if operation == Operation::Fix {
                    summary.comments_removed += removable;
                }
            }
        }
        for item in skipped {
            if item.error {
                summary.io_errors += 1;
            } else if item.explicit {
                summary.named_skips += 1;
            } else {
                *summary
                    .skipped_by_reason
                    .entry(skip_label(&item.reason).to_owned())
                    .or_default() += 1;
            }
        }
        summary
    }

    fn skipped_files(&self) -> usize {
        self.skipped_by_reason.values().sum()
    }
}

fn removable_count(file: &ProcessedFile) -> usize {
    file.result
        .report
        .comments
        .iter()
        .filter(|comment| comment.disposition.is_remove())
        .count()
}

/// Fold a skip reason onto a short label the summary can group by.
///
/// The per-file line says what to do about one file; the summary counts many,
/// so it trades the sentence for a key short enough to sit in a list of them.
///
/// Visible to the crate so the modules that *produce* the reasons — `files`
/// and `git` — can name this function in their own documentation rather than
/// describing a rule they do not own.
pub(crate) fn skip_label(reason: &str) -> &str {
    if reason.starts_with("larger than ") {
        "too large"
    } else if reason.starts_with("binary file") {
        "binary"
    } else if reason.starts_with("language disabled") {
        "language disabled"
    } else if reason == NO_LANGUAGE {
        "unknown language"
    } else {
        reason
    }
}

/// The `Keep` reason the core scanner gives a shebang or encoding line that
/// `--force-protected` would have removed. It is one of the six reasons the
/// differential protocol freezes, so matching on it is stable; the end-to-end
/// test `policy_all_says_how_to_remove_a_kept_preamble` is what would catch it
/// drifting apart from the scanner.
const PROTECTED_PREAMBLE: &str = "required source preamble";

/// How many comments were kept only because `--force-protected` was absent.
///
/// Counted from the disposition rather than from the comment kind: a shebang
/// held back by `--keep-kind shebang` stays kept whatever `--force-protected`
/// says, and advertising the flag for it would be a lie.
fn protected_preambles(files: &[ProcessedFile]) -> usize {
    files
        .iter()
        .flat_map(|file| &file.result.report.comments)
        .filter(|comment| {
            matches!(&comment.disposition, Disposition::Keep { reason } if reason == PROTECTED_PREAMBLE)
        })
        .count()
}

/// `1 file` / `2 files`: the count and its noun, pluralized by the regular
/// rule. Every noun the summary counts goes through this.
fn plural(count: usize, noun: &str) -> String {
    format!("{count} {noun}{}", if count == 1 { "" } else { "s" })
}

/// `1 comment` / `2 removable comments`: the noun is pluralized and an
/// optional adjective is placed in front of it.
fn comments(count: usize, adjective: &str) -> String {
    let space = if adjective.is_empty() { "" } else { " " };
    plural(count, &format!("{adjective}{space}comment"))
}

#[derive(Clone, Debug)]
pub struct ProcessedFile {
    pub path: PathBuf,
    pub source: Vec<u8>,
    pub language: Language,
    pub result: ProcessedResult,
}

/// The stages of a core transformation retained by the CLI.
///
/// Reports are always present. Edits, a source map, and transformed bytes are
/// materialized only for the commands and output formats that consume them.
#[derive(Clone, Debug)]
pub struct ProcessedResult {
    pub report: ScanReport,
    pub edits: Vec<Edit>,
    pub source_map: Option<SourceMap>,
    output: Option<Vec<u8>>,
    changed: bool,
}

impl ProcessedResult {
    pub fn report(report: ScanReport, changed: bool) -> Self {
        Self {
            report,
            edits: Vec::new(),
            source_map: None,
            output: None,
            changed,
        }
    }

    pub fn plan(
        source: &[u8],
        plan: TransformPlan,
        materialize_output: bool,
        materialize_source_map: bool,
    ) -> Self {
        let changed = plan.edits.iter().any(|edit| {
            source.get(edit.span.start..edit.span.end) != Some(edit.replacement.as_slice())
        });
        let output = materialize_output.then(|| plan.output(source));
        let source_map = materialize_source_map.then(|| plan.source_map(source.len()));
        Self {
            report: plan.report,
            edits: plan.edits,
            source_map,
            output,
            changed,
        }
    }

    #[cfg(test)]
    pub fn complete(result: TransformResult) -> Self {
        let changed = !result.edits.is_empty();
        Self {
            report: result.report,
            edits: result.edits,
            source_map: Some(result.source_map),
            output: Some(result.output),
            changed,
        }
    }

    pub const fn changed(&self) -> bool {
        self.changed
    }

    pub fn output(&self) -> &[u8] {
        self.output
            .as_deref()
            .expect("this operation requested transformed source bytes")
    }

    pub fn source_map(&self) -> &SourceMap {
        self.source_map
            .as_ref()
            .expect("this output format requested a source map")
    }
}

#[derive(Serialize)]
struct JsonFile<'a> {
    path: String,
    language: Language,
    changed: bool,
    report: &'a ocomment_core::ScanReport,
    edits: &'a [ocomment_core::Edit],
    source_map: &'a SourceMap,
}

/// The one-line label for a comment OComment would delete.
pub fn removable_label(kind: CommentKind) -> String {
    format!("removable {kind} comment")
}

/// The one-line label for a comment OComment deliberately protects.
pub fn kept_label(kind: CommentKind, reason: &str) -> String {
    format!("{}: {reason}", kept_prefix(kind))
}

/// The same label without a reason, for a report that gives the reason on a
/// line of its own.
fn kept_prefix(kind: CommentKind) -> String {
    format!("kept {kind} comment")
}

/// What `--explain` needs to account for one file's comments: the options its
/// scan actually ran with, and where each of their settings came from.
#[derive(Clone, Debug)]
pub struct FileExplanation {
    pub options: ScanOptions,
    pub trace: PolicyTrace,
}

/// That material for the files of one run, under the path the run reports each
/// file by. A run that was not asked to explain anything carries none.
pub type Explanations = BTreeMap<PathBuf, FileExplanation>;

/// One file's explanation material with its policy patterns already compiled.
///
/// The two regex sets are the same for every comment in the file, so they are
/// built once when the file is reached rather than once per reported line.
struct Explainer<'a> {
    material: &'a FileExplanation,
    patterns: DispositionPatterns,
}

impl<'a> Explainer<'a> {
    /// An unparseable pattern list is ignored here as the scanner ignores it,
    /// which is exactly what `explain_disposition` falls back to on its own.
    fn new(material: &'a FileExplanation) -> Self {
        Self {
            patterns: DispositionPatterns::compile(&material.options)
                .unwrap_or_else(|_| DispositionPatterns::empty()),
            material,
        }
    }
}

/// The indented line under one reported comment: the rule that decided its
/// fate, and either the setting behind that rule or the flag that would
/// overrule it.
///
/// The pattern a regex explanation quotes and the globs a source names were
/// both written by whoever wrote the configuration, so the composed line gets a
/// comment preview's treatment before it reaches a terminal: one line, no
/// control sequences. The width is not capped — a line that ends in an ellipsis
/// where the pattern was answers nothing.
fn explanation_line(
    file: &ProcessedFile,
    comment: &Comment,
    explainer: &Explainer<'_>,
    options: &RenderOptions,
) -> String {
    let material = explainer.material;
    let start = comment.span.start.min(file.source.len());
    let end = comment.span.end.clamp(start, file.source.len());
    let verdict = explain_comment_with(
        &explainer.patterns,
        comment,
        &file.source[start..end],
        file.language,
        &material.options,
    );
    let tail = match material.trace.origin_of(&verdict, &material.options) {
        Some(origin) => format!(" ({origin})"),
        None => next_step(&verdict),
    };
    format!(
        "    {}{}{}",
        color("\x1b[2m", options.presentation.color),
        fold(&format!("{verdict}{tail}")),
        color("\x1b[0m", options.presentation.color)
    )
}

/// Write that line under the comment it is about, when the run has the
/// material to account for it.
fn write_explanation(
    output: &mut impl Write,
    file: &ProcessedFile,
    comment: &Comment,
    explainer: Option<&Explainer<'_>>,
    options: &RenderOptions,
) -> Result<()> {
    let Some(explainer) = explainer else {
        return Ok(());
    };
    wrote(writeln!(
        output,
        "{}",
        explanation_line(file, comment, explainer, options)
    ))
}

/// How to overrule a built-in rule, which no setting decided and no table can
/// be pointed at for.
fn next_step(verdict: &DispositionExplanation) -> String {
    match verdict {
        DispositionExplanation::ProtectedPreamble => {
            "; add --force-protected to remove it".to_owned()
        }
        DispositionExplanation::KeptHtml => format!(
            "; use --remove-kind {} or --policy all to remove it",
            CommentKind::HtmlComment
        ),
        DispositionExplanation::KeptDirective { kind, .. } => {
            format!("; use --remove-kind {kind} or --policy all to remove it")
        }
        /* NOTE: The one keep with no flag behind it. `--policy all` does not
         * reach it either: what holds the body open is whatever comment is
         * still standing under this one, so that is the line to take first. */
        DispositionExplanation::KeptStructural { .. } => {
            "; the comment under it has to go first".to_owned()
        }
        _ => String::new(),
    }
}

/// How many display columns a comment preview may occupy.
const PREVIEW_COLUMNS: usize = 72;

/// A one-line, terminal-safe rendering of the comment at `span`.
///
/// Comment text is untrusted input that is about to be written to a terminal,
/// so the whole comment is folded onto one line, every control character —
/// `ESC` above all — is replaced with U+FFFD instead of being forwarded, and
/// the result is cut to `max_columns` display columns.
fn preview(source: &[u8], span: ByteSpan, max_columns: usize) -> String {
    let start = span.start.min(source.len());
    let end = span.end.clamp(start, source.len());
    truncate(
        fold(&String::from_utf8_lossy(&source[start..end])),
        max_columns,
    )
}

/// The same treatment for a line that did not come out of a source file.
///
/// What an external tool on `PATH` says about itself is untrusted for exactly
/// the reason a comment is: `doctor` prints it to the same terminal, and a
/// tool planted there could otherwise clear the screen or repaint the report
/// from its own version line.
pub(crate) fn sanitize_line(text: &str) -> String {
    truncate(fold(text), PREVIEW_COLUMNS)
}

/// The same treatment for a message that must not be cut short.
///
/// A comment preview is commentary and can be trusted to a fixed width, but a
/// diagnostic is the whole answer to a run that produced nothing else. The
/// `regex` crate writes a parse error over several lines, with a caret under
/// the byte it stopped at; the caret means nothing once the lines are joined,
/// yet the sentence after it names what is actually wrong with the pattern. So
/// this one folds — one line, no control characters — and keeps every word.
pub(crate) fn sanitize_message(text: &str) -> String {
    fold(text)
}

/// The same treatment for a name that must not be cut short — or reworded.
///
/// A directory name is chosen by whoever made the directory, so the rows
/// `doctor` prints one on are untrusted for the same reason a version line is.
/// What they are not is commentary: an absolute path is easily longer than a
/// comment preview may be, and a row that ends in an ellipsis where the reader
/// was looking for the rest of the path answers nothing.
///
/// Neither is the whitespace in a path commentary, which is why this does not
/// borrow [`fold`]: a name may begin with a space or carry a tab, and a reader
/// who is shown neither cannot type the name back, nor find it in a checkout
/// that has it. So the spacing is left exactly as it was given and every
/// control character — the tab among them — is replaced with U+FFFD, which
/// keeps the promise `fold` was borrowed for in the first place: whatever the
/// name holds, the row stays one row.
pub(crate) fn sanitize_path(text: &str) -> String {
    text.chars()
        .map(|character| {
            if is_control(character) {
                '\u{fffd}'
            } else {
                character
            }
        })
        .collect()
}

/// The same treatment for a line of source a prompt has to show as code.
///
/// A hunk is read for its shape as much as for its text — indentation says
/// what a line belongs to — so unlike a comment preview this one keeps the
/// spaces it was given and expands a tab onto the same eight-column stop the
/// `columns` layout measures a replacement by. What it does not keep is
/// anything that drives the terminal: every control character, `ESC` and the
/// bidirectional overrides above all, still becomes U+FFFD, and the result is
/// still one line cut to a fixed width, because the question underneath it has
/// to stay on the screen with it.
pub(crate) fn sanitize_source_line(text: &str) -> String {
    let mut line = String::with_capacity(text.len());
    let mut column = 0usize;
    for character in text.chars() {
        if character == '\t' {
            let width = TAB_WIDTH - (column % TAB_WIDTH);
            line.extend(std::iter::repeat_n(' ', width));
            column += width;
        } else if is_control(character) {
            line.push('\u{fffd}');
            column += 1;
        } else {
            line.push(character);
            column += columns(character);
        }
    }
    truncate(line, PREVIEW_COLUMNS)
}

/// The tab stop `sanitize_source_line` expands to, the one the `columns`
/// layout already measures a tab by.
const TAB_WIDTH: usize = 8;

/// Fold `text` onto one control-free line.
fn fold(text: &str) -> String {
    let mut folded = String::with_capacity(text.len());
    let mut pending_space = false;
    for character in text.chars() {
        if matches!(character, ' ' | '\t' | '\r' | '\n' | '\u{c}') {
            /* NOTE: Leading whitespace is dropped, and a run only becomes a space
             * once something else follows it, so the tail is trimmed too. */
            pending_space = !folded.is_empty();
            continue;
        }
        if pending_space {
            folded.push(' ');
            pending_space = false;
        }
        folded.push(if is_control(character) {
            '\u{fffd}'
        } else {
            character
        });
    }
    folded
}

/// C0, DEL, C1, and the bidirectional and separator format controls. None of
/// these may reach the terminal verbatim: C0 drives it, the bidi overrides and
/// isolates can make a comment render as its own reverse, and U+2028/U+2029
/// break the promise that a preview is one line. U+061C joins the marks it
/// belongs with, and U+FEFF is invisible wherever it lands.
fn is_control(character: char) -> bool {
    matches!(
        character,
        '\u{0}'..='\u{1f}'
            | '\u{7f}'..='\u{9f}'
            | '\u{61c}'
            | '\u{200e}'..='\u{200f}'
            | '\u{2028}'..='\u{2029}'
            | '\u{202a}'..='\u{202e}'
            | '\u{2066}'..='\u{2069}'
            | '\u{feff}'
    )
}

fn columns(character: char) -> usize {
    UnicodeWidthChar::width(character).unwrap_or(0)
}

/// How many characters a preview may carry for each column it may occupy.
/// Zero-width and combining characters cost no columns, so the width budget on
/// its own cannot bound the line a terminal has to hold.
const PREVIEW_CHARS_PER_COLUMN: usize = 4;

/// Cut `text` to `max_columns` display columns and to a hard character cap,
/// never inside a wide character, leaving room for the ellipsis that marks the
/// cut.
fn truncate(text: String, max_columns: usize) -> String {
    let max_chars = max_columns.saturating_mul(PREVIEW_CHARS_PER_COLUMN);
    if text.chars().map(columns).sum::<usize>() <= max_columns && text.chars().count() <= max_chars
    {
        return text;
    }
    let column_budget = max_columns.saturating_sub(1);
    let char_budget = max_chars.saturating_sub(1);
    let mut cut = String::with_capacity(text.len());
    let mut width = 0usize;
    for (taken, character) in text.chars().enumerate() {
        if taken >= char_budget {
            break;
        }
        width += columns(character);
        if width > column_budget {
            break;
        }
        cut.push(character);
    }
    cut.push('\u{2026}');
    cut
}

/// The `: <text>` tail a human line carries, dimmed when colour is on.
fn preview_suffix(source: &[u8], span: ByteSpan, options: &RenderOptions) -> String {
    if !options.preview {
        return String::new();
    }
    let text = preview(source, span, PREVIEW_COLUMNS);
    if text.is_empty() {
        return String::new();
    }
    format!(
        ": {}{text}{}",
        color("\x1b[2m", options.presentation.color),
        color("\x1b[0m", options.presentation.color)
    )
}

/// The handle every path that writes the product of a run takes: standard
/// output, locked once for the whole run and buffered.
///
/// `println!` panics when its write fails, and the release profile aborts on
/// panic, so a reader that stops early — `ocomment … | head` — would end the
/// process with SIGABRT. Writing through a handle that returns its errors lets
/// the caller decide instead, and `main` ends a closed pipe quietly.
pub type Stdout = BufWriter<io::StdoutLock<'static>>;

/// Lock standard output for the rest of the run and buffer it.
pub fn stdout() -> Stdout {
    BufWriter::new(io::stdout().lock())
}

/// The reader of the program's own output went away mid-run.
///
/// A broken pipe is only benign when it is *our* report that could not be
/// written; `ocomment … | head` is a reader that finished, not a run that
/// failed. Every other broken pipe — writing a rewritten blob into
/// `git hash-object`, for one — is a real failure, so the benign case is
/// tagged with this marker at the write that raised it instead of being
/// recognized by error kind anywhere in the chain.
#[derive(Debug)]
pub struct OutputPipeClosed;

impl std::fmt::Display for OutputPipeClosed {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("the reader of standard output closed the pipe")
    }
}

impl std::error::Error for OutputPipeClosed {}

/// Push the last buffered bytes out.
///
/// A `BufWriter` drops the error of the write it performs while being dropped,
/// so every writer is finished by hand and the failure reaches the caller.
pub fn finish(writer: &mut impl Write) -> Result<()> {
    wrote(writer.flush())
}

/// Raise one write to the program's own output, tagging the reader that closed
/// the pipe so `main` can end quietly for that case alone.
pub fn wrote(result: io::Result<()>) -> Result<()> {
    result.map_err(output_failure)
}

/// The error one failed write to our own output becomes.
fn output_failure(error: io::Error) -> anyhow::Error {
    if error.kind() == io::ErrorKind::BrokenPipe {
        return anyhow::Error::new(OutputPipeClosed);
    }
    anyhow::Error::new(error).context("cannot write standard output")
}

/// Write one line of commentary to standard error.
///
/// Commentary — the `-v` trace, the end-of-run summary — is not the product of
/// the run, so a reader that has already gone away is not a failure to report:
/// a closed pipe is dropped and only a real write failure is raised. What must
/// not happen is what `eprintln!` does, which is panic, and so abort under the
/// release profile.
pub fn note(writer: &mut impl Write, line: &str) -> Result<()> {
    match writeln!(writer, "{line}") {
        Err(error) if error.kind() != io::ErrorKind::BrokenPipe => {
            Err(anyhow::Error::new(error).context("cannot write standard error"))
        }
        _ => Ok(()),
    }
}

/// Turn a serialization failure back into the I/O error it usually is.
///
/// `serde_json` reports a failed write as an error of its own whose `source`
/// is the *source* of the I/O error rather than the I/O error itself, so a
/// closed pipe would be invisible to anything walking the chain. Its `From`
/// conversion hands the original error back.
fn write_error(error: serde_json::Error) -> anyhow::Error {
    output_failure(io::Error::from(error))
}

pub fn render(
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
    options: &RenderOptions,
) -> Result<()> {
    render_explained(files, skipped, options, &Explanations::new())
}

/// The same report, with the material `--explain` needs for the files it has
/// it for. A file with none is reported exactly as `render` reports it.
pub fn render_explained(
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
    options: &RenderOptions,
    explanations: &Explanations,
) -> Result<()> {
    let mut output = stdout();
    match options.format {
        OutputFormat::Human => render_human(&mut output, files, skipped, options, explanations),
        OutputFormat::Json => render_json(&mut output, files, skipped),
        OutputFormat::Jsonl => render_jsonl(&mut output, files, skipped),
        OutputFormat::Sarif => render_sarif(&mut output, files, skipped),
        OutputFormat::Github => render_github(&mut output, files, skipped, options.verbosity),
    }?;
    finish(&mut output)
}

fn render_human(
    output: &mut impl Write,
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
    options: &RenderOptions,
    explanations: &Explanations,
) -> Result<()> {
    let operation = options.operation;
    let presentation = options.presentation;
    let quiet = options.verbosity == Verbosity::Quiet;
    let verbose = options.verbosity == Verbosity::Verbose;
    for file in files {
        if operation == Operation::Diff && file.result.changed() {
            /* NOTE: The patch is the product of `diff`, so `-q` keeps it and drops
             * only the summary that follows on standard error. */
            wrote(output.write_all(&unified_diff(
                &file.path,
                &file.source,
                file.result.output(),
            )))?;
            continue;
        }
        let reports_comments = match operation {
            Operation::Scan => !file.result.report.comments.is_empty(),
            Operation::Fix => false,
            Operation::Check | Operation::Diff if quiet => false,
            Operation::Check | Operation::Diff if options.explain => {
                !file.result.report.comments.is_empty()
            }
            Operation::Check | Operation::Diff => file
                .result
                .report
                .comments
                .iter()
                .any(|comment| comment.disposition.is_remove()),
        };
        let lines = (!file.result.report.diagnostics.is_empty() || reports_comments)
            .then(|| LineIndex::new(&file.source));
        for diagnostic in &file.result.report.diagnostics {
            let (line, column) = lines
                .as_ref()
                .expect("a diagnostic requested a line index")
                .line_column(diagnostic.span.start);
            wrote(writeln!(
                output,
                "{}:{line}:{column}: {}{}[{}]{}: {}",
                display_path(&file.path, presentation.hyperlinks),
                color("\x1b[31m", presentation.color),
                diagnostic.severity,
                sanitize_message(&diagnostic.code),
                color("\x1b[0m", presentation.color),
                sanitize_message(&diagnostic.message)
            ))?;
        }
        let explainer = options
            .explain
            .then(|| explanations.get(&file.path))
            .flatten()
            .map(Explainer::new);
        let explainer = explainer.as_ref();
        if operation == Operation::Scan {
            // NOTE: The listing is the product of `scan`; `-q` keeps it too.
            for comment in &file.result.report.comments {
                let (line, column) = lines
                    .as_ref()
                    .expect("a scan listing requested a line index")
                    .line_column(comment.span.start);
                wrote(writeln!(
                    output,
                    "{}:{line}:{column}: {} {} {}..{}{}",
                    display_path(&file.path, presentation.hyperlinks),
                    comment.kind,
                    comment.disposition,
                    comment.span.start,
                    comment.span.end,
                    preview_suffix(&file.source, comment.span, options)
                ))?;
                write_explanation(output, file, comment, explainer, options)?;
            }
        } else if quiet {
            continue;
        } else if operation == Operation::Fix {
            if options.applied && file.result.changed() {
                wrote(writeln!(
                    output,
                    "fixed {}: removed {}",
                    display_path(&file.path, presentation.hyperlinks),
                    comments(removable_count(file), "")
                ))?;
            }
        } else {
            /* NOTE: `check` reports what it would remove. Asked to explain itself it
             * reports the rest too, because a comment it left alone is exactly
             * the one the reader is asking about. */
            for comment in &file.result.report.comments {
                let removable = comment.disposition.is_remove();
                if !options.explain && !removable {
                    continue;
                }
                let (line, column) = lines
                    .as_ref()
                    .expect("a finding requested a line index")
                    .line_column(comment.span.start);
                wrote(writeln!(
                    output,
                    "{}:{line}:{column}: {}{}{}{}",
                    display_path(&file.path, presentation.hyperlinks),
                    color(
                        if removable { "\x1b[33m" } else { "\x1b[32m" },
                        presentation.color
                    ),
                    if removable {
                        removable_label(comment.kind)
                    } else {
                        kept_prefix(comment.kind)
                    },
                    color("\x1b[0m", presentation.color),
                    preview_suffix(&file.source, comment.span, options)
                ))?;
                write_explanation(output, file, comment, explainer, options)?;
            }
        }
    }
    let skips = skip_lines(skipped, presentation, options.verbosity);
    /* NOTE: `diff` keeps standard output for the patch alone, so the skips it met
     * are left to standard error. `fix --dry-run` is that same `diff` speaking
     * for the `fix` it stands in for: a skipped path can be the whole answer
     * to the run, so the preview still owes the reader the reason — but beside
     * the summary that counts it, because what the preview promises on
     * standard output is a patch that has to survive being piped into `git
     * apply`. A plain `fix` writes no patch and keeps its skips there. */
    if operation != Operation::Diff {
        for line in &skips {
            wrote(writeln!(output, "{line}"))?;
        }
    }
    /* NOTE: The findings are on standard output and the commentary that follows is
     * on standard error; a terminal sees both, so the buffer is emptied first
     * to keep the report in the order it was written. */
    finish(output)?;
    let stderr = io::stderr();
    let mut report = stderr.lock();
    if operation == Operation::Diff && options.dry_run {
        for line in &skips {
            note(&mut report, line)?;
        }
    }
    if quiet {
        return Ok(());
    }
    let summary = Summary::compute(files, skipped, operation);
    let folded = !verbose && skipped.iter().any(|item| !item.error && !item.explicit);
    if verbose && let Some(line) = kind_breakdown(files, options) {
        note(&mut report, &line)?;
    }
    note(&mut report, &summary_report(&summary, options, folded))?;
    /* NOTE: Under any other policy a kept preamble is one of many deliberate keeps
     * and saying so every run would be noise. `all` said it would take
     * everything, so what it left behind is the surprise worth a line. */
    if options.policy == Policy::All {
        let protected = protected_preambles(files);
        if protected > 0 {
            /* NOTE: The line counts what it kept, so the pronoun that stands for it
             * has to agree with that count. */
            let pronoun = if protected == 1 { "it" } else { "them" };
            note(
                &mut report,
                &format!(
                    "{} kept; add --force-protected to remove {pronoun}.",
                    comments(protected, "protected preamble")
                ),
            )?;
        }
    }
    if summary.invalid_files > 0 && !options.force_invalid {
        let (verb, pronoun) = if summary.invalid_files == 1 {
            ("has", "it")
        } else {
            ("have", "them")
        };
        note(
            &mut report,
            &format!(
                "{} {verb} invalid syntax; nothing was written for {pronoun} \
                 (use --force-invalid to apply known-safe edits).",
                plural(summary.invalid_files, "file")
            ),
        )?;
    }
    Ok(())
}

/// The skips one run has to name, in one wording for whichever stream ends up
/// carrying them. An I/O error is named however quiet the run was asked to be:
/// it is a failure, not commentary.
///
/// Shared with `fix --interactive`, which writes no report of its own and would
/// otherwise be the one command that never says why it passed a file over.
/// Whether a skip is worth a line of the report, in human and in GitHub form.
///
/// An I/O error decides the exit code, so it is said however quietly the run
/// was asked to speak. A path the caller named is answered on a line of its
/// own, because they asked about that path. What a walk merely wandered past
/// is neither: one unscannable file is a skip, forty of them are noise, and
/// the end-of-run summary counts those instead — `-v` is how a reader asks for
/// the list. Both renderers share this so the two cannot drift apart.
pub(crate) fn skip_is_visible(item: &SkippedFile, verbosity: Verbosity) -> bool {
    item.error
        || (verbosity != Verbosity::Quiet && (item.explicit || verbosity == Verbosity::Verbose))
}

pub(crate) fn skip_lines(
    skipped: &[SkippedFile],
    presentation: Presentation,
    verbosity: Verbosity,
) -> Vec<String> {
    skipped
        .iter()
        .filter(|item| skip_is_visible(item, verbosity))
        .map(|item| {
            format!(
                "{}: {}: {}",
                display_path(&item.path, presentation.hyperlinks),
                if item.error { "error" } else { "skipped" },
                sanitize_message(&item.reason)
            )
        })
        .collect()
}

/// The numbers an interactive run's verdict is built from.
///
/// They count answers rather than findings, which is the one thing the ordinary
/// summary cannot say: it counts what a run *could* have removed.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct InteractiveOutcome {
    /// Comments the reader accepted for removal.
    pub removed: usize,
    /// Questions the reader answered. `a` and `d` answer for every remaining
    /// comment in their file, so those count here too.
    pub reviewed: usize,
    /// Comments the run had to offer, whether or not it got as far as asking.
    pub offered: usize,
    /// Files an accepted removal is written to.
    pub changed: usize,
    /// Files the run scanned.
    pub scanned: usize,
}

/// What an interactive run came to, in the vocabulary every other summary uses.
///
/// A run with nothing to offer borrows the wording the plain `fix` summary
/// gives the same answer, because the only number worth reporting there is how
/// much was looked at. A run stopped by `q` is counted against the questions it
/// actually asked, and says how many it never got to: measuring the acceptances
/// against every comment the run *could* have offered would read as a pile of
/// refusals nobody made.
///
/// Either way the verdict closes on the `(N files scanned)` every other summary
/// ends with. Answering questions about three files says nothing about how many
/// were opened to find them, and that is the number a reader checks a run
/// against.
pub(crate) fn interactive_summary(outcome: InteractiveOutcome) -> String {
    if outcome.offered == 0 {
        return format!("Nothing to fix in {}.", plural(outcome.scanned, "file"));
    }
    let unreviewed = outcome.offered.saturating_sub(outcome.reviewed);
    let tail = if unreviewed == 0 {
        String::new()
    } else {
        format!(" ({} not reviewed)", comments(unreviewed, ""))
    };
    format!(
        "Removed {} of {} in {}{tail} ({} scanned).",
        outcome.removed,
        comments(outcome.reviewed, ""),
        plural(outcome.changed, "file"),
        plural(outcome.scanned, "file")
    )
}

/// The whole end-of-run summary: the verdict for the run, the folded skips,
/// and the I/O errors that were listed one by one above it.
fn summary_report(summary: &Summary, options: &RenderOptions, folded: bool) -> String {
    let skips = skip_clause(summary, folded);
    let nothing = nothing_to(options);
    let mut report = if summary.files_scanned > 0 {
        format!("{}{skips}", summary_line(summary, options))
    } else if !skips.is_empty() {
        /* NOTE: Nothing was scanned, so the verdict would count zero files; what the
         * run actually did was pass every candidate over. */
        format!("Nothing to {nothing}:{skips}")
    } else if summary.named_skips > 0 {
        format!("Nothing to {nothing}.")
    } else {
        summary_line(summary, options)
    };
    if summary.io_errors > 0 {
        report.push_str(&format!(" {}.", plural(summary.io_errors, "I/O error")));
    }
    report
}

/// The verb a run uses for the work it found nothing to do. `fix --dry-run`
/// borrows the vocabulary of the `fix` it is standing in for, as it does
/// everywhere else in the summary.
fn nothing_to(options: &RenderOptions) -> &'static str {
    match options.operation {
        Operation::Check => "check",
        Operation::Fix => "fix",
        Operation::Diff if options.dry_run => "fix",
        Operation::Diff => "diff",
        Operation::Scan => "scan",
    }
}

/// The one-line verdict for the run, without the skipped-file clause.
fn summary_line(summary: &Summary, options: &RenderOptions) -> String {
    let scanned = plural(summary.files_scanned, "file");
    let found = || {
        format!(
            "Found {} in {} ({scanned} scanned).",
            comments(summary.removable_comments, "removable"),
            plural(summary.files_with_removable, "file")
        )
    };
    match options.operation {
        /* NOTE: `fix --dry-run` is the diff of a fix: it counts what a real run would
         * take out and points back at the run that would write it. */
        Operation::Diff if options.dry_run => {
            if summary.removable_comments == 0 {
                return format!("Nothing to fix in {scanned}.");
            }
            format!(
                "Would remove {} in {}. Rerun without --dry-run to apply.",
                comments(summary.removable_comments, ""),
                plural(summary.files_with_removable, "file")
            )
        }
        Operation::Check | Operation::Diff => {
            if summary.removable_comments == 0 {
                return format!("No removable comments in {scanned}.");
            }
            let next = if options.operation == Operation::Diff {
                "apply the patch"
            } else if summary.removable_comments == 1 {
                "remove it"
            } else {
                "remove them"
            };
            format!("{} Run `ocomment fix` to {next}.", found())
        }
        Operation::Fix => {
            if options.applied && summary.files_changed > 0 {
                format!(
                    "Removed {} in {} ({scanned} scanned).",
                    comments(summary.comments_removed, ""),
                    plural(summary.files_changed, "file")
                )
            } else if summary.removable_comments == 0 {
                format!("Nothing to fix in {scanned}.")
            } else {
                /* NOTE: The transaction never reached the disk; report what is still
                 * there rather than claiming a removal. */
                found()
            }
        }
        Operation::Scan => format!(
            "Scanned {scanned}: {} ({} removable, {} kept).",
            comments(summary.removable_comments + summary.kept_comments, ""),
            summary.removable_comments,
            summary.kept_comments
        ),
    }
}

/// The skipped-file clause appended to the summary line. Only the skips met
/// while walking are folded here; a named path was already reported on its own
/// line.
fn skip_clause(summary: &Summary, folded: bool) -> String {
    let total = summary.skipped_files();
    if total == 0 {
        return String::new();
    }
    let reasons: Vec<_> = summary
        .skipped_by_reason
        .iter()
        .map(|(label, count)| format!("{label}: {count}"))
        .collect();
    let hint = if folded { "; use -v to list" } else { "" };
    format!(
        " {} skipped ({}{hint}).",
        plural(total, "file"),
        reasons.join(", ")
    )
}

/// The `-v` breakdown of what each comment kind contributed.
fn kind_breakdown(files: &[ProcessedFile], options: &RenderOptions) -> Option<String> {
    let verb = if options.operation == Operation::Fix && options.applied {
        "removed"
    } else {
        "removable"
    };
    let mut removable = [0usize; CommentKind::ALL.len()];
    let mut kept = [0usize; CommentKind::ALL.len()];
    for file in files {
        for comment in &file.result.report.comments {
            let slot = CommentKind::ALL
                .iter()
                .position(|kind| *kind == comment.kind)
                .expect("CommentKind::ALL lists every kind");
            if comment.disposition.is_remove() {
                removable[slot] += 1;
            } else {
                kept[slot] += 1;
            }
        }
    }
    let mut parts = Vec::new();
    for (slot, kind) in CommentKind::ALL.into_iter().enumerate() {
        if removable[slot] > 0 {
            parts.push(format!("{kind} {} {verb}", removable[slot]));
        }
        if kept[slot] > 0 {
            parts.push(format!("{kind} {} kept", kept[slot]));
        }
    }
    (!parts.is_empty()).then(|| format!("kinds: {}", parts.join(", ")))
}

pub(crate) fn color(code: &'static str, enabled: bool) -> &'static str {
    if enabled { code } else { "" }
}

/// The path half of a report line, and the hyperlink wrapped around it.
///
/// A file name is chosen by whoever made the file, so the shown half is
/// untrusted input on its way to a terminal exactly like the preview beside
/// it, and gets `sanitize_path`'s treatment: one line, no control characters,
/// and no width cap, because a path cut to an ellipsis names no file.
///
/// The link *target* is untrusted for the same reason and by the same route —
/// the frame around it is written in escape bytes, so a name carrying one of
/// its own would close the frame early and the rest of the name would be read
/// as terminal instructions. A URL cannot carry a byte it has no spelling for
/// anyway, so the target is encoded outright rather than patched up for the
/// three characters somebody thought of first.
fn display_path(path: &Path, hyperlinks: bool) -> String {
    let display = sanitize_path(&path.display().to_string());
    if !hyperlinks {
        return display;
    }
    let absolute = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    #[cfg(unix)]
    let target = {
        use std::os::unix::ffi::OsStrExt;
        percent_encode(absolute.as_os_str().as_bytes())
    };
    #[cfg(not(unix))]
    let target = percent_encode(absolute.to_string_lossy().as_bytes());
    format!("\x1b]8;;file://{target}\x1b\\{display}\x1b]8;;\x1b\\")
}

/// The path half of a `file://` URL, with every byte a URL may not carry
/// spelled as the `%XX` a reader of the URL puts back.
///
/// The unreserved set of RFC 3986 is kept as it stands, and so is the `/` that
/// separates one path segment from the next; everything else — the space and
/// the `#` that used to be special-cased here, the `%` that makes an encoding
/// an encoding, and every control byte — is encoded. A path is bytes rather
/// than characters, so the encoding is done over the UTF-8 the name is spelled
/// in: a `%XX` pair is defined as a byte, and half an encoded character is not
/// a character a terminal can put back together.
fn percent_encode(path: impl AsRef<[u8]>) -> String {
    let path = path.as_ref();
    let mut encoded = String::with_capacity(path.len());
    for byte in path.iter().copied() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/') {
            encoded.push(char::from(byte));
        } else {
            push_percent_encoded(&mut encoded, byte);
        }
    }
    encoded
}

fn push_percent_encoded(output: &mut String, byte: u8) {
    output.push('%');
    output.push(HEX[usize::from(byte >> 4)]);
    output.push(HEX[usize::from(byte & 0xf)]);
}

/// The digits a percent-encoded byte is spelled with. RFC 3986 asks for the
/// upper-case ones.
const HEX: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
];

fn render_json(
    output: &mut impl Write,
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
) -> Result<()> {
    #[derive(Serialize)]
    struct Document<'a> {
        version: u8,
        files: JsonFiles<'a>,
        skipped: JsonSkipped<'a>,
    }
    serde_json::to_writer_pretty(
        &mut *output,
        &Document {
            version: 1,
            files: JsonFiles(files),
            skipped: JsonSkipped(skipped),
        },
    )
    .map_err(write_error)?;
    wrote(writeln!(output))?;
    Ok(())
}

struct JsonFiles<'a>(&'a [ProcessedFile]);

impl Serialize for JsonFiles<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
        for file in self.0 {
            sequence.serialize_element(&json_file(file))?;
        }
        sequence.end()
    }
}

struct JsonSkipped<'a>(&'a [SkippedFile]);

impl Serialize for JsonSkipped<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        #[derive(Serialize)]
        struct Entry<'a> {
            path: std::borrow::Cow<'a, str>,
            reason: &'a str,
            error: bool,
        }
        let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
        for item in self.0 {
            sequence.serialize_element(&Entry {
                path: item.path.to_string_lossy(),
                reason: &item.reason,
                error: item.error,
            })?;
        }
        sequence.end()
    }
}

fn render_jsonl(
    output: &mut impl Write,
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
) -> Result<()> {
    for file in files {
        serde_json::to_writer(&mut *output, &json_file(file)).map_err(write_error)?;
        wrote(writeln!(output))?;
    }
    for item in skipped {
        serde_json::to_writer(
            &mut *output,
            &json!({"type": "skip", "path": item.path.to_string_lossy(), "reason": item.reason, "error": item.error}),
        )
        .map_err(write_error)?;
        wrote(writeln!(output))?;
    }
    Ok(())
}

fn json_file(file: &ProcessedFile) -> JsonFile<'_> {
    JsonFile {
        path: file.path.to_string_lossy().into_owned(),
        language: file.language,
        changed: file.result.changed(),
        report: &file.result.report,
        edits: &file.result.edits,
        source_map: file.result.source_map(),
    }
}

/// Where a SARIF reader is sent to learn what the tool itself is.
const TOOL_INFORMATION_URI: &str = "https://github.com/P4suta/OComment";

/// Where a rule about a comment sends a reader asking why that comment is
/// reported — and why the one beside it is not.
const KIND_HELP_URI: &str = "https://github.com/P4suta/OComment#why-was-this-comment-kept";

/// The base id a path under the directory the run walked is reported against.
/// SARIF readers, GitHub code scanning among them, resolve `%SRCROOT%` to the
/// root of the checkout.
const SRCROOT: &str = "%SRCROOT%";

/// The one sentence every scan diagnostic is described by. The codes are as
/// varied as the languages that raise them, and the result carries the message
/// that says what was actually met.
const DIAGNOSTIC_DESCRIPTION: &str =
    "A problem OComment met while scanning the file; the message on the result says what it was.";

/// The repository spelling a machine format reports a path under.
///
/// GitHub's `file=` property is a repository path, while SARIF wants a URI.
/// Both start from this byte-preserving spelling: platform separators become
/// `/`, and `.` segments left by a typed path are removed. Keeping this layer
/// separate prevents URI escaping from being mistaken for a repository name.
fn report_path_bytes(path: &Path) -> Vec<u8> {
    #[cfg(unix)]
    let bytes = {
        use std::os::unix::ffi::OsStrExt;
        path.as_os_str().as_bytes().to_vec()
    };
    #[cfg(not(unix))]
    let bytes = path.to_string_lossy().replace('\\', "/").into_bytes();

    let segments: Vec<&[u8]> = bytes
        .split(|byte| *byte == b'/')
        .filter(|segment| *segment != b".")
        .collect();
    if segments.is_empty() {
        /* NOTE: The path was `.` (or `./`) and naming nothing at all would be worse
         * than naming the directory. */
        return bytes;
    }
    let mut normalized = Vec::with_capacity(bytes.len());
    for (index, segment) in segments.into_iter().enumerate() {
        if index > 0 {
            normalized.push(b'/');
        }
        normalized.extend_from_slice(segment);
    }
    normalized
}

/// Turn a repository path into UTF-8 without replacing a Unix filename byte.
/// Invalid byte sequences use `%XX`; valid Unicode keeps its semantic value.
fn report_path(path: &Path) -> String {
    lossless_text(&report_path_bytes(path))
}

fn lossless_text(mut bytes: &[u8]) -> String {
    let mut text = String::with_capacity(bytes.len());
    while !bytes.is_empty() {
        match std::str::from_utf8(bytes) {
            Ok(valid) => {
                text.push_str(valid);
                break;
            }
            Err(error) => {
                let valid = error.valid_up_to();
                text.push_str(
                    std::str::from_utf8(&bytes[..valid])
                        .expect("the UTF-8 error identifies a valid prefix"),
                );
                let invalid = error.error_len().unwrap_or(bytes.len() - valid);
                for byte in &bytes[valid..valid + invalid] {
                    push_percent_encoded(&mut text, *byte);
                }
                bytes = &bytes[valid + invalid..];
            }
        }
    }
    text
}

/// The URI spelling SARIF requires. Unlike a GitHub annotation property it is
/// an RFC 3986 reference, so spaces, controls, literal percent signs, and raw
/// Unix filename bytes are percent-encoded exactly once.
fn sarif_uri(path: &Path) -> String {
    if path == Path::new(STDIN_PATH) {
        return STDIN_PATH.to_owned();
    }
    let mut encoded = String::new();
    for byte in report_path_bytes(path) {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~' | b'/' | b':') {
            encoded.push(char::from(byte));
        } else {
            push_percent_encoded(&mut encoded, byte);
        }
    }
    encoded
}

/// Encode a GitHub workflow-command `file=` property from path bytes. This is
/// not URI encoding: GitHub decodes its small `%25`/`%0D`/`%0A` command
/// alphabet before matching the repository path. Invalid UTF-8 has no command
/// representation, so it remains visible and non-lossy as `%XX` instead of
/// silently becoming U+FFFD.
fn github_path(path: &Path) -> String {
    let bytes = report_path_bytes(path);
    let mut escaped = String::with_capacity(bytes.len());
    let mut remaining = bytes.as_slice();
    while !remaining.is_empty() {
        match std::str::from_utf8(remaining) {
            Ok(valid) => {
                escaped.push_str(&github_escape(valid));
                break;
            }
            Err(error) => {
                let valid = error.valid_up_to();
                escaped.push_str(&github_escape(
                    std::str::from_utf8(&remaining[..valid])
                        .expect("the UTF-8 error identifies a valid prefix"),
                ));
                let invalid = error.error_len().unwrap_or(remaining.len() - valid);
                for byte in &remaining[valid..valid + invalid] {
                    push_percent_encoded(&mut escaped, *byte);
                }
                remaining = &remaining[valid + invalid..];
            }
        }
    }
    escaped
}

/// The SARIF `artifactLocation` for a reported path.
///
/// A path under the directory the run started in is reported against
/// `%SRCROOT%`: SARIF resolves a relative URI against a base id, and a reader
/// given none has nothing to resolve it against, so the finding lands on no
/// file. An absolute path is not under the checkout as far as the run can
/// tell, one that climbs out through `..` has left it, and the pseudo-path
/// standard input is reported under is not a file at all — each of those is
/// reported as it stands, with no base id claiming otherwise.
fn artifact_location(path: &Path) -> Value {
    let repository_path = report_path(path);
    let uri = sarif_uri(path);
    if under_source_root(path) {
        let uri = if reads_as_a_drive_letter(&repository_path) {
            format!("./{uri}")
        } else {
            uri
        };
        json!({"uri": uri, "uriBaseId": SRCROOT})
    } else {
        json!({"uri": uri})
    }
}

/// Whether a repository-relative URI opens with a segment no reader will take
/// for a directory name.
///
/// A `uri` is read as a URI, and RFC 3986 hands a relative reference's first
/// segment to the scheme as soon as it holds a colon: `c:/a.rs` parses as the
/// scheme `c` over the path `/a.rs`, and a Windows reader sees a drive letter
/// in it besides. A POSIX checkout is free to hold a directory named `c:`, so
/// the path says which it meant with the one `.` segment the standard keeps
/// for exactly this: `./c:/a.rs` is a relative reference whatever reads it,
/// and it still resolves against `%SRCROOT%`.
///
/// Only a repository-relative path is treated this way. A GitHub annotation is
/// matched against the paths the checkout uses rather than parsed as a URI, so
/// [`report_path`] leaves the spelling alone and only this document adds to it;
/// `tools/validate_schemas.py` is the other half of the rule and turns down
/// the bare form.
fn reads_as_a_drive_letter(uri: &str) -> bool {
    let mut head = uri.split('/').next().unwrap_or_default().chars();
    matches!(
        (head.next(), head.next(), head.next()),
        (Some(letter), Some(':'), None) if letter.is_ascii_alphabetic()
    )
}

fn under_source_root(path: &Path) -> bool {
    path != Path::new(STDIN_PATH)
        && path
            .components()
            .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
        && path
            .components()
            .any(|component| matches!(component, Component::Normal(_)))
}

/// The rules of one SARIF run, and the index each result points at.
///
/// A result names its rule twice: by `ruleId`, and by the position of that
/// rule's description in `tool.driver.rules`. A code-scanning UI shows a
/// finding through that description — its title, the sentence under it, and
/// the link it offers — so handing out the id and the index together is what
/// keeps a result from pointing at a description that is not there.
///
/// Every comment kind is described whether or not the run met one, because the
/// rules a tool reports are also read as the list of what it can find. The
/// rest — a scan diagnostic, a skipped file, a file that could not be read —
/// are described as the run meets them.
struct SarifRules {
    entries: Vec<Value>,
    indices: BTreeMap<String, usize>,
}

impl SarifRules {
    fn new() -> Self {
        let mut rules = Self {
            entries: Vec::new(),
            indices: BTreeMap::new(),
        };
        for kind in CommentKind::ALL {
            rules.describe(
                &format!("removable-{kind}"),
                "note",
                &format!("Removable {kind} comment"),
                &format!(
                    "A {kind} comment OComment can remove without changing what the file does."
                ),
                KIND_HELP_URI,
            );
        }
        rules
    }

    /// The index of the rule `id`, describing it first if this run has not
    /// reported it before.
    fn describe(&mut self, id: &str, level: &str, short: &str, full: &str, help: &str) -> usize {
        if let Some(&index) = self.indices.get(id) {
            return index;
        }
        let index = self.entries.len();
        self.entries.push(json!({
            "id": id,
            "shortDescription": {"text": short},
            "fullDescription": {"text": full},
            "helpUri": help,
            "defaultConfiguration": {"level": level},
        }));
        self.indices.insert(id.to_owned(), index);
        index
    }

    fn kind(&self, kind: CommentKind) -> usize {
        let id = format!("removable-{kind}");
        *self
            .indices
            .get(&id)
            .expect("every comment kind is described")
    }

    fn index(&self, id: &str) -> usize {
        *self
            .indices
            .get(id)
            .expect("every emitted SARIF result has a prepared rule")
    }
}

/// A kebab-cased code read back as the title of a rule:
/// `unterminated-comment` is `Unterminated comment`.
fn sentence_case(code: &str) -> String {
    let spelled = code.replace('-', " ");
    let mut characters = spelled.chars();
    match characters.next() {
        Some(first) => first.to_uppercase().collect::<String>() + characters.as_str(),
        None => spelled,
    }
}

fn sarif_level(severity: ocomment_core::Severity) -> &'static str {
    match severity {
        ocomment_core::Severity::Error => "error",
        ocomment_core::Severity::Warning => "warning",
        ocomment_core::Severity::Info | ocomment_core::Severity::Hint => "note",
    }
}

/// A SARIF result array serialized one finding at a time. Keeping the rule
/// table separate lets the header be finalized first without retaining a
/// `serde_json::Value` for every comment in the run.
struct SarifResults<'a> {
    files: &'a [ProcessedFile],
    skipped: &'a [SkippedFile],
    rules: &'a SarifRules,
}

impl Serialize for SarifResults<'_> {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut results = serializer.serialize_seq(None)?;
        for file in self.files {
            if file.result.report.diagnostics.is_empty()
                && !file
                    .result
                    .report
                    .comments
                    .iter()
                    .any(|comment| comment.disposition.is_remove())
            {
                continue;
            }
            let location = artifact_location(&file.path);
            let lines = LineIndex::new(&file.source);
            for comment in file
                .result
                .report
                .comments
                .iter()
                .filter(|comment| comment.disposition.is_remove())
            {
                let (line, column) = lines.line_column(comment.span.start);
                let (end_line, end_column) = lines.line_column(comment.span.end);
                let (fix_span, replacement) = fix_for_span(file, comment.span);
                let (fix_line, fix_column) = lines.line_column(fix_span.start);
                let (fix_end_line, fix_end_column) = lines.line_column(fix_span.end);
                let kind = comment.kind.as_str();
                results.serialize_element(&json!({
                    "ruleId": format!("removable-{kind}"),
                    "ruleIndex": self.rules.kind(comment.kind),
                    "level": "note",
                    "message": {"text": removable_label(comment.kind)},
                    "locations": [{"physicalLocation": {
                        "artifactLocation": location.clone(),
                        "region": {"startLine": line, "startColumn": column,
                            "endLine": end_line, "endColumn": end_column}
                    }}],
                    "fixes": [{
                        "description": {"text": "Remove comment with OComment"},
                        "artifactChanges": [{
                            "artifactLocation": location.clone(),
                            "replacements": [{"deletedRegion": {
                                "startLine": fix_line, "startColumn": fix_column,
                                "endLine": fix_end_line, "endColumn": fix_end_column
                            }, "insertedContent": {"text": replacement}}]
                        }]
                    }]
                }))?;
            }
            for diagnostic in &file.result.report.diagnostics {
                let (line, column) = lines.line_column(diagnostic.span.start);
                let (end_line, end_column) = lines.line_column(diagnostic.span.end);
                let level = sarif_level(diagnostic.severity);
                results.serialize_element(&json!({
                    "ruleId": diagnostic.code,
                    "ruleIndex": self.rules.index(&diagnostic.code),
                    "level": level,
                    "message": {"text": diagnostic.message},
                    "locations": [{"physicalLocation": {
                        "artifactLocation": location.clone(),
                        "region": {"startLine": line, "startColumn": column,
                            "endLine": end_line, "endColumn": end_column}
                    }}]
                }))?;
            }
        }
        for item in self.skipped {
            let (id, level) = if item.error {
                ("io-error", "error")
            } else {
                ("skipped-file", "note")
            };
            results.serialize_element(&json!({
                "ruleId": id,
                "ruleIndex": self.rules.index(id),
                "level": level,
                "message": {"text": item.reason},
                "locations": [{"physicalLocation": {
                    "artifactLocation": artifact_location(&item.path)
                }}]
            }))?;
        }
        results.end()
    }
}

fn render_sarif(
    output: &mut impl Write,
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
) -> Result<()> {
    let mut rules = SarifRules::new();
    for file in files {
        for diagnostic in &file.result.report.diagnostics {
            rules.describe(
                &diagnostic.code,
                sarif_level(diagnostic.severity),
                &sentence_case(&diagnostic.code),
                DIAGNOSTIC_DESCRIPTION,
                TOOL_INFORMATION_URI,
            );
        }
    }
    for item in skipped {
        let (id, level, short, full) = if item.error {
            (
                "io-error",
                "error",
                "File could not be read",
                "A file OComment could not read or write; the message on the result carries the operating-system error.",
            )
        } else {
            (
                "skipped-file",
                "note",
                "Skipped file",
                "A file OComment did not scan; the message on the result says why it was left alone.",
            )
        };
        rules.describe(id, level, short, full, TOOL_INFORMATION_URI);
    }

    #[derive(Serialize)]
    struct Document<'a> {
        version: &'static str,
        #[serde(rename = "$schema")]
        schema: &'static str,
        runs: &'a [Run<'a>],
    }
    #[derive(Serialize)]
    struct Run<'a> {
        tool: Tool<'a>,
        results: SarifResults<'a>,
    }
    #[derive(Serialize)]
    struct Tool<'a> {
        driver: Driver<'a>,
    }
    #[derive(Serialize)]
    struct Driver<'a> {
        name: &'static str,
        version: &'static str,
        #[serde(rename = "informationUri")]
        information_uri: &'static str,
        rules: &'a [Value],
    }

    let runs = [Run {
        tool: Tool {
            driver: Driver {
                name: "ocomment",
                version: env!("CARGO_PKG_VERSION"),
                information_uri: TOOL_INFORMATION_URI,
                rules: &rules.entries,
            },
        },
        results: SarifResults {
            files,
            skipped,
            rules: &rules,
        },
    }];
    serde_json::to_writer_pretty(
        &mut *output,
        &Document {
            version: "2.1.0",
            schema: "https://json.schemastore.org/sarif-2.1.0.json",
            runs: &runs,
        },
    )
    .map_err(write_error)?;
    wrote(writeln!(output))?;
    Ok(())
}

/// The rewrite a removed comment's SARIF fix offers: the bytes it deletes and
/// the bytes that go in their place.
///
/// A fix is an offer to rewrite the file, so what it deletes has to be what the
/// run would have deleted. Under [`ocomment_core::Layout::Compact`] that is
/// wider than the comment: a comment alone on its line takes the indentation
/// before it and the terminator after it with it, and a fix cut back to the
/// comment's own span would leave behind exactly the blank line that layout
/// exists to close up. So the edit that *contains* the comment is what is
/// reported, rather than one that starts and ends where the comment does.
///
/// Edits are sorted and non-overlapping and each one spans the comment it
/// removes, so at most one of them can contain a given comment. A file whose
/// report came back invalid has comments but no edits — nothing is rewritten
/// from a source the scanner could not read to the end — and there the
/// comment's own span, with nothing to put in its place, is all there is to
/// offer.
fn fix_for_span(file: &ProcessedFile, span: ByteSpan) -> (ByteSpan, String) {
    file.result
        .edits
        .iter()
        .find(|edit| edit.span.start <= span.start && edit.span.end >= span.end)
        .map_or_else(
            || (span, String::new()),
            |edit| {
                (
                    edit.span,
                    String::from_utf8_lossy(&edit.replacement).into_owned(),
                )
            },
        )
}

fn render_github(
    output: &mut impl Write,
    files: &[ProcessedFile],
    skipped: &[SkippedFile],
    verbosity: Verbosity,
) -> Result<()> {
    for file in files {
        if file.result.report.diagnostics.is_empty()
            && !file
                .result
                .report
                .comments
                .iter()
                .any(|comment| comment.disposition.is_remove())
        {
            continue;
        }
        let lines = LineIndex::new(&file.source);
        for comment in file
            .result
            .report
            .comments
            .iter()
            .filter(|comment| comment.disposition.is_remove())
        {
            let (line, column) = lines.line_column(comment.span.start);
            wrote(writeln!(
                output,
                "::notice file={},line={line},col={column}::{}",
                github_path(&file.path),
                removable_label(comment.kind)
            ))?;
        }
        for diagnostic in &file.result.report.diagnostics {
            let (line, column) = lines.line_column(diagnostic.span.start);
            wrote(writeln!(
                output,
                "::error file={},line={line},col={column},title={}::{}",
                github_path(&file.path),
                github_escape(&diagnostic.code),
                github_escape(&diagnostic.message)
            ))?;
        }
    }
    /* INVARIANT: `-q` trims the human report down to what went wrong, and there is
     * no such thing to trim here: an annotation is the *product* of this
     * format, not commentary about it, and a hook told to work quietly is
     * still owed the notice for the path its caller named and the error for
     * the file it could not read. So the visibility rule below is asked at
     * `Normal` however quiet the run was, and only `-v` widens it. */
    let visibility = match verbosity {
        Verbosity::Quiet => Verbosity::Normal,
        loud => loud,
    };
    /* NOTE: An annotation costs the reader a line of the checks tab, so a walked
     * skip is folded away here exactly as it is in the human report: a run
     * over a repository with forty Markdown files in it must not post forty
     * notices about them. */
    for item in skipped
        .iter()
        .filter(|item| skip_is_visible(item, visibility))
    {
        wrote(writeln!(
            output,
            "::{} file={},title={}::{}",
            if item.error { "error" } else { "notice" },
            github_path(&item.path),
            if item.error {
                "OComment I/O error"
            } else {
                "OComment skipped file"
            },
            github_escape(&item.reason)
        ))?;
    }
    Ok(())
}

pub fn unified_diff(path: &Path, original: &[u8], transformed: &[u8]) -> Vec<u8> {
    let old = byte_lines(original);
    let new = byte_lines(transformed);
    let mut output = Vec::new();
    output.extend_from_slice(b"--- ");
    output.extend_from_slice(&git_patch_path(b"a/", path));
    output.extend_from_slice(b"\n+++ ");
    output.extend_from_slice(&git_patch_path(b"b/", path));
    output.push(b'\n');
    let ops = capture_diff_slices(Algorithm::Myers, &old, &new);
    for group in group_diff_ops(ops, 3) {
        let old_start = group.first().map_or(0, |op| op.old_range().start) + 1;
        let new_start = group.first().map_or(0, |op| op.new_range().start) + 1;
        let old_len: usize = group.iter().map(|op| op.old_range().len()).sum();
        let new_len: usize = group.iter().map(|op| op.new_range().len()).sum();
        output.extend_from_slice(
            format!("@@ -{old_start},{old_len} +{new_start},{new_len} @@\n").as_bytes(),
        );
        for op in group {
            for change in op.iter_changes(&old, &new) {
                let prefix = match change.tag() {
                    ChangeTag::Delete => b'-',
                    ChangeTag::Insert => b'+',
                    ChangeTag::Equal => b' ',
                };
                output.push(prefix);
                output.extend_from_slice(change.value());
                if !change.value().ends_with(b"\n") {
                    output.extend_from_slice(b"\n\\ No newline at end of file\n");
                }
            }
        }
    }
    output
}

/// Split on the byte Git treats as a line ending without decoding or replacing
/// any other byte. The newline remains in each item so the resulting patch can
/// reconstruct the source exactly.
fn byte_lines(bytes: &[u8]) -> Vec<&[u8]> {
    let mut lines = Vec::new();
    let mut start = 0;
    for (index, byte) in bytes.iter().enumerate() {
        if *byte == b'\n' {
            lines.push(&bytes[start..=index]);
            start = index + 1;
        }
    }
    if start < bytes.len() {
        lines.push(&bytes[start..]);
    }
    lines
}

/// Spell a patch header path the way Git's parser accepts it. Ordinary names
/// stay readable; bytes that could terminate or corrupt the header use Git's
/// C-style quoting, including three-digit octal escapes for non-UTF-8 bytes.
fn git_patch_path(prefix: &[u8], path: &Path) -> Vec<u8> {
    #[cfg(unix)]
    let bytes = {
        use std::os::unix::ffi::OsStrExt;
        path.as_os_str().as_bytes().to_vec()
    };
    #[cfg(not(unix))]
    let bytes = path.to_string_lossy().replace('\\', "/").into_bytes();

    let mut full = Vec::with_capacity(prefix.len() + bytes.len());
    full.extend_from_slice(prefix);
    full.extend_from_slice(&bytes);
    let quoted = full
        .iter()
        .any(|byte| *byte < b' ' || *byte >= 0x7f || matches!(*byte, b'"' | b'\\'));
    if !quoted {
        return full;
    }
    let mut output = Vec::with_capacity(full.len() + 2);
    output.push(b'"');
    for byte in full {
        match byte {
            b'\n' => output.extend_from_slice(br"\n"),
            b'\r' => output.extend_from_slice(br"\r"),
            b'\t' => output.extend_from_slice(br"\t"),
            0x08 => output.extend_from_slice(br"\b"),
            0x0c => output.extend_from_slice(br"\f"),
            b'"' => output.extend_from_slice(br#"\""#),
            b'\\' => output.extend_from_slice(br"\\"),
            b' '..=b'~' => output.push(byte),
            _ => output.extend_from_slice(format!("\\{byte:03o}").as_bytes()),
        }
    }
    output.push(b'"');
    output
}

/// A reusable byte-offset index for the CLI's one-based line and column
/// coordinates.
///
/// `after_first` preserves the established answer for an offset on the LF of
/// a CRLF pair: that offset is already on the following line, while an offset
/// after the pair begins its column after both bytes.
#[derive(Clone, Debug, Default)]
pub(crate) struct LineIndex {
    /// `(after_first << 1) | is_crlf`. Packing the CRLF bit keeps the index to
    /// one machine word per logical line break even though an offset on the
    /// LF and an offset after it have different column starts.
    breaks: Vec<usize>,
    source_len: usize,
}

impl LineIndex {
    pub(crate) fn new(source: &[u8]) -> Self {
        let mut breaks = Vec::new();
        let mut index = 0usize;
        while index < source.len() {
            if source[index] == b'\r' {
                let after_first = index + 1;
                let crlf = source.get(index + 1) == Some(&b'\n');
                breaks.push((after_first << 1) | usize::from(crlf));
                index = after_first + usize::from(crlf);
            } else if source[index] == b'\n' {
                index += 1;
                breaks.push(index << 1);
            } else {
                index += 1;
            }
        }
        Self {
            breaks,
            source_len: source.len(),
        }
    }

    pub(crate) fn line_column(&self, offset: usize) -> (usize, usize) {
        let offset = offset.min(self.source_len);
        let line_breaks = self
            .breaks
            .partition_point(|line_break| (*line_break >> 1) <= offset);
        let start = line_breaks.checked_sub(1).map_or(0, |index| {
            let encoded = self.breaks[index];
            ((encoded >> 1) + (encoded & 1)).min(offset)
        });
        (line_breaks + 1, offset - start + 1)
    }
}

fn github_escape(text: &str) -> String {
    let mut escaped = String::with_capacity(text.len());
    for character in text.chars() {
        match character {
            '%' => escaped.push_str("%25"),
            '\r' => escaped.push_str("%0D"),
            '\n' => escaped.push_str("%0A"),
            ':' => escaped.push_str("%3A"),
            ',' => escaped.push_str("%2C"),
            character if is_control(character) => {
                for byte in character.to_string().bytes() {
                    push_percent_encoded(&mut escaped, byte);
                }
            }
            character => escaped.push(character),
        }
    }
    escaped
}

pub fn changed(files: &[ProcessedFile]) -> bool {
    files.iter().any(|file| file.result.changed())
}
pub fn invalid(files: &[ProcessedFile]) -> bool {
    files.iter().any(|file| !file.result.report.valid)
}

#[allow(dead_code)]
fn _span(_: ByteSpan) -> Value {
    Value::Null
}

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

    fn linear_line_column(source: &[u8], offset: usize) -> (usize, usize) {
        let offset = offset.min(source.len());
        let mut line = 1usize;
        let mut start = 0usize;
        let mut index = 0usize;
        while index < offset {
            if source[index] == b'\r' {
                index += if source.get(index + 1) == Some(&b'\n') && index + 1 < offset {
                    2
                } else {
                    1
                };
                line += 1;
                start = index;
            } else if source[index] == b'\n' {
                index += 1;
                line += 1;
                start = index;
            } else {
                index += 1;
            }
        }
        (line, offset - start + 1)
    }

    #[test]
    fn line_index_matches_the_previous_walk_at_every_offset() {
        let alphabet = *b"x\r\n";
        for length in 0..=7usize {
            let variants = 3usize.pow(length as u32);
            for mut variant in 0..variants {
                let mut source = Vec::with_capacity(length);
                for _ in 0..length {
                    source.push(alphabet[variant % alphabet.len()]);
                    variant /= alphabet.len();
                }
                let lines = LineIndex::new(&source);
                for offset in 0..=source.len() + 2 {
                    assert_eq!(
                        lines.line_column(offset),
                        linear_line_column(&source, offset),
                        "source={source:?}, offset={offset}"
                    );
                }
            }
        }
    }

    /// The frame around a hyperlink target is written in escape bytes, so a
    /// name carrying one of its own would close the frame early and be read as
    /// terminal instructions from there on. Nor may a URL carry the `%` that
    /// makes an encoding an encoding, the space that ends a URL, or the `#`
    /// that starts a fragment.
    #[test]
    fn a_hyperlink_target_encodes_every_byte_a_url_may_not_carry() {
        assert_eq!(
            percent_encode("/tmp/plain-file_name.rs~"),
            "/tmp/plain-file_name.rs~"
        );
        assert_eq!(percent_encode("/tmp/a b#c%d.rs"), "/tmp/a%20b%23c%25d.rs");
        assert_eq!(
            percent_encode("/tmp/evil\u{1b}[2Jname.rs"),
            "/tmp/evil%1B%5B2Jname.rs"
        );
        /* NOTE: A path is bytes, and one character is as many `%XX` pairs as it
         * takes to spell it. */
        assert_eq!(percent_encode("/tmp/\u{e9}.rs"), "/tmp/%C3%A9.rs");
    }

    /// A name is shown to be typed back, so its own spacing survives; what
    /// does not is anything that would drive the terminal or break the row.
    #[test]
    fn a_sanitized_path_keeps_its_spacing_and_loses_its_controls() {
        assert_eq!(sanitize_path(" lead.rs "), " lead.rs ");
        assert_eq!(sanitize_path("ta\tb.rs"), "ta\u{fffd}b.rs");
        assert_eq!(sanitize_path("two  spaces.rs"), "two  spaces.rs");
        assert_eq!(sanitize_path("a\nb\u{1b}c.rs"), "a\u{fffd}b\u{fffd}c.rs");
    }

    /// The reported path is read by a machine that has to find the file again:
    /// GitHub matches an annotation by `file=`, and a SARIF reader resolves
    /// `artifactLocation.uri` against the checkout. A Windows separator and a
    /// `.` segment both name a file no checkout has.
    #[test]
    fn report_path_spells_a_path_the_way_a_repository_does() {
        assert_eq!(report_path(Path::new("./a.rs")), "a.rs");
        assert_eq!(report_path(Path::new("sub/./doc.rs")), "sub/doc.rs");
        assert_eq!(report_path(Path::new("./sub/./doc.rs")), "sub/doc.rs");
        #[cfg(windows)]
        {
            assert_eq!(report_path(Path::new(r"sub\doc.rs")), "sub/doc.rs");
            assert_eq!(report_path(Path::new(r".\sub\.\doc.rs")), "sub/doc.rs");
        }
        #[cfg(unix)]
        {
            /* NOTE: On Unix a backslash is a filename byte, not a separator. */
            assert_eq!(report_path(Path::new(r"sub\doc.rs")), r"sub\doc.rs");
            assert_eq!(sarif_uri(Path::new(r"sub\doc.rs")), "sub%5Cdoc.rs");
        }
        /* NOTE: A path that leaves the tree, an absolute one, and standard input are
         * all left as they are; only the separators are normalised. */
        assert_eq!(report_path(Path::new("../sibling/a.rs")), "../sibling/a.rs");
        assert_eq!(report_path(Path::new("/tmp/a.rs")), "/tmp/a.rs");
        assert_eq!(report_path(Path::new(STDIN_PATH)), STDIN_PATH);
        // NOTE: Naming the working directory as nothing at all would be worse.
        assert_eq!(report_path(Path::new(".")), ".");
    }

    #[cfg(unix)]
    #[test]
    fn machine_path_encoders_preserve_raw_unix_bytes_without_sharing_syntax() {
        use std::{ffi::OsString, os::unix::ffi::OsStringExt};

        let path = PathBuf::from(OsString::from_vec(b"odd \xff,\n\x1b.rs".to_vec()));
        assert_eq!(sarif_uri(&path), "odd%20%FF%2C%0A%1B.rs");
        assert_eq!(github_path(&path), "odd %FF%2C%0A%1B.rs");
        assert!(!sarif_uri(&path).contains('\u{fffd}'));
        assert!(!github_path(&path).contains('\u{fffd}'));

        let raw_invalid = PathBuf::from(OsString::from_vec(b"odd \xff.rs".to_vec()));
        let literal_percent = Path::new("odd %FF.rs");
        assert_eq!(github_path(&raw_invalid), "odd %FF.rs");
        assert_eq!(github_path(literal_percent), "odd %25FF.rs");
        assert_ne!(github_path(literal_percent), github_path(&raw_invalid));
    }

    /// `%SRCROOT%` says the path is measured from the root of the checkout, so
    /// it is claimed only for the paths that are.
    #[test]
    fn only_a_path_inside_the_tree_is_reported_against_the_source_root() {
        for inside in ["a.rs", "sub/doc.rs", "./sub/doc.rs"] {
            assert_eq!(
                artifact_location(Path::new(inside))["uriBaseId"],
                json!(SRCROOT),
                "`{inside}` is not reported against the source root"
            );
        }
        for outside in ["../sibling/a.rs", "/tmp/a.rs", STDIN_PATH] {
            let location = artifact_location(Path::new(outside));
            assert_eq!(
                location.get("uriBaseId"),
                None,
                "`{outside}` claims to be under the source root"
            );
        }
    }

    /// A relative reference whose first segment holds a colon is read as a
    /// scheme, so a checkout that really does hold a directory named `c:` says
    /// so with the one `.` segment a URI keeps for the purpose. Nothing else
    /// gains one, and a path that is under no base is left exactly as it was.
    #[test]
    fn a_first_segment_that_reads_as_a_drive_letter_is_disambiguated() {
        let location = artifact_location(Path::new("c:/a.rs"));
        assert_eq!(location["uri"], json!("./c:/a.rs"));
        assert_eq!(location["uriBaseId"], json!(SRCROOT));
        assert_eq!(artifact_location(Path::new("c:"))["uri"], json!("./c:"));
        for plain in ["a.rs", "sub/doc.rs", "cc:/a.rs", "sub/c:/a.rs"] {
            assert_eq!(
                artifact_location(Path::new(plain))["uri"],
                json!(sarif_uri(Path::new(plain))),
                "`{plain}` was disambiguated and had no need of it"
            );
        }
        assert_eq!(
            artifact_location(Path::new("/tmp/c:/a.rs"))["uri"],
            json!("/tmp/c:/a.rs"),
            "a path under no base was rewritten"
        );
    }

    /// Every result points into the rules by index, so the two orders have to
    /// be the same one.
    #[test]
    fn a_rule_is_described_once_and_keeps_its_index() {
        let mut rules = SarifRules::new();
        assert_eq!(rules.entries.len(), CommentKind::ALL.len());
        assert_eq!(rules.kind(CommentKind::Line), 0);
        let first = rules.describe("io-error", "error", "short", "full", TOOL_INFORMATION_URI);
        assert_eq!(first, CommentKind::ALL.len());
        let again = rules.describe("io-error", "note", "other", "other", TOOL_INFORMATION_URI);
        assert_eq!(first, again, "a second sighting described the rule twice");
        assert_eq!(
            rules.entries[first]["defaultConfiguration"]["level"],
            "error"
        );
        assert_eq!(rules.entries.len(), CommentKind::ALL.len() + 1);
    }

    #[test]
    fn a_diagnostic_code_reads_back_as_a_title() {
        assert_eq!(
            sentence_case("unterminated-comment"),
            "Unterminated comment"
        );
        assert_eq!(sentence_case("nesting-limit"), "Nesting limit");
        assert_eq!(sentence_case(""), "");
    }

    fn preview_of(source: &[u8], max_columns: usize) -> String {
        preview(source, ByteSpan::new(0, source.len()), max_columns)
    }

    #[test]
    fn preview_collapses_every_run_of_whitespace_and_trims() {
        assert_eq!(
            preview_of(b"  /*\r\n\tkeep\t this  tidy \x0c*/  ", 72),
            "/* keep this tidy */"
        );
    }

    #[test]
    fn preview_truncates_on_display_width_without_splitting_a_wide_character() {
        let source = "ab漢字漢字漢字ab".as_bytes();
        assert_eq!(preview_of(source, 20), "ab漢字漢字漢字ab");
        let cut = preview_of(source, 10);
        assert_eq!(cut, "ab漢字漢…");
        assert!(cut.ends_with(''), "truncation is unmarked: {cut}");
        let width: usize = cut
            .chars()
            .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0))
            .sum();
        assert!(width <= 10, "`{cut}` is {width} columns wide");
    }

    #[test]
    fn preview_replaces_control_characters_with_the_replacement_character() {
        let source = b"// \x1b[31m\x07 \xc2\x9b\x7f bell";
        let rendered = preview_of(source, 72);
        assert_eq!(rendered, "// \u{fffd}[31m\u{fffd} \u{fffd}\u{fffd} bell");
        assert!(
            !rendered.contains('\x1b'),
            "an escape sequence survived: {rendered:?}"
        );
    }

    #[test]
    fn preview_replaces_invalid_utf8_bytes() {
        assert_eq!(
            preview_of(b"// \xff\xfe end", 72),
            "// \u{fffd}\u{fffd} end"
        );
    }

    /// Bidi overrides and isolates can make a comment render as its own
    /// reverse, and the line/paragraph separators break the one-line promise.
    #[test]
    fn preview_replaces_bidirectional_and_separator_controls() {
        let source = "// \u{202e}reverse\u{202c} \u{200e}\u{200f} \u{2066}iso\u{2069} \
                      \u{2028}\u{2029} \u{61c}\u{feff} end";
        assert_eq!(
            preview_of(source.as_bytes(), 72),
            "// \u{fffd}reverse\u{fffd} \u{fffd}\u{fffd} \u{fffd}iso\u{fffd} \
             \u{fffd}\u{fffd} \u{fffd}\u{fffd} end"
        );
        for character in [
            '\u{61c}', '\u{200e}', '\u{200f}', '\u{202a}', '\u{202b}', '\u{202c}', '\u{202d}',
            '\u{202e}', '\u{2066}', '\u{2067}', '\u{2068}', '\u{2069}', '\u{2028}', '\u{2029}',
            '\u{feff}',
        ] {
            assert!(
                is_control(character),
                "U+{:04X} still reaches the terminal",
                character as u32
            );
        }
    }

    /// Zero-width characters cost no display columns, so the width budget alone
    /// cannot bound the line; a hard character cap must.
    #[test]
    fn preview_caps_the_character_count_of_a_zero_width_run() {
        let source = format!("a{}", "\u{301}".repeat(1000));
        let rendered = preview_of(source.as_bytes(), 8);
        assert!(
            rendered.chars().count() <= 8 * 4,
            "preview is {} characters wide",
            rendered.chars().count()
        );
        assert!(rendered.ends_with('\u{2026}'), "truncation is unmarked");
    }

    /// A hunk is read as code, so the indentation that says what a line belongs
    /// to survives — but nothing that drives the terminal does, because the
    /// prompt asking about that line sits directly underneath it.
    #[test]
    fn a_source_line_keeps_its_shape_and_loses_its_control_characters() {
        assert_eq!(
            sanitize_source_line("    let x = 1; // note"),
            "    let x = 1; // note",
            "the indentation of a shown line was collapsed"
        );
        assert_eq!(
            sanitize_source_line("\tif (x) {"),
            "        if (x) {",
            "a tab did not reach its eight-column stop"
        );
        assert_eq!(
            sanitize_source_line("a\u{1b}[2Jb\u{202e}c"),
            "a\u{fffd}[2Jb\u{fffd}c",
            "an escape sequence reached the terminal verbatim"
        );
        let capped = sanitize_source_line(&"v".repeat(PREVIEW_COLUMNS * 3));
        let width: usize = capped
            .chars()
            .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0))
            .sum();
        assert!(
            width <= PREVIEW_COLUMNS,
            "a shown line ran to {width} columns and pushed the question off the screen"
        );
    }

    /// The interactive verdict counts answers, and every noun agrees with the
    /// number in front of it. It closes on the same `(N files scanned)` the
    /// plain `fix` summary ends with: the reader still has to be told how much
    /// was looked at to reach the answers.
    #[test]
    fn the_interactive_summary_pluralizes_both_of_its_nouns() {
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                removed: 1,
                reviewed: 1,
                offered: 1,
                changed: 1,
                scanned: 1,
            }),
            "Removed 1 of 1 comment in 1 file (1 file scanned)."
        );
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                removed: 2,
                reviewed: 5,
                offered: 5,
                changed: 3,
                scanned: 4,
            }),
            "Removed 2 of 5 comments in 3 files (4 files scanned)."
        );
    }

    /// A run that was never asked a question says so in the vocabulary the
    /// plain `fix` summary uses for the same answer, and counts the files it
    /// scanned — `Removed 0 of 0 comments in 0 files` named three numbers, none
    /// of which was the one the reader wanted.
    #[test]
    fn an_interactive_run_with_nothing_to_offer_borrows_the_fix_wording() {
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                scanned: 3,
                ..InteractiveOutcome::default()
            }),
            "Nothing to fix in 3 files."
        );
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                scanned: 1,
                ..InteractiveOutcome::default()
            }),
            "Nothing to fix in 1 file."
        );
    }

    /// `q` stops the questions, so the verdict counts the ones that were
    /// answered and says how many were left unasked. Reporting `1 of 9` to a
    /// reader who answered twice would read as seven refusals.
    #[test]
    fn a_stopped_interactive_run_counts_the_questions_it_asked() {
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                removed: 1,
                reviewed: 2,
                offered: 9,
                changed: 1,
                scanned: 4,
            }),
            "Removed 1 of 2 comments in 1 file (7 comments not reviewed) (4 files scanned)."
        );
        assert_eq!(
            interactive_summary(InteractiveOutcome {
                removed: 0,
                reviewed: 1,
                offered: 2,
                changed: 0,
                scanned: 1,
            }),
            "Removed 0 of 1 comment in 0 files (1 comment not reviewed) (1 file scanned)."
        );
    }

    /// What a probed tool says about itself gets the preview's treatment: one
    /// line, no control sequences, and no more of it than a preview shows.
    #[test]
    fn sanitize_line_replaces_controls_and_caps_the_width() {
        assert_eq!(
            sanitize_line("\u{1b}[2J\u{1b}[1;31mv1.0\tPWNED\u{1b}[0m"),
            "\u{fffd}[2J\u{fffd}[1;31mv1.0 PWNED\u{fffd}[0m"
        );
        let capped = sanitize_line(&"v".repeat(PREVIEW_COLUMNS * 3));
        let width: usize = capped
            .chars()
            .map(|ch| unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0))
            .sum();
        assert!(
            width <= PREVIEW_COLUMNS,
            "`{capped}` is {width} columns wide"
        );
        assert!(capped.ends_with('\u{2026}'), "truncation is unmarked");
    }

    #[test]
    fn preview_reads_only_the_span() {
        let source = b"let x = 1; // TODO remove\n";
        assert_eq!(preview(source, ByteSpan::new(11, 25), 72), "// TODO remove");
    }
}