cmakefmt-rust 1.0.0

A fast, correct CMake formatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
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
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
// SPDX-FileCopyrightText: Copyright 2026 Puneet Matharu
//
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::collections::BTreeSet;
use std::collections::HashMap;
use std::fmt::Write as _;
use std::hash::{Hash, Hasher};
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{mpsc, Arc};

use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use cmakefmt::spec::registry::CommandRegistry;
use cmakefmt::{
    convert_legacy_config_files, default_config_template_for,
    files::{discover_cmake_files_with_options, is_cmake_file, matches_filter, DiscoveryOptions},
    format_source_with_registry, format_source_with_registry_debug, generate_json_schema, parser,
    render_effective_config, CaseStyle, Config, DumpConfigFormat,
};
use indicatif::{ProgressBar, ProgressDrawTarget, ProgressStyle};
use regex::Regex;
use serde::{Deserialize, Serialize};
use similar::TextDiff;

const LONG_ABOUT: &str = "

Parse CMake listfiles and format them nicely.

Formatting is configurable with one or more YAML or TOML configuration files.
If no config file is specified on the command line, cmakefmt will try to find
the nearest .cmakefmt.yaml, .cmakefmt.yml, or .cmakefmt.toml for each input by
walking up through parent directories to the repository root or filesystem
root. If no project-local config exists, cmakefmt falls back to the same files
in the home directory when present.

Direct file arguments are always processed, even if ignore files would skip
them during recursive discovery. Ignore rules only affect files discovered
from directories, --files-from, or Git-aware selection modes.

Use `cmakefmt init` to generate a starter .cmakefmt.yaml, or
`cmakefmt config dump` to print the full default template.

Legacy cmake-format config files can be converted with
`cmakefmt config convert <path>`.

Use `cmakefmt config path` to inspect which config file was selected,
`cmakefmt config show` for the effective config, and `cmakefmt config explain`
for a human-readable explanation of config resolution.";

fn cli_styles() -> clap::builder::Styles {
    use clap::builder::styling::{AnsiColor, Effects, Style};
    clap::builder::Styles::styled()
        .header(
            Style::new()
                .fg_color(Some(AnsiColor::Green.into()))
                .effects(Effects::BOLD),
        )
        .usage(
            Style::new()
                .fg_color(Some(AnsiColor::Green.into()))
                .effects(Effects::BOLD),
        )
        .literal(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
        .placeholder(Style::new().fg_color(Some(AnsiColor::Cyan.into())))
        .valid(Style::new().fg_color(Some(AnsiColor::Green.into())))
        .invalid(
            Style::new()
                .fg_color(Some(AnsiColor::Red.into()))
                .effects(Effects::BOLD),
        )
        .error(
            Style::new()
                .fg_color(Some(AnsiColor::Red.into()))
                .effects(Effects::BOLD),
        )
}

/// A fast, correct CMake formatter.
#[derive(Parser, Debug)]
#[command(
    name = "cmakefmt",
    version,
    long_version = env!("CMAKEFMT_CLI_LONG_VERSION"),
    about = "Parse CMake listfiles and format them nicely.",
    long_about = LONG_ABOUT,
    styles = cli_styles(),
)]
struct Cli {
    /// Files or directories to format. Use `-` for stdin.
    ///
    /// If omitted, `cmakefmt` recursively finds CMake files under the current
    /// working directory.
    files: Vec<String>,

    /// Read more formatting targets from a file, or `-` for stdin.
    ///
    /// Accepts newline-delimited or NUL-delimited path lists. This is useful
    /// for scripted workflows that already know which files to pass to
    /// `cmakefmt`.
    #[arg(
        long = "files-from",
        value_name = "PATH",
        help_heading = "Input Selection"
    )]
    files_from: Vec<String>,

    /// Rewrite files on disk instead of printing formatted output.
    ///
    /// Semantic verification is enabled by default for in-place rewrites.
    /// Use `--fast` to skip it.
    #[arg(
        short = 'i',
        long = "in-place",
        help_heading = "Output Modes",
        conflicts_with = "list_changed_files",
        conflicts_with = "list_input_files"
    )]
    in_place: bool,

    /// Exit with code 1 if any selected file would change.
    ///
    /// No files are modified on disk.
    #[arg(
        long,
        help_heading = "Output Modes",
        conflicts_with = "list_input_files"
    )]
    check: bool,

    /// Print only the files that would change, without modifying them.
    #[arg(
        long = "list-changed-files",
        alias = "list-files",
        help_heading = "Output Modes",
        conflicts_with = "quiet",
        conflicts_with = "list_input_files"
    )]
    list_changed_files: bool,

    /// Print the selected input files after discovery/filtering, without formatting them.
    #[arg(
        long = "list-input-files",
        help_heading = "Output Modes",
        conflicts_with = "check",
        conflicts_with = "list_changed_files",
        conflicts_with = "in_place",
        conflicts_with = "diff",
        conflicts_with = "quiet"
    )]
    list_input_files: bool,

    /// List commands that don't match any built-in or user-defined spec.
    ///
    /// Parses the selected files and prints each unrecognized command name
    /// with its file and line number. Useful for discovering project-specific
    /// commands that should be added to the `commands:` config section.
    #[arg(
        long = "list-unknown-commands",
        help_heading = "Output Modes",
        conflicts_with = "check",
        conflicts_with = "in_place",
        conflicts_with = "diff",
        conflicts_with = "list_changed_files",
        conflicts_with = "list_input_files",
        conflicts_with = "explain",
        conflicts_with = "watch",
        conflicts_with = "quiet",
        conflicts_with = "progress_bar"
    )]
    list_unknown_commands: bool,

    /// Filter recursively discovered CMake paths with a regex.
    ///
    /// This only affects discovery from directories or Git/file-list driven
    /// inputs. Direct file arguments are always kept.
    #[arg(
        long = "path-regex",
        value_name = "REGEX",
        help_heading = "Input Selection"
    )]
    file_regex: Option<String>,

    /// Add one or more extra ignore files during recursive discovery.
    ///
    /// This only affects discovered files, not direct file arguments.
    #[arg(
        long = "ignore-path",
        value_name = "PATH",
        help_heading = "Input Selection"
    )]
    ignore_paths: Vec<PathBuf>,

    /// Ignore `.gitignore` files during recursive discovery.
    ///
    /// By default, cmakefmt honours `.gitignore` rules when discovering
    /// files from directories.
    #[arg(long = "no-gitignore", help_heading = "Input Selection")]
    no_gitignore: bool,

    /// Sort discovered files by path before processing.
    ///
    /// Guarantees alphabetical output order regardless of filesystem
    /// discovery order. Direct file arguments are sorted too.
    #[arg(long, help_heading = "Input Selection")]
    sorted: bool,

    /// Generate a roff man page and print it to stdout.
    #[arg(long = "generate-man-page", help_heading = "Release And Packaging")]
    generate_man_page: bool,

    /// Print detailed discovery, config, and formatter diagnostics to stderr.
    #[arg(long, help_heading = "Execution")]
    debug: bool,

    /// Show a per-file status summary instead of formatted output.
    ///
    /// Prints a status line for each file to stderr with change details,
    /// line counts, and elapsed time. In stdout mode (no `--check`,
    /// `--in-place`, or `--diff`), formatted output is suppressed.
    #[arg(short, long, help_heading = "Output Modes", conflicts_with = "quiet")]
    summary: bool,

    /// Suppress per-file output and emit only end-of-run summaries.
    ///
    /// In stdout mode, formatted output is suppressed. In `--check` mode,
    /// "would be reformatted" lines are suppressed. Errors and the summary
    /// line are always printed.
    #[arg(short, long, help_heading = "Execution")]
    quiet: bool,

    /// Print a git-style summary after formatting (e.g. "3 files changed, 12 lines reformatted").
    ///
    /// This works with all output modes (`--check`, `--diff`, `--in-place`, and
    /// stdout). When combined with `--quiet`, the stat line is still printed.
    #[arg(long, help_heading = "Execution")]
    stat: bool,

    /// Continue processing other files after a file-level parse or format error.
    ///
    /// Without this flag, human runs still fail at the first file error.
    #[arg(long = "keep-going", help_heading = "Execution")]
    keep_going: bool,

    /// Print a unified diff instead of the full formatted output.
    #[arg(
        short,
        long,
        help_heading = "Output Modes",
        conflicts_with = "in_place"
    )]
    diff: bool,

    /// Show why each command was formatted the way it was.
    ///
    /// Prints a per-command explanation of the layout decision (inline,
    /// hanging, or vertical) and the config values that influenced it.
    /// Requires exactly one formatting target.
    #[arg(
        long,
        help_heading = "Output Modes",
        conflicts_with = "check",
        conflicts_with = "in_place",
        conflicts_with = "diff",
        conflicts_with = "list_changed_files",
        conflicts_with = "list_input_files",
        conflicts_with = "quiet",
        conflicts_with = "progress_bar"
    )]
    explain: bool,

    /// Watch for file changes and reformat automatically.
    ///
    /// Watches the specified files or directories for changes and reformats
    /// them in-place. Press Ctrl+C to stop.
    #[arg(
        long,
        help_heading = "Execution",
        conflicts_with = "check",
        conflicts_with = "diff",
        conflicts_with = "list_changed_files",
        conflicts_with = "list_input_files",
        conflicts_with = "quiet",
        conflicts_with = "explain",
        conflicts_with = "progress_bar"
    )]
    watch: bool,

    /// Cache formatted results for repeated runs on the same files.
    ///
    /// Speeds up large-repo checks by skipping files that haven't changed.
    #[arg(long, help_heading = "Execution")]
    cache: bool,

    /// Override the cache directory used by `--cache`.
    ///
    /// Supplying a cache location also enables caching.
    #[arg(
        long = "cache-location",
        value_name = "PATH",
        help_heading = "Execution"
    )]
    cache_location: Option<PathBuf>,

    /// Choose whether cache invalidation tracks file metadata or file contents.
    #[arg(
        long = "cache-strategy",
        value_enum,
        default_value_t = CacheStrategy::Metadata,
        help_heading = "Execution"
    )]
    cache_strategy: CacheStrategy,

    /// Select modified Git-tracked files instead of explicit input paths.
    ///
    /// Use `--since` to compare against a specific base ref; otherwise
    /// `cmakefmt` compares the working tree against `HEAD`.
    #[arg(long, help_heading = "Input Selection", conflicts_with = "staged")]
    changed: bool,

    /// Select staged Git-tracked files instead of explicit input paths.
    ///
    /// Useful for pre-commit hooks that should only check files in the
    /// current changeset.
    #[arg(long, help_heading = "Input Selection", conflicts_with = "changed")]
    staged: bool,

    /// Git base ref used together with `--changed`.
    ///
    /// Without this flag, `--changed` compares against `HEAD`.
    #[arg(
        long,
        requires = "changed",
        value_name = "REF",
        help_heading = "Input Selection"
    )]
    since: Option<String>,

    /// Virtual path used for config discovery and diagnostics when reading stdin.
    ///
    /// This does not read from disk; it only gives stdin formatting a real
    /// project-relative path to work from.
    #[arg(
        long = "stdin-path",
        value_name = "PATH",
        help_heading = "Input Selection"
    )]
    stdin_path: Option<PathBuf>,

    /// Restrict formatting to one or more 1-based inclusive line ranges.
    ///
    /// This is intended for editor integrations and only works on a single
    /// formatting target.
    #[arg(
        long = "lines",
        value_name = "START:END",
        help_heading = "Input Selection"
    )]
    line_ranges: Vec<LineRange>,

    /// Choose the output report format.
    #[arg(
        long = "report-format",
        value_enum,
        default_value_t = ReportFormat::Human,
        help_heading = "Output Modes"
    )]
    report_format: ReportFormat,

    /// Control ANSI color output.
    #[arg(
        long = "color",
        alias = "colour",
        value_enum,
        default_value_t = ColorChoice::Auto,
        help_heading = "Output Modes"
    )]
    color: ColorChoice,

    /// Set the number of parallel formatting jobs.
    ///
    /// Defaults to the available CPU count minus one (minimum 1). Pass an
    /// explicit value to override, or `--parallel 1` to force serial.
    #[arg(
        short = 'j',
        long,
        value_name = "JOBS",
        help_heading = "Execution",
        num_args = 0..=1,
        default_missing_value = "0",
    )]
    parallel: Option<usize>,

    /// Show a progress bar on stderr while processing files.
    ///
    /// The progress bar is intended for directory or multi-file runs.
    #[arg(short, long = "progress-bar", help_heading = "Execution")]
    progress_bar: bool,

    /// Use one or more explicit config files instead of config discovery.
    ///
    /// Later files override earlier ones.
    #[arg(
        short = 'c',
        long = "config-file",
        visible_alias = "config",
        value_name = "PATH",
        help_heading = "Config Overrides"
    )]
    config_paths: Vec<PathBuf>,

    /// Disable config discovery and ignore explicit config files.
    ///
    /// Only built-in defaults and CLI overrides remain.
    #[arg(long, help_heading = "Config Overrides")]
    no_config: bool,

    /// Disable `.editorconfig` fallback.
    ///
    /// By default, when no `.cmakefmt.yaml` config file is found, cmakefmt
    /// reads `indent_style` and `indent_size` from `.editorconfig`. This
    /// flag disables that fallback.
    #[arg(long = "no-editorconfig", help_heading = "Config Overrides")]
    no_editorconfig: bool,

    /// Override the maximum line width.
    #[arg(short = 'l', long, help_heading = "Config Overrides")]
    line_width: Option<usize>,

    /// Override the number of spaces per indent level.
    #[arg(long, help_heading = "Config Overrides")]
    tab_size: Option<usize>,

    /// Normalise command name case (lower, upper, unchanged).
    #[arg(long, help_heading = "Config Overrides")]
    command_case: Option<CaseStyle>,

    /// Normalise keyword case (lower, upper, unchanged).
    #[arg(long, help_heading = "Config Overrides")]
    keyword_case: Option<CaseStyle>,

    /// Place closing paren on its own line when wrapping.
    #[arg(long, help_heading = "Config Overrides")]
    dangle_parens: Option<bool>,

    /// Refuse to run unless the current cmakefmt version matches exactly.
    ///
    /// Useful for pinned CI and editor wrappers that need a specific version.
    #[arg(long, value_name = "VERSION", help_heading = "Execution")]
    required_version: Option<String>,

    /// Verify that formatting preserves the parsed CMake semantics.
    ///
    /// In-place rewrites verify semantics by default; use this flag to enable
    /// the same safety check in stdout, diff, and check modes.
    #[arg(long, help_heading = "Execution", conflicts_with = "no_verify")]
    verify: bool,

    /// Skip semantic verification, even for in-place rewrites.
    ///
    /// Improves throughput on trusted inputs at the cost of safety.
    #[arg(
        long = "no-verify",
        visible_alias = "fast",
        help_heading = "Execution",
        conflicts_with = "verify"
    )]
    no_verify: bool,

    /// Enable all experimental formatting options.
    ///
    /// Equivalent to setting every option in the `[experimental]` config
    /// section. Experimental options are unstable and may change between
    /// releases.
    #[arg(long, help_heading = "Execution")]
    preview: bool,

    /// Format only files that opt in with a `# cmakefmt: enable` style pragma.
    ///
    /// Useful for gradually rolling out formatting across a large codebase.
    #[arg(long, help_heading = "Execution")]
    require_pragma: bool,

    /// Subcommand (e.g. `cmakefmt config dump`).
    #[command(subcommand)]
    command: Option<CliCommand>,
}

#[derive(Clone, Debug, Subcommand)]
enum CliCommand {
    /// Start the cmakefmt LSP server (reads/writes JSON-RPC on stdio).
    Lsp,
    /// Generate shell completion scripts and print them to stdout.
    Completions {
        /// The shell to generate completions for.
        #[arg(value_enum)]
        shell: Shell,
    },
    /// Install a git pre-commit hook that runs `cmakefmt --check` on staged
    /// CMake files.
    InstallHook,
    /// Config inspection, generation, and conversion.
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Dump internal representations (AST, parse tree) for debugging.
    Dump {
        #[command(subcommand)]
        action: DumpAction,

        /// Input file to dump (reads stdin if omitted).
        #[arg(global = true)]
        file: Option<PathBuf>,
    },
}

#[derive(Clone, Debug, Subcommand)]
enum ConfigAction {
    /// Print the default config template.
    Dump {
        /// Output format.
        #[arg(long, value_enum, default_value = "yaml")]
        format: DumpConfigFormat,
    },
    /// Print the JSON Schema for the config file.
    Schema,
    /// Validate a config file without formatting.
    Check {
        /// Config file to validate (discovers automatically if omitted).
        path: Option<String>,
    },
    /// Print the effective config for a target.
    Show {
        /// Target file for config resolution.
        path: Option<String>,
        /// Output format.
        #[arg(long, value_enum, default_value = "yaml")]
        format: DumpConfigFormat,
    },
    /// Print the config file path selected for a target.
    Path {
        /// Target file for config resolution.
        path: Option<String>,
    },
    /// Explain config resolution for a target or the current directory.
    Explain {
        /// Target file for config resolution.
        path: Option<String>,
    },
    /// Convert legacy cmake-format config files.
    Convert {
        /// Legacy config file(s) to convert.
        paths: Vec<PathBuf>,
        /// Output format.
        #[arg(long, value_enum, default_value = "yaml")]
        format: DumpConfigFormat,
    },
    /// Write a starter `.cmakefmt.yaml` to the current directory.
    Init,
}

#[derive(Clone, Debug, Subcommand)]
enum DumpAction {
    /// Print the raw parser AST as a tree.
    Ast,
    /// Print the formatted parse tree (not yet implemented).
    Parse,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum ColorChoice {
    /// Use colour only when stdout looks like an interactive terminal.
    Auto,
    /// Always emit ANSI colour codes.
    Always,
    /// Never emit ANSI colour codes.
    Never,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum ReportFormat {
    /// Human-friendly terminal output.
    Human,
    /// Machine-readable JSON output.
    Json,
    /// GitHub Actions workflow commands.
    Github,
    /// Checkstyle XML.
    Checkstyle,
    /// JUnit XML.
    Junit,
    /// SARIF JSON.
    Sarif,
    /// Editor-friendly JSON with byte-range replacements.
    Edit,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
enum CacheStrategy {
    /// Use file size and modification time to detect cache invalidation.
    Metadata,
    /// Hash file contents to detect cache invalidation.
    Content,
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct LineRange {
    start: usize,
    end: usize,
}

impl LineRange {
    fn contains(&self, line: usize) -> bool {
        self.start <= line && line <= self.end
    }
}

impl FromStr for LineRange {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let Some((start, end)) = value.split_once(':') else {
            return Err("expected START:END".to_owned());
        };
        let start = start
            .parse::<usize>()
            .map_err(|_| "line range start must be a positive integer".to_owned())?;
        let end = end
            .parse::<usize>()
            .map_err(|_| "line range end must be a positive integer".to_owned())?;
        if start == 0 || end == 0 {
            return Err("line ranges are 1-based".to_owned());
        }
        if end < start {
            return Err("line range end must be >= start".to_owned());
        }
        Ok(Self { start, end })
    }
}

/// Exit codes matching the spec in ARCHITECTURE.md.
const EXIT_OK: u8 = 0;
const EXIT_CHECK_FAILED: u8 = 1;
const EXIT_ERROR: u8 = 2;

fn main() -> ExitCode {
    std::panic::set_hook(Box::new(|info| {
        let message = if let Some(s) = info.payload().downcast_ref::<&str>() {
            (*s).to_string()
        } else if let Some(s) = info.payload().downcast_ref::<String>() {
            s.clone()
        } else {
            "unknown".to_string()
        };

        let location = info
            .location()
            .map(|l| format!("{}:{}", l.file(), l.line()))
            .unwrap_or_else(|| "unknown".to_string());

        eprintln!(
            "\
cmakefmt encountered an internal error and crashed.

This is a bug. Please report it at:
  https://github.com/cmakefmt/cmakefmt/issues/new

Include the following in your report:
  cmakefmt version: {}
  OS: {} ({})
  panic: {}
  location: {}",
            env!("CARGO_PKG_VERSION"),
            std::env::consts::OS,
            std::env::consts::ARCH,
            message,
            location,
        );
    }));

    let cli = Cli::parse();

    match run(&cli) {
        Ok(code) => ExitCode::from(code),
        Err(cmakefmt::Error::Io(ref e)) if e.kind() == std::io::ErrorKind::BrokenPipe => {
            ExitCode::from(EXIT_OK)
        }
        Err(err) => {
            eprintln!("{}", render_cli_error(&err));
            ExitCode::from(EXIT_ERROR)
        }
    }
}

fn run(cli: &Cli) -> Result<u8, cmakefmt::Error> {
    check_required_version(cli)?;

    match &cli.command {
        #[cfg(feature = "lsp")]
        Some(CliCommand::Lsp) => {
            cmakefmt::lsp::run().map_err(|e| cmakefmt::Error::Formatter(e.to_string()))?;
            return Ok(EXIT_OK);
        }
        Some(CliCommand::Completions { shell }) => {
            let mut command = Cli::command();
            generate(*shell, &mut command, "cmakefmt", &mut io::stdout());
            return Ok(EXIT_OK);
        }
        Some(CliCommand::InstallHook) => {
            return install_git_hook();
        }
        Some(CliCommand::Config { action }) => {
            return run_config_subcommand(cli, action);
        }
        Some(CliCommand::Dump { action, file }) => {
            return run_dump_subcommand(cli, action, file.as_deref());
        }
        None => {}
    }

    if cli.generate_man_page {
        let command = Cli::command();
        clap_mangen::Man::new(command)
            .render(&mut io::stdout())
            .map_err(cmakefmt::Error::Io)?;
        return Ok(EXIT_OK);
    }

    validate_cli(cli)?;

    let stdout_mode = is_stdout_mode(cli);
    let colorize_stdout = stdout_mode && should_colorize_stdout(cli.color);
    let file_filter = compile_file_filter(cli.file_regex.as_deref())?;
    let mut targets = collect_targets(cli, file_filter.as_ref())?;
    if cli.sorted {
        targets.sort_by(|a, b| {
            a.display_name(cli.stdin_path.as_deref())
                .cmp(&b.display_name(cli.stdin_path.as_deref()))
        });
    }
    if cli.list_input_files {
        for target in &targets {
            println!("{}", target.display_name(cli.stdin_path.as_deref()));
        }
        return Ok(EXIT_OK);
    }
    if cli.list_unknown_commands {
        return run_list_unknown_commands(cli, &targets);
    }
    if cli.explain && targets.len() != 1 {
        return Err(cmakefmt::Error::Formatter(
            "--explain requires exactly one formatting target".to_owned(),
        ));
    }
    if cli.watch {
        return run_watch(cli, &targets, file_filter.as_ref());
    }
    if !cli.line_ranges.is_empty() && targets.len() != 1 {
        return Err(cmakefmt::Error::Formatter(
            "--lines requires exactly one formatting target".to_owned(),
        ));
    }
    let parallel_jobs = resolve_parallel_jobs(cli.parallel)?;
    let stdout_is_terminal = io::stdout().is_terminal();
    let stderr_is_terminal = io::stderr().is_terminal();
    let colorize_stderr = should_colorize_stderr(cli.color);

    if let Some(reason) =
        progress_bar_suppressed_reason(cli, targets.len(), stdout_is_terminal, stderr_is_terminal)
    {
        if colorize_stderr {
            eprintln!("\n\x1b[1;93mâš  warning: --progress-bar ignored ({reason})\x1b[0m\n");
        } else {
            eprintln!("\nwarning: --progress-bar ignored ({reason})\n");
        }
    }
    let progress = ProgressReporter::new(
        should_enable_progress_bar(cli, targets.len(), stdout_is_terminal, stderr_is_terminal),
        targets.len(),
    );

    if cli.debug {
        log_debug(format!(
            "discovered {} target(s){}",
            targets.len(),
            debug_parallel_suffix(parallel_jobs)
        ));
    }

    let start_time = std::time::Instant::now();
    let mut state = RunState {
        results: Vec::new(),
        failures: Vec::new(),
        summary: RunSummary {
            selected: targets.len(),
            ..RunSummary::default()
        },
        human_output: HumanOutputState::new(stdout_mode && targets.len() > 1),
    };

    process_targets(
        &targets,
        cli,
        parallel_jobs,
        colorize_stdout,
        &progress,
        |target_result| {
            handle_completed_target(
                target_result,
                cli,
                colorize_stdout,
                colorize_stderr,
                &progress,
                &mut state,
            )
        },
    )?;
    state.summary.elapsed = start_time.elapsed();
    let RunState {
        results,
        failures,
        summary,
        ..
    } = state;

    if cli.in_place {
        write_in_place_updates(&results)?;
    }

    if cli.report_format != ReportFormat::Human {
        // Emit the unified diff for report formats that don't embed it in
        // their structured output. GitHub annotations are line-prefixed and
        // coexist safely with diff text; JSON/Checkstyle/JUnit/SARIF would
        // be corrupted by raw text prepended to the structured output.
        if cli.diff && cli.report_format == ReportFormat::Github {
            for result in &results {
                if result.would_change {
                    write_diff_to_stdout(result, colorize_stdout)?;
                }
            }
        }
        print_non_human_report(cli, &results, &failures, &summary)?;
        return machine_mode_exit_code(&results, &failures, &summary, cli);
    }

    if should_print_human_summary(cli, &summary, &failures, results.len()) {
        progress.eprintln(&render_human_summary(&summary))?;
    }

    if cli.stat {
        progress.eprintln(&render_stat_summary(&summary))?;
    }

    if cli.check && !cli.quiet && summary.changed > 0 && cli.report_format == ReportFormat::Human {
        progress.eprintln("hint: run `cmakefmt --in-place .` to fix formatting")?;
    }

    if !failures.is_empty() {
        Ok(EXIT_ERROR)
    } else if (cli.check || cli.list_changed_files) && summary.changed > 0 {
        Ok(EXIT_CHECK_FAILED)
    } else {
        Ok(EXIT_OK)
    }
}

fn run_list_unknown_commands(cli: &Cli, targets: &[InputTarget]) -> Result<u8, cmakefmt::Error> {
    use cmakefmt::parser;
    use std::collections::BTreeMap;

    // command_name -> vec of (file, line)
    let mut unknown: BTreeMap<String, Vec<(String, usize)>> = BTreeMap::new();

    for target in targets {
        let (display_name, source) = match target {
            InputTarget::Stdin => {
                let mut buf = String::new();
                io::Read::read_to_string(&mut io::stdin(), &mut buf)
                    .map_err(cmakefmt::Error::Io)?;
                ("<stdin>".to_owned(), buf)
            }
            InputTarget::Path(path) => {
                let source = std::fs::read_to_string(path).map_err(cmakefmt::Error::Io)?;
                (path.display().to_string(), source)
            }
        };

        let (_, registry, _) = build_context(
            cli,
            match target {
                InputTarget::Path(p) => Some(p.as_path()),
                InputTarget::Stdin => cli.stdin_path.as_deref().map(Path::new),
            },
        )?;

        let file = match parser::parse(&source) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("warning: {display_name}: parse error, skipping ({e})");
                continue;
            }
        };

        for statement in &file.statements {
            if let parser::ast::Statement::Command(command) = statement {
                if !registry.contains(&command.name) {
                    let line = source[..command.span.0]
                        .chars()
                        .filter(|&c| c == '\n')
                        .count()
                        + 1;
                    unknown
                        .entry(command.name.to_ascii_lowercase())
                        .or_default()
                        .push((display_name.clone(), line));
                }
            }
        }
    }

    if unknown.is_empty() {
        eprintln!("No unknown commands found.");
        return Ok(EXIT_OK);
    }

    for (name, locations) in &unknown {
        println!("{name}");
        for (file, line) in locations {
            println!("  {file}:{line}");
        }
    }

    Ok(EXIT_OK)
}

fn run_watch(
    cli: &Cli,
    initial_targets: &[InputTarget],
    file_filter: Option<&Regex>,
) -> Result<u8, cmakefmt::Error> {
    use notify_debouncer_mini::{new_debouncer, DebouncedEventKind};
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;
    use std::time::Duration;

    let colorize_stderr = should_colorize_stderr(cli.color);

    // Collect directories to watch from the initial targets.
    let mut watch_roots = Vec::new();
    for target in initial_targets {
        match target {
            InputTarget::Path(path) => {
                if path.is_dir() {
                    watch_roots.push(path.clone());
                } else if let Some(parent) = path.parent() {
                    watch_roots.push(parent.to_path_buf());
                }
            }
            InputTarget::Stdin => {}
        }
    }
    if watch_roots.is_empty() {
        watch_roots.push(std::env::current_dir().map_err(cmakefmt::Error::Io)?);
    }

    let shutdown = Arc::new(AtomicBool::new(false));
    let shutdown_clone = shutdown.clone();
    ctrlc::set_handler(move || {
        shutdown_clone.store(true, Ordering::Relaxed);
    })
    .map_err(|e| cmakefmt::Error::Formatter(format!("failed to set Ctrl+C handler: {e}")))?;

    let (tx, rx) = std::sync::mpsc::channel();
    let mut debouncer = new_debouncer(Duration::from_millis(300), tx)
        .map_err(|e| cmakefmt::Error::Formatter(format!("failed to create file watcher: {e}")))?;

    for root in &watch_roots {
        debouncer
            .watcher()
            .watch(root, notify::RecursiveMode::Recursive)
            .map_err(|e| {
                cmakefmt::Error::Formatter(format!("failed to watch {}: {e}", root.display()))
            })?;
    }

    eprintln!(
        "watching {} for changes (Ctrl+C to stop)...",
        watch_roots
            .iter()
            .map(|r| r.display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );

    while !shutdown.load(Ordering::Relaxed) {
        let events = match rx.recv_timeout(Duration::from_millis(500)) {
            Ok(Ok(events)) => events,
            Ok(Err(err)) => {
                eprintln!("watch error: {err}");
                continue;
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
        };

        let mut formatted_paths = BTreeSet::new();
        for event in &events {
            if !matches!(event.kind, DebouncedEventKind::Any) {
                continue;
            }
            let path = &event.path;
            if !path.is_file() || !cmakefmt::files::is_cmake_file(path) {
                continue;
            }
            if let Some(filter) = file_filter {
                if !filter.is_match(&path.display().to_string()) {
                    continue;
                }
            }
            if formatted_paths.contains(path) {
                continue;
            }
            formatted_paths.insert(path.clone());

            match watch_format_file(cli, path, colorize_stderr) {
                Ok(msg) => eprintln!("{msg}"),
                Err(e) => eprintln!("error: {}: {e}", path.display()),
            }
        }
    }

    eprintln!("stopped.");
    Ok(EXIT_OK)
}

fn watch_format_file(cli: &Cli, path: &Path, colorize: bool) -> Result<String, cmakefmt::Error> {
    let source = std::fs::read_to_string(path).map_err(cmakefmt::Error::Io)?;
    let (config, registry, _) = build_context(cli, Some(path))?;
    let formatted = format_source_with_registry(&source, &config, &registry)
        .map_err(|e| e.with_display_name(path.display().to_string()))?;

    let would_change = formatted != source;
    if would_change {
        atomic_write(path, &formatted)?;
        if colorize {
            Ok(format!("\x1b[1;93m!\x1b[0m {}", path.display()))
        } else {
            Ok(format!("[!] {}", path.display()))
        }
    } else if colorize {
        Ok(format!(
            "\x1b[1;32m✔\x1b[0m \x1b[2m{}\x1b[0m",
            path.display()
        ))
    } else {
        Ok(format!("[ok] {}", path.display()))
    }
}

fn is_stdout_mode(cli: &Cli) -> bool {
    !cli.list_changed_files && !cli.list_input_files && !cli.check && !cli.in_place
}

fn needs_debug_lines(cli: &Cli) -> bool {
    cli.debug || cli.explain
}

fn streams_stdout_during_run(cli: &Cli) -> bool {
    if cli.report_format != ReportFormat::Human {
        return false;
    }

    if cli.list_changed_files || cli.diff {
        return true;
    }

    is_stdout_mode(cli) && !cli.summary && !cli.quiet
}

fn should_enable_progress_bar(
    cli: &Cli,
    total: usize,
    stdout_is_terminal: bool,
    stderr_is_terminal: bool,
) -> bool {
    cli.progress_bar
        && total > 1
        && stderr_is_terminal
        && (!streams_stdout_during_run(cli) || !stdout_is_terminal)
}

/// Returns a human-readable reason if the progress bar was requested but
/// suppressed, or `None` if it was enabled (or not requested).
fn progress_bar_suppressed_reason(
    cli: &Cli,
    total: usize,
    stdout_is_terminal: bool,
    stderr_is_terminal: bool,
) -> Option<&'static str> {
    if !cli.progress_bar
        || should_enable_progress_bar(cli, total, stdout_is_terminal, stderr_is_terminal)
    {
        return None;
    }
    if !stderr_is_terminal {
        Some("stderr is not a terminal")
    } else if total <= 1 {
        Some("only one file to process")
    } else {
        Some("output is streaming to the terminal; pipe stdout to enable")
    }
}

struct RunState {
    results: Vec<ProcessedTarget>,
    failures: Vec<FailedTarget>,
    summary: RunSummary,
    human_output: HumanOutputState,
}

struct HumanOutputState {
    multi_target_stdout: bool,
    wrote_stdout_block: bool,
}

impl HumanOutputState {
    fn new(multi_target_stdout: bool) -> Self {
        Self {
            multi_target_stdout,
            wrote_stdout_block: false,
        }
    }
}

fn process_targets<F>(
    targets: &[InputTarget],
    cli: &Cli,
    parallel_jobs: usize,
    colorize_stdout: bool,
    progress: &ProgressReporter,
    mut on_result: F,
) -> Result<(), cmakefmt::Error>
where
    F: FnMut(Result<ProcessedTarget, cmakefmt::Error>) -> Result<(), cmakefmt::Error>,
{
    if parallel_jobs > 1 && targets.iter().all(InputTarget::is_path) {
        process_targets_parallel(
            targets,
            cli,
            parallel_jobs,
            colorize_stdout,
            progress,
            &mut on_result,
        )
    } else {
        if cli.debug && parallel_jobs > 1 && targets.iter().any(|target| !target.is_path()) {
            log_debug("parallel mode ignored because stdin input must run serially");
        }
        process_targets_serial(targets, cli, colorize_stdout, progress, &mut on_result)
    }
}

fn handle_completed_target(
    target_result: Result<ProcessedTarget, cmakefmt::Error>,
    cli: &Cli,
    colorize_stdout: bool,
    colorize_stderr: bool,
    progress: &ProgressReporter,
    state: &mut RunState,
) -> Result<(), cmakefmt::Error> {
    match target_result {
        Ok(result) => {
            if result.skipped {
                state.summary.skipped += 1;
            } else if result.would_change {
                state.summary.changed += 1;
                state.summary.total_changed_lines += result.changed_lines.len();
            } else {
                state.summary.unchanged += 1;
            }

            if cli.summary && cli.report_format == ReportFormat::Human {
                progress.eprintln(&render_summary_line(&result, colorize_stderr))?;
            }

            if cli.report_format == ReportFormat::Human {
                emit_human_result(
                    &result,
                    cli,
                    colorize_stdout,
                    progress,
                    &mut state.human_output,
                )?;
            }

            state.results.push(result);
            Ok(())
        }
        Err(err) => {
            if !cli.keep_going {
                return Err(err);
            }

            state.summary.failed += 1;
            let failure = FailedTarget {
                display_name: error_display_name(&err),
                rendered_error: render_cli_error(&err),
            };

            if cli.summary && cli.report_format == ReportFormat::Human {
                progress.eprintln(&render_summary_failed_line(
                    &failure.display_name,
                    colorize_stderr,
                ))?;
            }

            if cli.report_format == ReportFormat::Human {
                emit_human_failure(&failure, progress)?;
            }

            state.failures.push(failure);
            Ok(())
        }
    }
}

fn emit_human_result(
    result: &ProcessedTarget,
    cli: &Cli,
    colorize_stdout: bool,
    progress: &ProgressReporter,
    human_output: &mut HumanOutputState,
) -> Result<(), cmakefmt::Error> {
    if cli.debug {
        for line in &result.debug_lines {
            progress.eprintln(&format!("debug: {line}"))?;
        }
    }

    if cli.explain {
        render_explain_output(result, progress)?;
        return Ok(());
    }

    if result.skipped {
        if is_stdout_mode(cli) && !cli.quiet && !cli.summary {
            write_stdout_result(result, colorize_stdout, human_output)?;
        }
        return Ok(());
    }

    if cli.list_changed_files {
        if result.would_change {
            writeln!(io::stdout(), "{}", result.display_name).map_err(cmakefmt::Error::Io)?;
            flush_stdout()?;
        }
        return Ok(());
    }

    if cli.check {
        if result.would_change {
            if cli.diff {
                write_diff_to_stdout(result, colorize_stdout)?;
                flush_stdout()?;
            }
            if !cli.quiet && !cli.summary {
                progress.eprintln(&format!("{} would be reformatted", result.display_name))?;
            }
        }
        return Ok(());
    }

    if cli.in_place {
        return Ok(());
    }

    if cli.diff {
        if result.would_change {
            write_diff_to_stdout(result, colorize_stdout)?;
            flush_stdout()?;
        }
        return Ok(());
    }

    if !cli.summary && !cli.quiet {
        write_stdout_result(result, colorize_stdout, human_output)?;
    }

    Ok(())
}

fn emit_human_failure(
    failure: &FailedTarget,
    progress: &ProgressReporter,
) -> Result<(), cmakefmt::Error> {
    progress.eprintln(&failure.rendered_error)
}

fn write_stdout_result(
    result: &ProcessedTarget,
    colorize_stdout: bool,
    human_output: &mut HumanOutputState,
) -> Result<(), cmakefmt::Error> {
    if human_output.multi_target_stdout {
        if human_output.wrote_stdout_block {
            io::stdout().write_all(b"\n").map_err(cmakefmt::Error::Io)?;
        }
        write_stdout_header(&result.display_name, colorize_stdout)?;
    }
    let display_output = result
        .highlighted_output
        .as_deref()
        .unwrap_or(&result.formatted);
    io::stdout()
        .write_all(display_output.as_bytes())
        .map_err(cmakefmt::Error::Io)?;
    flush_stdout()?;
    human_output.wrote_stdout_block = true;
    Ok(())
}

fn flush_stdout() -> Result<(), cmakefmt::Error> {
    io::stdout().flush().map_err(cmakefmt::Error::Io)
}

fn error_display_name(err: &cmakefmt::Error) -> String {
    match err {
        cmakefmt::Error::Parse(parse) => parse.display_name.clone(),
        cmakefmt::Error::Config(config) => config.path.display().to_string(),
        cmakefmt::Error::Spec(spec) => spec.path.display().to_string(),
        cmakefmt::Error::Formatter(message) => message
            .split(':')
            .next()
            .unwrap_or("<unknown>")
            .trim()
            .to_owned(),
        cmakefmt::Error::Io(_) | cmakefmt::Error::LayoutTooWide { .. } => "<unknown>".to_owned(),
        _ => "<unknown>".to_owned(),
    }
}

fn write_stdout_header(display_name: &str, colorize: bool) -> Result<(), cmakefmt::Error> {
    if colorize {
        writeln!(io::stdout(), "\u{1b}[1;36m### {display_name}\u{1b}[0m")
            .map_err(cmakefmt::Error::Io)?;
    } else {
        writeln!(io::stdout(), "### {display_name}").map_err(cmakefmt::Error::Io)?;
    }
    Ok(())
}

fn validate_cli(cli: &Cli) -> Result<(), cmakefmt::Error> {
    if cli.no_config && !cli.config_paths.is_empty() {
        return Err(cmakefmt::Error::Formatter(
            "--no-config cannot be combined with --config-file".to_owned(),
        ));
    }

    if cli.verify && cli.no_verify {
        return Err(cmakefmt::Error::Formatter(
            "--verify cannot be combined with --fast".to_owned(),
        ));
    }

    if (cli.staged || cli.changed) && (!cli.files.is_empty() || !cli.files_from.is_empty()) {
        return Err(cmakefmt::Error::Formatter(
            "--staged/--changed cannot be combined with explicit input paths or --files-from"
                .to_owned(),
        ));
    }

    if cli.stdin_path.is_some() && !cli.files.iter().any(|file| file == "-") {
        return Err(cmakefmt::Error::Formatter(
            "--stdin-path requires stdin input via `cmakefmt -`".to_owned(),
        ));
    }

    if cli.generate_man_page
        && (!cli.files.is_empty()
            || !cli.files_from.is_empty()
            || !cli.config_paths.is_empty()
            || cli.no_config
            || cli.debug
            || cli.quiet
            || cli.keep_going
            || cli.diff
            || cli.check
            || cli.in_place
            || cli.list_changed_files
            || cli.list_input_files
            || cli.staged
            || cli.changed
            || cli.stdin_path.is_some()
            || !cli.line_ranges.is_empty())
    {
        return Err(cmakefmt::Error::Formatter(
            "completion/man-page generation cannot be combined with formatting or config-introspection inputs".to_owned(),
        ));
    }

    if cli.diff && cli.list_changed_files {
        return Err(cmakefmt::Error::Formatter(
            "--diff cannot be combined with --list-changed-files".to_owned(),
        ));
    }

    if cli.list_input_files && cli.report_format != ReportFormat::Human {
        return Err(cmakefmt::Error::Formatter(
            "--list-input-files only supports human output".to_owned(),
        ));
    }

    if cli.list_input_files && !cli.line_ranges.is_empty() {
        return Err(cmakefmt::Error::Formatter(
            "--list-input-files cannot be combined with --lines".to_owned(),
        ));
    }

    if cli.watch && cli.files.iter().any(|f| f == "-") {
        return Err(cmakefmt::Error::Formatter(
            "--watch cannot read from stdin".to_owned(),
        ));
    }

    Ok(())
}

fn run_config_subcommand(cli: &Cli, action: &ConfigAction) -> Result<u8, cmakefmt::Error> {
    match action {
        ConfigAction::Dump { format } => {
            print!("{}", default_config_template_for(*format));
            Ok(EXIT_OK)
        }
        ConfigAction::Schema => {
            println!("{}", generate_json_schema());
            Ok(EXIT_OK)
        }
        ConfigAction::Check { path } => {
            let path_arg = path.as_deref().unwrap_or("");
            run_check_config(cli, path_arg)
        }
        ConfigAction::Show { format, path } => {
            if let Some(p) = path {
                if !Path::new(p).exists() {
                    eprintln!("error: file not found: {p}");
                    return Ok(EXIT_ERROR);
                }
            }
            let target = path
                .as_ref()
                .map(PathBuf::from)
                .or_else(|| resolve_config_probe_target(cli).ok().flatten());
            let (config, _, _) = build_context(cli, target.as_deref())?;
            let rendered = render_effective_config(&config, *format)?;
            print!("{rendered}");
            if !rendered.ends_with('\n') {
                println!();
            }
            Ok(EXIT_OK)
        }
        ConfigAction::Path { path } => {
            if let Some(p) = path {
                if !Path::new(p).exists() {
                    eprintln!("error: file not found: {p}");
                    return Ok(EXIT_ERROR);
                }
            }
            let target = path
                .as_ref()
                .map(PathBuf::from)
                .or_else(|| resolve_config_probe_target(cli).ok().flatten());
            let config_context = resolve_config_context(cli, target.as_deref());
            for p in &config_context.sources {
                println!("{}", p.display());
            }
            Ok(EXIT_OK)
        }
        ConfigAction::Explain { path } => {
            if let Some(p) = path {
                if !Path::new(p).exists() {
                    eprintln!("error: file not found: {p}");
                    return Ok(EXIT_ERROR);
                }
            }
            let target = path.as_deref().map(Path::new).unwrap_or(Path::new("."));
            explain_config(cli, target)
        }
        ConfigAction::Convert { paths, format } => {
            if paths.is_empty() {
                return Err(cmakefmt::Error::Formatter(
                    "cmakefmt config convert requires at least one config file path".to_owned(),
                ));
            }
            let output = convert_legacy_config_files(paths, *format)?;
            print!("{output}");
            Ok(EXIT_OK)
        }
        ConfigAction::Init => {
            let path = Path::new(".cmakefmt.yaml");
            if path.exists() {
                eprintln!(".cmakefmt.yaml already exists");
                return Ok(EXIT_ERROR);
            }
            std::fs::write(path, default_config_template_for(DumpConfigFormat::Yaml))
                .map_err(cmakefmt::Error::Io)?;
            eprintln!("created .cmakefmt.yaml");
            Ok(EXIT_OK)
        }
    }
}

fn run_dump_subcommand(
    cli: &Cli,
    action: &DumpAction,
    file: Option<&Path>,
) -> Result<u8, cmakefmt::Error> {
    let source = match file {
        Some(path) if path.as_os_str() != "-" => {
            std::fs::read_to_string(path).map_err(cmakefmt::Error::Io)?
        }
        _ => {
            let mut buf = String::new();
            io::Read::read_to_string(&mut io::stdin(), &mut buf).map_err(cmakefmt::Error::Io)?;
            buf
        }
    };

    match action {
        DumpAction::Ast => {
            let parsed = parser::parse(&source)?;
            let color = should_colorize_stdout(cli.color);
            let tree = cmakefmt::dump::dump_ast(&parsed, color);
            print!("{tree}");
            Ok(EXIT_OK)
        }
        DumpAction::Parse => {
            let config_path = file.filter(|p| p.as_os_str() != "-");
            let (_, registry, _) = build_context(cli, config_path)?;
            let parsed = parser::parse(&source)?;
            let color = should_colorize_stdout(cli.color);
            let tree = cmakefmt::dump::dump_parse(&parsed, &registry, color);
            print!("{tree}");
            Ok(EXIT_OK)
        }
    }
}

fn install_git_hook() -> Result<u8, cmakefmt::Error> {
    let hooks_dir = Path::new(".git/hooks");
    if !hooks_dir.exists() {
        eprintln!("error: not a git repository (no .git/hooks directory)");
        return Ok(EXIT_ERROR);
    }
    let hook_path = hooks_dir.join("pre-commit");
    if hook_path.exists() {
        eprintln!(
            "error: {} already exists; remove it first or add cmakefmt manually",
            hook_path.display()
        );
        return Ok(EXIT_ERROR);
    }
    let hook_content = "#!/bin/sh\n\
        # Installed by cmakefmt install-hook\n\
        cmakefmt --check --staged\n";
    std::fs::write(&hook_path, hook_content).map_err(cmakefmt::Error::Io)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook_path, std::fs::Permissions::from_mode(0o755))
            .map_err(cmakefmt::Error::Io)?;
    }
    eprintln!("installed pre-commit hook: {}", hook_path.display());
    Ok(EXIT_OK)
}

fn run_check_config(cli: &Cli, path_arg: &str) -> Result<u8, cmakefmt::Error> {
    if !path_arg.is_empty() {
        let path = Path::new(path_arg);
        if !path.exists() {
            eprintln!("config file not found: {}", path.display());
            return Ok(EXIT_ERROR);
        }
        match Config::from_files(&[path.to_path_buf()]) {
            Ok(_) => {
                println!("config is valid: {}", path.display());
                Ok(EXIT_OK)
            }
            Err(err) => {
                eprintln!("{err}");
                Ok(EXIT_ERROR)
            }
        }
    } else {
        let context = resolve_config_context(cli, Some(Path::new(".")));
        if context.sources.is_empty() {
            eprintln!("no config file found");
            return Ok(EXIT_ERROR);
        }
        match Config::from_files(&context.sources) {
            Ok(_) => {
                for source in &context.sources {
                    println!("config is valid: {}", source.display());
                }
                Ok(EXIT_OK)
            }
            Err(err) => {
                eprintln!("{err}");
                Ok(EXIT_ERROR)
            }
        }
    }
}

fn explain_config(cli: &Cli, path: &Path) -> Result<u8, cmakefmt::Error> {
    let (config, _, config_context) = build_context(cli, Some(path))?;
    println!("target: {}", path.display());
    println!("config mode: {}", describe_config_mode(config_context.mode));
    if config_context.sources.is_empty() {
        println!("config files: none");
    } else {
        println!("config files:");
        for source in &config_context.sources {
            println!("  - {}", source.display());
        }
    }

    let cli_overrides = describe_cli_overrides(cli);
    println!("{cli_overrides}");
    println!();
    println!("effective config:");
    let rendered = render_effective_config(&config, DumpConfigFormat::Yaml)?;
    print!("{rendered}");
    if !rendered.ends_with('\n') {
        println!();
    }
    Ok(EXIT_OK)
}

fn resolve_config_probe_target(cli: &Cli) -> Result<Option<PathBuf>, cmakefmt::Error> {
    if cli.files.is_empty() {
        return Ok(Some(PathBuf::from(".")));
    }

    if cli.files.len() != 1 {
        return Err(cmakefmt::Error::Formatter(
            "config introspection expects exactly one explicit path".to_owned(),
        ));
    }

    if cli.files[0] == "-" {
        return cli.stdin_path.clone().map(Some).ok_or_else(|| {
            cmakefmt::Error::Formatter(
                "stdin config introspection requires --stdin-path".to_owned(),
            )
        });
    }

    Ok(Some(PathBuf::from(&cli.files[0])))
}

fn resolve_config_context(cli: &Cli, file_path: Option<&Path>) -> ConfigContext {
    if cli.no_config {
        return ConfigContext {
            mode: ConfigSourceMode::Disabled,
            sources: Vec::new(),
        };
    }

    if !cli.config_paths.is_empty() {
        return ConfigContext {
            mode: ConfigSourceMode::Explicit,
            sources: cli.config_paths.clone(),
        };
    }

    if let Some(path) = file_path {
        let sources = Config::config_sources_for(path);
        return ConfigContext {
            mode: if sources.is_empty() {
                ConfigSourceMode::DefaultsOnly
            } else {
                ConfigSourceMode::Discovered
            },
            sources,
        };
    }

    ConfigContext {
        mode: ConfigSourceMode::DefaultsOnly,
        sources: Vec::new(),
    }
}

fn describe_config_mode(mode: ConfigSourceMode) -> &'static str {
    match mode {
        ConfigSourceMode::Disabled => "disabled by --no-config",
        ConfigSourceMode::Explicit => "explicit --config-file override(s)",
        ConfigSourceMode::Discovered => "discovered from the target path",
        ConfigSourceMode::DefaultsOnly => "defaults only",
    }
}

fn compile_file_filter(pattern: Option<&str>) -> Result<Option<Regex>, cmakefmt::Error> {
    pattern
        .map(|pattern| {
            Regex::new(pattern).map_err(|err| {
                cmakefmt::Error::Formatter(format!("invalid file regex {pattern:?}: {err}"))
            })
        })
        .transpose()
}

fn collect_targets(
    cli: &Cli,
    file_filter: Option<&Regex>,
) -> Result<Vec<InputTarget>, cmakefmt::Error> {
    if cli.debug {
        log_discovery_context(cli, file_filter);
    }

    let inputs = collect_input_arguments(cli, file_filter)?;

    let mut targets = Vec::new();
    let mut seen_paths = BTreeSet::new();

    for input in inputs {
        if input == "-" {
            targets.push(InputTarget::Stdin);
            continue;
        }

        let path = PathBuf::from(&input);
        if path.is_file() {
            push_unique_path(&mut targets, &mut seen_paths, path);
            continue;
        }

        if path.is_dir() {
            let all_cmake = discover_cmake_files_with_options(
                &path,
                DiscoveryOptions {
                    file_filter: None,
                    honor_gitignore: !cli.no_gitignore,
                    explicit_ignore_paths: &cli.ignore_paths,
                },
            );
            let filtered = if file_filter.is_some() {
                discover_cmake_files_with_options(
                    &path,
                    DiscoveryOptions {
                        file_filter,
                        honor_gitignore: !cli.no_gitignore,
                        explicit_ignore_paths: &cli.ignore_paths,
                    },
                )
            } else {
                all_cmake.clone()
            };

            if cli.debug && file_filter.is_some() {
                let filtered_set: BTreeSet<_> = filtered.iter().collect();
                for skipped in &all_cmake {
                    if !filtered_set.contains(skipped) {
                        log_debug(format!("skipped by --path-regex: {}", skipped.display()));
                    }
                }
            }

            for discovered in filtered {
                push_unique_path(&mut targets, &mut seen_paths, discovered);
            }
            continue;
        }

        return Err(cmakefmt::Error::Formatter(format!(
            "{}: no such file or directory",
            path.display()
        )));
    }

    Ok(targets)
}

fn log_discovery_context(cli: &Cli, file_filter: Option<&Regex>) {
    if cli.staged {
        log_debug("discovery mode: --staged (git staged files only)");
    } else if cli.changed {
        let since = cli.since.as_deref().unwrap_or("HEAD");
        log_debug(format!("discovery mode: --changed --since {since}"));
    }
    if !cli.no_gitignore {
        log_debug("discovery: .gitignore rules active (use --no-gitignore to disable)");
    }
    if !cli.ignore_paths.is_empty() {
        for p in &cli.ignore_paths {
            log_debug(format!("discovery: explicit ignore path: {}", p.display()));
        }
    }
    if let Some(re) = file_filter {
        log_debug(format!("discovery: --path-regex filter active: {re}"));
    }
    if cli.require_pragma {
        log_debug("discovery: --require-pragma active (files without pragma will be skipped)");
    }
}

fn collect_input_arguments(
    cli: &Cli,
    file_filter: Option<&Regex>,
) -> Result<Vec<String>, cmakefmt::Error> {
    let mut inputs = Vec::new();

    if cli.staged {
        inputs.extend(collect_git_paths(GitSelectionMode::Staged, file_filter)?);
    } else if cli.changed {
        inputs.extend(collect_git_paths(
            GitSelectionMode::Changed(cli.since.as_deref()),
            file_filter,
        )?);
    }

    for files_from in &cli.files_from {
        inputs.extend(read_files_from(files_from)?);
    }

    inputs.extend(cli.files.clone());

    if inputs.is_empty() {
        inputs.push(".".to_owned());
    }

    Ok(inputs)
}

#[derive(Copy, Clone)]
enum GitSelectionMode<'a> {
    Staged,
    Changed(Option<&'a str>),
}

fn collect_git_paths(
    mode: GitSelectionMode<'_>,
    file_filter: Option<&Regex>,
) -> Result<Vec<String>, cmakefmt::Error> {
    let repo_root = git_command(["rev-parse", "--show-toplevel"])?;
    let repo_root = PathBuf::from(repo_root.trim());

    let diff_output = match mode {
        GitSelectionMode::Staged => {
            git_command(["diff", "--name-only", "--cached", "--diff-filter=ACMR"])?
        }
        GitSelectionMode::Changed(Some(reference)) => git_command([
            "diff",
            "--name-only",
            "--diff-filter=ACMR",
            &format!("{reference}...HEAD"),
        ])?,
        GitSelectionMode::Changed(None) => {
            git_command(["diff", "--name-only", "--diff-filter=ACMR", "HEAD"])?
        }
    };

    let mut paths = Vec::new();
    for line in diff_output
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
    {
        let candidate = repo_root.join(line);
        if is_cmake_file(&candidate) && matches_filter(&candidate, file_filter) {
            paths.push(candidate.display().to_string());
        }
    }
    Ok(paths)
}

fn git_command<const N: usize>(args: [&str; N]) -> Result<String, cmakefmt::Error> {
    let output = std::process::Command::new("git")
        .args(args)
        .output()
        .map_err(cmakefmt::Error::Io)?;
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
    } else {
        Err(cmakefmt::Error::Formatter(format!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        )))
    }
}

fn read_files_from(source: &str) -> Result<Vec<String>, cmakefmt::Error> {
    let contents = if source == "-" {
        let mut stdin = String::new();
        io::stdin()
            .read_to_string(&mut stdin)
            .map_err(cmakefmt::Error::Io)?;
        stdin
    } else {
        std::fs::read_to_string(source)
            .map_err(|err| cmakefmt::Error::Formatter(format!("{source}: {err}")))?
    };

    let entries = if contents.contains('\0') {
        contents
            .split('\0')
            .map(str::trim)
            .filter(|entry| !entry.is_empty())
            .map(ToOwned::to_owned)
            .collect()
    } else {
        contents
            .lines()
            .map(str::trim)
            .filter(|entry| !entry.is_empty())
            .map(ToOwned::to_owned)
            .collect()
    };
    Ok(entries)
}

fn push_unique_path(
    targets: &mut Vec<InputTarget>,
    seen_paths: &mut BTreeSet<PathBuf>,
    path: PathBuf,
) {
    if seen_paths.insert(path.clone()) {
        targets.push(InputTarget::Path(path));
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ConfigSourceMode {
    Disabled,
    Explicit,
    Discovered,
    DefaultsOnly,
}

#[derive(Clone, Debug)]
struct ConfigContext {
    mode: ConfigSourceMode,
    sources: Vec<PathBuf>,
}

/// Build a formatting context by layering: defaults → config files → CLI
/// overrides, and by merging any `[commands]` spec overrides from the same
/// config files into the command registry.
fn build_context(
    cli: &Cli,
    file_path: Option<&Path>,
) -> Result<(Config, CommandRegistry, ConfigContext), cmakefmt::Error> {
    let config_context = resolve_config_context(cli, file_path);

    let mut config = Config::from_files(&config_context.sources)?;
    let mut registry = CommandRegistry::builtins().clone();
    for path in &config_context.sources {
        registry.merge_override_file(path)?;
    }

    // Apply .editorconfig fallback when no cmakefmt config file was found.
    if matches!(config_context.mode, ConfigSourceMode::DefaultsOnly) && !cli.no_editorconfig {
        if let Some(path) = file_path {
            let ec = cmakefmt::config::editorconfig::read_editorconfig(path);
            if let Some(use_tabs) = ec.use_tabs {
                config.use_tabchars = use_tabs;
            }
            if let Some(tab_size) = ec.tab_size {
                config.tab_size = tab_size;
            }
            if cli.debug && ec.has_any() {
                log_debug(format!(
                    "editorconfig fallback: tab_size={}, use_tabs={}",
                    ec.tab_size
                        .map_or("(default)".to_owned(), |v| v.to_string()),
                    ec.use_tabs
                        .map_or("(default)".to_owned(), |v| v.to_string()),
                ));
            }
        }
    }

    if let Some(v) = cli.line_width {
        config.line_width = v;
    }
    if let Some(v) = cli.tab_size {
        config.tab_size = v;
    }
    if let Some(v) = cli.command_case {
        config.command_case = v;
    }
    if let Some(v) = cli.keyword_case {
        config.keyword_case = v;
    }
    if let Some(v) = cli.dangle_parens {
        config.dangle_parens = v;
    }

    // --preview enables all experimental options.
    if cli.preview {
        config.experimental = cmakefmt::config::Experimental::default();
        // When experimental options are added, this should call a method
        // that sets them all to true, e.g.:
        // config.experimental = cmakefmt::config::Experimental::all_enabled();
    }

    Ok((config, registry, config_context))
}

#[derive(Clone)]
enum InputTarget {
    Stdin,
    Path(PathBuf),
}

impl InputTarget {
    fn is_path(&self) -> bool {
        matches!(self, InputTarget::Path(_))
    }

    fn display_name(&self, stdin_path: Option<&Path>) -> String {
        match self {
            Self::Stdin => stdin_path
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| "<stdin>".to_owned()),
            Self::Path(path) => path.display().to_string(),
        }
    }
}

struct ProcessedTarget {
    path: Option<PathBuf>,
    display_name: String,
    formatted: String,
    highlighted_output: Option<String>,
    unified_diff: Option<String>,
    changed_lines: Vec<usize>,
    would_change: bool,
    skipped: bool,
    skip_reason: Option<String>,
    debug_lines: Vec<String>,
    source_lines: usize,
    formatted_lines: usize,
    elapsed: std::time::Duration,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum VerificationMode {
    Disabled,
    Enabled,
}

struct FailedTarget {
    display_name: String,
    rendered_error: String,
}

#[derive(Clone, Debug)]
struct CacheContext {
    cache_file: PathBuf,
    tool_signature: String,
    config_signature: String,
    source_signature: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct CacheEntry {
    tool_signature: String,
    config_signature: String,
    source_signature: String,
    formatted: String,
}

#[derive(Debug, Serialize)]
struct JsonReport {
    mode: &'static str,
    summary: RunSummary,
    files: Vec<JsonFileReport>,
    errors: Vec<JsonErrorReport>,
}

#[derive(Debug, Serialize)]
struct JsonErrorReport {
    display_name: String,
    error: String,
}

#[derive(Debug, Serialize)]
struct JsonFileReport {
    display_name: String,
    path: Option<String>,
    would_change: bool,
    skipped: bool,
    skip_reason: Option<String>,
    changed_lines: Vec<usize>,
    formatted: Option<String>,
    diff: Option<String>,
    debug_lines: Vec<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    elapsed_ms: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    source_lines: Option<usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    formatted_lines: Option<usize>,
}

#[derive(Debug, Default, Serialize)]
struct RunSummary {
    selected: usize,
    changed: usize,
    unchanged: usize,
    skipped: usize,
    failed: usize,
    total_changed_lines: usize,
    #[serde(skip)]
    elapsed: std::time::Duration,
}

fn process_targets_serial<F>(
    targets: &[InputTarget],
    cli: &Cli,
    colorize_stdout: bool,
    progress: &ProgressReporter,
    on_result: &mut F,
) -> Result<(), cmakefmt::Error>
where
    F: FnMut(Result<ProcessedTarget, cmakefmt::Error>) -> Result<(), cmakefmt::Error>,
{
    for target in targets {
        on_result(process_target(target, cli, colorize_stdout, progress))?;
    }
    Ok(())
}

fn process_targets_parallel<F>(
    targets: &[InputTarget],
    cli: &Cli,
    parallel_jobs: usize,
    colorize_stdout: bool,
    progress: &ProgressReporter,
    on_result: &mut F,
) -> Result<(), cmakefmt::Error>
where
    F: FnMut(Result<ProcessedTarget, cmakefmt::Error>) -> Result<(), cmakefmt::Error>,
{
    let worker_count = parallel_jobs.min(targets.len().max(1));
    let next_work = AtomicUsize::new(0);
    let cancelled = AtomicBool::new(false);

    std::thread::scope(|scope| {
        let (tx, rx) = mpsc::channel();

        for _ in 0..worker_count {
            let tx = tx.clone();
            let next_work = &next_work;
            let cancelled = &cancelled;
            scope.spawn(move || loop {
                if cancelled.load(Ordering::Relaxed) {
                    break;
                }
                let index = next_work.fetch_add(1, Ordering::Relaxed);
                let Some(target) = targets.get(index) else {
                    break;
                };
                if tx
                    .send((
                        index,
                        process_target(target, cli, colorize_stdout, progress),
                    ))
                    .is_err()
                {
                    break;
                }
            });
        }
        drop(tx);

        // Buffer out-of-order results and flush in input order. Uses a
        // HashMap so memory scales with the actual backlog, not total
        // target count.
        let mut next_emit = 0;
        let mut pending: HashMap<usize, Result<ProcessedTarget, cmakefmt::Error>> = HashMap::new();
        let mut first_error: Option<cmakefmt::Error> = None;

        while let Ok((index, result)) = rx.recv() {
            // Cancel workers immediately on errors, even if we can't
            // emit them yet due to ordering.
            if first_error.is_none() && result.is_err() && !cli.keep_going {
                cancelled.store(true, Ordering::Relaxed);
            }

            pending.insert(index, result);

            // Drain all contiguous results starting from next_emit.
            while pending.contains_key(&next_emit) {
                let result = pending.remove(&next_emit).unwrap();
                match on_result(result) {
                    Ok(()) => {}
                    Err(err) => {
                        cancelled.store(true, Ordering::Relaxed);
                        first_error = Some(err);
                    }
                }
                next_emit += 1;
            }
        }

        match first_error {
            Some(err) => Err(err),
            None => Ok(()),
        }
    })
}

fn process_target(
    target: &InputTarget,
    cli: &Cli,
    colorize_stdout: bool,
    progress: &ProgressReporter,
) -> Result<ProcessedTarget, cmakefmt::Error> {
    let start = std::time::Instant::now();
    let mut result = match target {
        InputTarget::Stdin => process_stdin(cli, colorize_stdout),
        InputTarget::Path(path) => process_path(path, cli, colorize_stdout),
    };
    if let Ok(ref mut r) = result {
        r.elapsed = start.elapsed();
    }
    progress.finish_one();
    result
}

fn process_stdin(cli: &Cli, colorize_stdout: bool) -> Result<ProcessedTarget, cmakefmt::Error> {
    let mut source = String::new();
    io::stdin()
        .read_to_string(&mut source)
        .map_err(cmakefmt::Error::Io)?;

    let stdin_path = cli.stdin_path.as_deref();
    let display_name = stdin_path
        .map(|path| path.display().to_string())
        .unwrap_or_else(|| "<stdin>".to_owned());
    if cli.require_pragma && !has_enable_pragma(&source) {
        return Ok(skipped_target(
            stdin_path.map(Path::to_path_buf),
            display_name,
            source,
            "missing format opt-in pragma".to_owned(),
            cli.debug,
        ));
    }
    let (config, registry, config_context) = build_context(cli, stdin_path)?;
    let collect_debug = needs_debug_lines(cli);
    let mut debug_lines = if collect_debug {
        vec![
            format!("processing {display_name}"),
            describe_config_context(&config_context),
        ]
    } else {
        Vec::new()
    };
    let (formatted, mut formatter_debug) = if collect_debug {
        match format_source_with_registry_debug(&source, &config, &registry) {
            Ok(result) => result,
            Err(err) => return Err(err.with_display_name(&display_name)),
        }
    } else {
        match format_source_with_registry(&source, &config, &registry) {
            Ok(formatted) => (formatted, Vec::new()),
            Err(err) => return Err(err.with_display_name(&display_name)),
        }
    };
    if collect_debug {
        debug_lines.append(&mut formatter_debug);
    }

    if verification_mode(cli) == VerificationMode::Enabled {
        verify_semantics(&source, &formatted, &registry, &display_name)?;
        if collect_debug {
            debug_lines.push(format!(
                "result {display_name}: semantic verification passed"
            ));
        }
    }

    let formatted = apply_line_ranges(&source, &formatted, &cli.line_ranges, &display_name)?;

    let would_change = formatted != source;
    let source_lines = source.lines().count();
    let formatted_lines = formatted.lines().count();
    let changed_lines = if needs_changed_lines(cli, colorize_stdout) {
        changed_formatted_line_numbers(
            &split_lines_with_endings(&source),
            &split_lines_with_endings(&formatted),
        )
    } else {
        Vec::new()
    };
    if collect_debug {
        debug_lines.push(format!(
            "result {display_name}: would_change={would_change}"
        ));
        debug_lines.push(format!(
            "result {display_name}: changed_lines={}",
            changed_lines.len()
        ));
    }
    let highlighted_output = colorize_stdout
        .then(|| highlight_changed_lines(&source, &formatted))
        .filter(|_| would_change);
    let unified_diff = would_change.then(|| build_unified_diff(&display_name, &source, &formatted));

    Ok(ProcessedTarget {
        path: stdin_path.map(Path::to_path_buf),
        display_name,
        formatted,
        highlighted_output,
        unified_diff,
        changed_lines,
        would_change,
        skipped: false,
        skip_reason: None,
        debug_lines,
        source_lines,
        formatted_lines,
        elapsed: std::time::Duration::ZERO,
    })
}

fn process_path(
    path: &Path,
    cli: &Cli,
    colorize_stdout: bool,
) -> Result<ProcessedTarget, cmakefmt::Error> {
    let source = std::fs::read_to_string(path)
        .map_err(|err| cmakefmt::Error::Formatter(format!("{}: {err}", path.display())))?;
    if cli.require_pragma && !has_enable_pragma(&source) {
        return Ok(skipped_target(
            Some(path.to_path_buf()),
            path.display().to_string(),
            source,
            "missing format opt-in pragma".to_owned(),
            cli.debug,
        ));
    }
    let (config, registry, config_context) = build_context(cli, Some(path))?;
    let collect_debug = needs_debug_lines(cli);
    let mut debug_lines = if collect_debug {
        vec![
            format!("processing {}", path.display()),
            describe_config_context(&config_context),
            describe_cli_overrides(cli),
        ]
    } else {
        Vec::new()
    };
    let cache_context = if cli.cache || cli.cache_location.is_some() {
        Some(cache_context(
            path,
            &source,
            &config,
            &config_context,
            cli.cache_location.as_deref(),
            cli.cache_strategy,
        )?)
    } else {
        None
    };

    let mut cache_hit = false;
    let (formatted, mut formatter_debug) = if let Some(cache) = &cache_context {
        if let Some(cached) = read_cache_entry(cache)? {
            cache_hit = true;
            if collect_debug {
                debug_lines.push(format!(
                    "cache hit {} ({})",
                    path.display(),
                    cache.cache_file.display()
                ));
            }
            (cached.formatted, Vec::new())
        } else {
            if collect_debug {
                debug_lines.push(format!(
                    "cache miss {} ({})",
                    path.display(),
                    cache.cache_file.display()
                ));
            }
            if collect_debug {
                match format_source_with_registry_debug(&source, &config, &registry) {
                    Ok(result) => result,
                    Err(err) => return Err(err.with_display_name(path.display().to_string())),
                }
            } else {
                match format_source_with_registry(&source, &config, &registry) {
                    Ok(formatted) => (formatted, Vec::new()),
                    Err(err) => return Err(err.with_display_name(path.display().to_string())),
                }
            }
        }
    } else if collect_debug {
        match format_source_with_registry_debug(&source, &config, &registry) {
            Ok(result) => result,
            Err(err) => return Err(err.with_display_name(path.display().to_string())),
        }
    } else {
        match format_source_with_registry(&source, &config, &registry) {
            Ok(formatted) => (formatted, Vec::new()),
            Err(err) => return Err(err.with_display_name(path.display().to_string())),
        }
    };
    if collect_debug {
        debug_lines.append(&mut formatter_debug);
    }

    if verification_mode(cli) == VerificationMode::Enabled {
        verify_semantics(&source, &formatted, &registry, &path.display().to_string())?;
        if collect_debug {
            debug_lines.push(format!(
                "result {}: semantic verification passed",
                path.display()
            ));
        }
    }

    let formatted = apply_line_ranges(
        &source,
        &formatted,
        &cli.line_ranges,
        &path.display().to_string(),
    )?;
    let would_change = formatted != source;
    let source_lines = source.lines().count();
    let formatted_lines = formatted.lines().count();
    let changed_lines = if needs_changed_lines(cli, colorize_stdout) {
        changed_formatted_line_numbers(
            &split_lines_with_endings(&source),
            &split_lines_with_endings(&formatted),
        )
    } else {
        Vec::new()
    };
    if collect_debug {
        debug_lines.push(format!(
            "result {}: would_change={would_change}",
            path.display()
        ));
        debug_lines.push(format!(
            "result {}: changed_lines={}",
            path.display(),
            changed_lines.len()
        ));
    }
    let highlighted_output = colorize_stdout
        .then(|| highlight_changed_lines(&source, &formatted))
        .filter(|_| would_change);
    let unified_diff =
        would_change.then(|| build_unified_diff(&path.display().to_string(), &source, &formatted));

    if let Some(cache) = &cache_context {
        if !cache_hit {
            write_cache_entry(
                cache,
                CacheEntry {
                    tool_signature: cache.tool_signature.clone(),
                    config_signature: cache.config_signature.clone(),
                    source_signature: cache.source_signature.clone(),
                    formatted: formatted.clone(),
                },
            )?;
        }
    }

    Ok(ProcessedTarget {
        path: Some(path.to_path_buf()),
        display_name: path.display().to_string(),
        formatted,
        highlighted_output,
        unified_diff,
        changed_lines,
        would_change,
        skipped: false,
        skip_reason: None,
        debug_lines,
        source_lines,
        formatted_lines,
        elapsed: std::time::Duration::ZERO,
    })
}

fn needs_changed_lines(cli: &Cli, colorize_stdout: bool) -> bool {
    colorize_stdout
        || !cli.line_ranges.is_empty()
        || cli.debug
        || cli.summary
        || cli.stat
        || cli.report_format != ReportFormat::Human
}

fn verification_mode(cli: &Cli) -> VerificationMode {
    if cli.verify || (cli.in_place && !cli.no_verify) {
        VerificationMode::Enabled
    } else {
        VerificationMode::Disabled
    }
}

fn has_enable_pragma(source: &str) -> bool {
    source.lines().any(|line| {
        let trimmed = line.trim();
        trimmed.contains("cmakefmt: enable")
            || trimmed.contains("fmt: enable")
            || trimmed.contains("cmake-format: enable")
    })
}

fn skipped_target(
    path: Option<PathBuf>,
    display_name: String,
    source: String,
    reason: String,
    debug: bool,
) -> ProcessedTarget {
    let mut debug_lines = Vec::new();
    if debug {
        debug_lines.push(format!("processing {display_name}"));
        debug_lines.push(format!("skipped {display_name}: {reason}"));
    }
    let source_lines = source.lines().count();

    ProcessedTarget {
        path,
        display_name,
        formatted_lines: source_lines,
        formatted: source,
        highlighted_output: None,
        unified_diff: None,
        changed_lines: Vec::new(),
        would_change: false,
        skipped: true,
        skip_reason: Some(reason),
        debug_lines,
        source_lines,
        elapsed: std::time::Duration::ZERO,
    }
}

fn cache_context(
    path: &Path,
    source: &str,
    config: &Config,
    config_context: &ConfigContext,
    cache_location: Option<&Path>,
    cache_strategy: CacheStrategy,
) -> Result<CacheContext, cmakefmt::Error> {
    let cache_root = cache_location
        .map(Path::to_path_buf)
        .unwrap_or_else(|| default_cache_dir(path));
    let cache_key = stable_hash(&path.display().to_string());
    let cache_file = cache_root.join(format!("{cache_key}.json"));
    let rendered_config = render_effective_config(config, DumpConfigFormat::Toml)?;
    let mut config_fingerprint = format!(
        "{}\n{}",
        env!("CMAKEFMT_CLI_LONG_VERSION"),
        rendered_config.trim_end()
    );
    for source_path in &config_context.sources {
        config_fingerprint.push('\n');
        config_fingerprint.push_str(
            &std::fs::read_to_string(source_path)
                .unwrap_or_else(|_| format!("<unreadable:{}>", source_path.display())),
        );
    }

    Ok(CacheContext {
        cache_file,
        tool_signature: env!("CMAKEFMT_CLI_LONG_VERSION").to_owned(),
        config_signature: stable_hash(&config_fingerprint),
        source_signature: source_signature(path, source, cache_strategy)?,
    })
}

fn default_cache_dir(path: &Path) -> PathBuf {
    find_git_root(path)
        .unwrap_or_else(|| {
            std::env::current_dir().unwrap_or_else(|_| {
                path.parent()
                    .map(Path::to_path_buf)
                    .unwrap_or_else(|| PathBuf::from("."))
            })
        })
        .join(".cmakefmt-cache")
}

fn find_git_root(path: &Path) -> Option<PathBuf> {
    let mut current = if path.is_dir() {
        path.to_path_buf()
    } else {
        path.parent()?.to_path_buf()
    };

    loop {
        if current.join(".git").exists() {
            return Some(current);
        }
        if !current.pop() {
            return None;
        }
    }
}

fn source_signature(
    path: &Path,
    source: &str,
    cache_strategy: CacheStrategy,
) -> Result<String, cmakefmt::Error> {
    match cache_strategy {
        CacheStrategy::Metadata => {
            let metadata = std::fs::metadata(path).map_err(cmakefmt::Error::Io)?;
            let modified = metadata
                .modified()
                .ok()
                .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
                .map(|duration| duration.as_nanos())
                .unwrap_or_default();
            Ok(format!("metadata:{}:{}", metadata.len(), modified))
        }
        CacheStrategy::Content => Ok(format!("content:{}", stable_hash(source))),
    }
}

fn read_cache_entry(cache: &CacheContext) -> Result<Option<CacheEntry>, cmakefmt::Error> {
    let contents = match std::fs::read_to_string(&cache.cache_file) {
        Ok(contents) => contents,
        Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(err) => return Err(cmakefmt::Error::Io(err)),
    };

    let entry: CacheEntry = match serde_json::from_str(&contents) {
        Ok(entry) => entry,
        Err(_) => return Ok(None),
    };

    Ok((entry.tool_signature == cache.tool_signature
        && entry.config_signature == cache.config_signature
        && entry.source_signature == cache.source_signature)
        .then_some(entry))
}

fn write_cache_entry(cache: &CacheContext, entry: CacheEntry) -> Result<(), cmakefmt::Error> {
    if let Some(parent) = cache.cache_file.parent() {
        std::fs::create_dir_all(parent).map_err(cmakefmt::Error::Io)?;
    }
    let json = serde_json::to_string(&entry).map_err(|err| {
        cmakefmt::Error::Formatter(format!("failed to serialize cache entry: {err}"))
    })?;
    std::fs::write(&cache.cache_file, json).map_err(cmakefmt::Error::Io)
}

fn stable_hash<T: Hash + ?Sized>(value: &T) -> String {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    value.hash(&mut hasher);
    format!("{:016x}", hasher.finish())
}

fn check_required_version(cli: &Cli) -> Result<(), cmakefmt::Error> {
    let Some(required) = &cli.required_version else {
        return Ok(());
    };

    let required = required.trim().trim_start_matches('v');
    let current = env!("CARGO_PKG_VERSION");
    if required == current {
        Ok(())
    } else {
        Err(cmakefmt::Error::Formatter(format!(
            "required cmakefmt version {required} does not match current version {current}"
        )))
    }
}

fn verify_semantics(
    original: &str,
    formatted: &str,
    registry: &CommandRegistry,
    display_name: &str,
) -> Result<(), cmakefmt::Error> {
    let original_ast =
        parser::parse(original).map_err(|err| err.with_display_name(display_name.to_owned()))?;
    let formatted_ast =
        parser::parse(formatted).map_err(|err| err.with_display_name(display_name.to_owned()))?;

    if normalize_semantics(original_ast, registry) == normalize_semantics(formatted_ast, registry) {
        Ok(())
    } else {
        Err(cmakefmt::Error::Formatter(format!(
            "{display_name}: semantic verification failed; formatted output changes the parsed CMake structure"
        )))
    }
}

fn resolve_parallel_jobs(requested: Option<usize>) -> Result<usize, cmakefmt::Error> {
    match requested {
        None => {
            // Default: available CPUs minus 1, minimum 1.
            let cpus = std::thread::available_parallelism()
                .map(|p| p.get())
                .unwrap_or(1);
            Ok(cpus.saturating_sub(1).max(1))
        }
        Some(0) => std::thread::available_parallelism()
            .map(|parallelism| parallelism.get())
            .map_err(cmakefmt::Error::Io),
        Some(jobs) => Ok(jobs.max(1)),
    }
}

#[derive(Clone)]
struct ProgressReporter {
    inner: Option<Arc<ProgressBar>>,
}

impl ProgressReporter {
    fn new(enabled: bool, total: usize) -> Self {
        let inner = enabled.then(|| {
            let progress = ProgressBar::new(total as u64);
            progress.set_draw_target(ProgressDrawTarget::stderr());
            progress.set_style(
                ProgressStyle::with_template(
                    "{spinner:.green} [Elapsed: {elapsed_precise}] |{bar:50.green/green}| ({eta_precise}) {pos}/{len} ({percent}%) files",
                )
                .expect("progress template should be valid")
                .progress_chars("=> "),
            );
            Arc::new(progress)
        });
        Self { inner }
    }

    fn finish_one(&self) {
        let Some(inner) = &self.inner else {
            return;
        };

        inner.inc(1);
        if inner.position() == inner.length().unwrap_or(0) {
            inner.finish();
        }
    }

    fn eprintln(&self, message: &str) -> Result<(), cmakefmt::Error> {
        if let Some(inner) = &self.inner {
            inner.println(message);
        } else {
            eprintln!("{message}");
        }
        io::stderr().flush().map_err(cmakefmt::Error::Io)
    }
}

fn should_colorize_stdout(choice: ColorChoice) -> bool {
    match choice {
        ColorChoice::Auto => {
            io::stdout().is_terminal()
                && std::env::var_os("NO_COLOR").is_none()
                && std::env::var("TERM").map_or(true, |term| term != "dumb")
        }
        ColorChoice::Always => true,
        ColorChoice::Never => false,
    }
}

fn should_colorize_stderr(choice: ColorChoice) -> bool {
    match choice {
        ColorChoice::Auto => {
            io::stderr().is_terminal()
                && std::env::var_os("NO_COLOR").is_none()
                && std::env::var("TERM").map_or(true, |term| term != "dumb")
        }
        ColorChoice::Always => true,
        ColorChoice::Never => false,
    }
}

fn highlight_changed_lines(source: &str, formatted: &str) -> String {
    let original_lines = split_lines_with_endings(source);
    let formatted_lines = split_lines_with_endings(formatted);
    let changed_mask = changed_formatted_line_mask(&original_lines, &formatted_lines);
    let mut output = String::with_capacity(formatted.len() + changed_mask.len() * 10);

    for (line, changed) in formatted_lines.iter().zip(changed_mask) {
        if changed {
            push_cyan_line(&mut output, line);
        } else {
            output.push_str(line);
        }
    }

    output
}

fn split_lines_with_endings(source: &str) -> Vec<&str> {
    if source.is_empty() {
        Vec::new()
    } else {
        source.split_inclusive('\n').collect()
    }
}

fn changed_formatted_line_mask<'a>(original: &[&'a str], formatted: &[&'a str]) -> Vec<bool> {
    let mut prefix_len = 0;
    while prefix_len < original.len()
        && prefix_len < formatted.len()
        && original[prefix_len] == formatted[prefix_len]
    {
        prefix_len += 1;
    }

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

    let original_mid = &original[prefix_len..original.len() - suffix_len];
    let formatted_mid = &formatted[prefix_len..formatted.len() - suffix_len];

    let mut changed = vec![false; prefix_len];
    changed.extend(diff_middle_mask(original_mid, formatted_mid));
    changed.extend(std::iter::repeat_n(false, suffix_len));
    changed
}

fn changed_formatted_line_numbers(original: &[&str], formatted: &[&str]) -> Vec<usize> {
    changed_formatted_line_mask(original, formatted)
        .into_iter()
        .enumerate()
        .filter_map(|(index, changed)| changed.then_some(index + 1))
        .collect()
}

fn diff_middle_mask<'a>(original: &[&'a str], formatted: &[&'a str]) -> Vec<bool> {
    const MAX_DP_CELLS: usize = 2_000_000;

    if formatted.is_empty() {
        return Vec::new();
    }

    if original.is_empty() {
        return vec![true; formatted.len()];
    }

    if original.len().saturating_mul(formatted.len()) > MAX_DP_CELLS {
        return vec![true; formatted.len()];
    }

    let mut dp = vec![vec![0u32; formatted.len() + 1]; original.len() + 1];

    for i in (0..original.len()).rev() {
        for j in (0..formatted.len()).rev() {
            dp[i][j] = if original[i] == formatted[j] {
                dp[i + 1][j + 1] + 1
            } else {
                dp[i + 1][j].max(dp[i][j + 1])
            };
        }
    }

    let mut changed = vec![true; formatted.len()];
    let mut i = 0;
    let mut j = 0;

    while i < original.len() && j < formatted.len() {
        if original[i] == formatted[j] {
            changed[j] = false;
            i += 1;
            j += 1;
        } else if dp[i + 1][j] >= dp[i][j + 1] {
            i += 1;
        } else {
            j += 1;
        }
    }

    changed
}

fn push_cyan_line(output: &mut String, line: &str) {
    push_ansi_line(output, line, "\u{1b}[36m");
}

fn push_red_line(output: &mut String, line: &str) {
    push_ansi_line(output, line, "\u{1b}[31m");
}

fn push_green_line(output: &mut String, line: &str) {
    push_ansi_line(output, line, "\u{1b}[32m");
}

fn push_ansi_line(output: &mut String, line: &str, colour: &str) {
    const RESET: &str = "\u{1b}[0m";

    if let Some(stripped) = line.strip_suffix('\n') {
        output.push_str(colour);
        output.push_str(stripped);
        output.push_str(RESET);
        output.push('\n');
    } else {
        output.push_str(colour);
        output.push_str(line);
        output.push_str(RESET);
    }
}

fn colorize_unified_diff(diff: &str) -> String {
    let mut output = String::with_capacity(diff.len() + 256);
    for line in split_lines_with_endings(diff) {
        if line.starts_with('+') && !line.starts_with("+++") {
            push_green_line(&mut output, line);
        } else if line.starts_with('-') && !line.starts_with("---") {
            push_red_line(&mut output, line);
        } else {
            output.push_str(line);
        }
    }
    output
}

fn build_unified_diff(display_name: &str, source: &str, formatted: &str) -> String {
    TextDiff::from_lines(source, formatted)
        .unified_diff()
        .context_radius(3)
        .header(&format!("a/{display_name}"), &format!("b/{display_name}"))
        .to_string()
}

fn apply_line_ranges(
    source: &str,
    formatted: &str,
    line_ranges: &[LineRange],
    display_name: &str,
) -> Result<String, cmakefmt::Error> {
    if line_ranges.is_empty() {
        return Ok(formatted.to_owned());
    }

    let changed_lines = changed_formatted_line_numbers(
        &split_lines_with_endings(source),
        &split_lines_with_endings(formatted),
    );
    let mut outside = Vec::new();
    for line in changed_lines {
        if !line_ranges.iter().any(|range| range.contains(line)) {
            outside.push(line);
        }
    }

    if outside.is_empty() {
        Ok(formatted.to_owned())
    } else {
        Err(cmakefmt::Error::Formatter(format!(
            "{display_name}: selected line ranges would affect lines outside the requested ranges ({})",
            outside
                .into_iter()
                .map(|line| line.to_string())
                .collect::<Vec<_>>()
                .join(", ")
        )))
    }
}

fn build_json_report(
    results: &[ProcessedTarget],
    failures: &[FailedTarget],
    summary: &RunSummary,
    cli: &Cli,
) -> JsonReport {
    let mode = if cli.in_place {
        "in-place"
    } else if cli.check {
        "check"
    } else if cli.list_changed_files {
        "list-changed-files"
    } else if cli.list_input_files {
        "list-input-files"
    } else if cli.diff {
        "diff"
    } else {
        "stdout"
    };

    JsonReport {
        mode,
        summary: RunSummary {
            selected: summary.selected,
            changed: summary.changed,
            unchanged: summary.unchanged,
            skipped: summary.skipped,
            failed: summary.failed,
            total_changed_lines: summary.total_changed_lines,
            ..RunSummary::default()
        },
        files: results
            .iter()
            .map(|result| JsonFileReport {
                display_name: result.display_name.clone(),
                path: result.path.as_ref().map(|path| path.display().to_string()),
                would_change: result.would_change,
                skipped: result.skipped,
                skip_reason: result.skip_reason.clone(),
                changed_lines: result.changed_lines.clone(),
                formatted: (!cli.in_place
                    && !cli.check
                    && !cli.list_changed_files
                    && !cli.list_input_files
                    && !cli.diff)
                    .then(|| result.formatted.clone()),
                diff: cli
                    .diff
                    .then(|| result.unified_diff.clone().unwrap_or_default()),
                debug_lines: if cli.debug {
                    result.debug_lines.clone()
                } else {
                    Vec::new()
                },
                elapsed_ms: cli.summary.then_some(result.elapsed.as_millis() as u64),
                source_lines: cli.summary.then_some(result.source_lines),
                formatted_lines: cli.summary.then_some(result.formatted_lines),
            })
            .collect(),
        errors: failures
            .iter()
            .map(|failure| JsonErrorReport {
                display_name: failure.display_name.clone(),
                error: failure.rendered_error.clone(),
            })
            .collect(),
    }
}

fn build_github_report(
    results: &[ProcessedTarget],
    failures: &[FailedTarget],
    summary: &RunSummary,
) -> String {
    let mut out = String::new();

    for result in results {
        if !result.would_change {
            continue;
        }

        let line = result.changed_lines.first().copied().unwrap_or(1);
        let file = github_escape_property(
            result
                .path
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| result.display_name.clone())
                .as_str(),
        );
        let message = github_escape_message("file would be reformatted by cmakefmt");
        let _ = writeln!(out, "::warning file={file},line={line}::{message}");
    }

    for failure in failures {
        let file = github_escape_property(&failure.display_name);
        let message = github_escape_message(&failure.rendered_error);
        let _ = writeln!(out, "::error file={file}::{message}");
    }

    let summary_line = github_escape_message(&render_human_summary(summary));
    let _ = writeln!(out, "::notice::{summary_line}");
    out
}

fn build_checkstyle_report(results: &[ProcessedTarget], failures: &[FailedTarget]) -> String {
    let mut out = String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    out.push_str("<checkstyle version=\"4.3\">\n");

    for result in results {
        if !result.would_change {
            continue;
        }
        let path = xml_escape(
            result
                .path
                .as_ref()
                .map(|path| path.display().to_string())
                .unwrap_or_else(|| result.display_name.clone())
                .as_str(),
        );
        let line = result.changed_lines.first().copied().unwrap_or(1);
        out.push_str(&format!("  <file name=\"{path}\">\n"));
        out.push_str(&format!(
            "    <error line=\"{line}\" severity=\"warning\" source=\"cmakefmt.format\" message=\"{}\"/>\n",
            xml_escape("file would be reformatted by cmakefmt")
        ));
        out.push_str("  </file>\n");
    }

    for failure in failures {
        let path = xml_escape(&failure.display_name);
        out.push_str(&format!("  <file name=\"{path}\">\n"));
        out.push_str(&format!(
            "    <error severity=\"error\" source=\"cmakefmt.error\" message=\"{}\"/>\n",
            xml_escape(&failure.rendered_error)
        ));
        out.push_str("  </file>\n");
    }

    out.push_str("</checkstyle>\n");
    out
}

fn build_junit_report(
    results: &[ProcessedTarget],
    failures: &[FailedTarget],
    summary: &RunSummary,
) -> String {
    let mut out = String::from("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
    out.push_str(&format!(
        "<testsuite name=\"cmakefmt\" tests=\"{}\" failures=\"{}\" errors=\"{}\">\n",
        summary.selected, summary.changed, summary.failed
    ));

    for result in results {
        out.push_str(&format!(
            "  <testcase classname=\"cmakefmt\" name=\"{}\">",
            xml_escape(&result.display_name)
        ));
        if result.would_change {
            out.push_str(&format!(
                "<failure message=\"{}\">{}</failure>",
                xml_escape("file would be reformatted by cmakefmt"),
                xml_escape(
                    result
                        .unified_diff
                        .as_deref()
                        .unwrap_or("file would be reformatted by cmakefmt")
                )
            ));
        }
        out.push_str("</testcase>\n");
    }

    for failure in failures {
        out.push_str(&format!(
            "  <testcase classname=\"cmakefmt\" name=\"{}\"><error message=\"{}\">{}</error></testcase>\n",
            xml_escape(&failure.display_name),
            xml_escape("cmakefmt failed to process the file"),
            xml_escape(&failure.rendered_error)
        ));
    }

    out.push_str("</testsuite>\n");
    out
}

fn build_sarif_report(results: &[ProcessedTarget], failures: &[FailedTarget]) -> serde_json::Value {
    let mut sarif_results = Vec::new();

    for result in results {
        if !result.would_change {
            continue;
        }

        let uri = result
            .path
            .as_ref()
            .map(|path| path.display().to_string())
            .unwrap_or_else(|| result.display_name.clone());
        sarif_results.push(serde_json::json!({
            "ruleId": "cmakefmt/would-reformat",
            "level": "warning",
            "message": { "text": "file would be reformatted by cmakefmt" },
            "locations": [{
                "physicalLocation": {
                    "artifactLocation": { "uri": uri },
                    "region": { "startLine": result.changed_lines.first().copied().unwrap_or(1) }
                }
            }]
        }));
    }

    for failure in failures {
        sarif_results.push(serde_json::json!({
            "ruleId": "cmakefmt/error",
            "level": "error",
            "message": { "text": failure.rendered_error },
            "locations": [{
                "physicalLocation": {
                    "artifactLocation": { "uri": failure.display_name }
                }
            }]
        }));
    }

    serde_json::json!({
        "version": "2.1.0",
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "runs": [{
            "tool": {
                "driver": {
                    "name": "cmakefmt",
                    "informationUri": "https://github.com/cmakefmt/cmakefmt",
                    "rules": [
                        {
                            "id": "cmakefmt/would-reformat",
                            "shortDescription": { "text": "file would be reformatted" }
                        },
                        {
                            "id": "cmakefmt/error",
                            "shortDescription": { "text": "cmakefmt failed to process the file" }
                        }
                    ]
                }
            },
            "results": sarif_results
        }]
    })
}

fn github_escape_property(value: &str) -> String {
    value
        .replace('%', "%25")
        .replace('\r', "%0D")
        .replace('\n', "%0A")
}

fn github_escape_message(value: &str) -> String {
    github_escape_property(value)
}

fn xml_escape(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('"', "&quot;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('\'', "&apos;")
}

fn machine_mode_exit_code(
    results: &[ProcessedTarget],
    failures: &[FailedTarget],
    _summary: &RunSummary,
    cli: &Cli,
) -> Result<u8, cmakefmt::Error> {
    if !failures.is_empty() {
        Ok(EXIT_ERROR)
    } else if (cli.check || cli.list_changed_files) && results.iter().any(|r| r.would_change) {
        Ok(EXIT_CHECK_FAILED)
    } else {
        Ok(EXIT_OK)
    }
}

fn write_in_place_updates(results: &[ProcessedTarget]) -> Result<(), cmakefmt::Error> {
    for result in results {
        if let Some(path) = &result.path {
            if result.would_change {
                atomic_write(path, &result.formatted)?;
            }
        }
    }
    Ok(())
}

/// Write `contents` to `path` atomically by writing to a temporary file in the
/// same directory and then renaming. This prevents partial writes and avoids
/// TOCTOU races where the target could be replaced with a symlink between read
/// and write.
fn write_diff_to_stdout(result: &ProcessedTarget, colorize: bool) -> Result<(), cmakefmt::Error> {
    let diff_output = result.unified_diff.as_deref().unwrap_or_default();
    let display_output = if colorize {
        colorize_unified_diff(diff_output)
    } else {
        diff_output.to_owned()
    };
    io::stdout()
        .write_all(display_output.as_bytes())
        .map_err(cmakefmt::Error::Io)
}

fn atomic_write(path: &Path, contents: &str) -> Result<(), cmakefmt::Error> {
    let dir = path.parent().unwrap_or(Path::new("."));
    let mut tmp = tempfile::NamedTempFile::new_in(dir).map_err(cmakefmt::Error::Io)?;
    tmp.write_all(contents.as_bytes())
        .map_err(cmakefmt::Error::Io)?;
    tmp.persist(path)
        .map_err(|e| cmakefmt::Error::Io(e.error))?;
    Ok(())
}

fn print_non_human_report(
    cli: &Cli,
    results: &[ProcessedTarget],
    failures: &[FailedTarget],
    summary: &RunSummary,
) -> Result<(), cmakefmt::Error> {
    match cli.report_format {
        ReportFormat::Human => Ok(()),
        ReportFormat::Json => {
            println!(
                "{}",
                serde_json::to_string_pretty(&build_json_report(results, failures, summary, cli))
                    .map_err(|err| {
                    cmakefmt::Error::Formatter(format!("failed to build JSON report: {err}"))
                })?
            );
            Ok(())
        }
        ReportFormat::Github => {
            print!("{}", build_github_report(results, failures, summary));
            Ok(())
        }
        ReportFormat::Checkstyle => {
            print!("{}", build_checkstyle_report(results, failures));
            Ok(())
        }
        ReportFormat::Junit => {
            print!("{}", build_junit_report(results, failures, summary));
            Ok(())
        }
        ReportFormat::Sarif => {
            println!(
                "{}",
                serde_json::to_string_pretty(&build_sarif_report(results, failures)).map_err(
                    |err| cmakefmt::Error::Formatter(format!(
                        "failed to build SARIF report: {err}"
                    ))
                )?
            );
            Ok(())
        }
        ReportFormat::Edit => {
            println!(
                "{}",
                serde_json::to_string_pretty(&build_edit_report(results)).map_err(|err| {
                    cmakefmt::Error::Formatter(format!("failed to build edit report: {err}"))
                })?
            );
            Ok(())
        }
    }
}

fn build_edit_report(results: &[ProcessedTarget]) -> serde_json::Value {
    let edits: Vec<serde_json::Value> = results
        .iter()
        .filter(|r| r.would_change && !r.skipped)
        .map(|r| {
            serde_json::json!({
                "file": r.display_name,
                "replacement": r.formatted
            })
        })
        .collect();
    serde_json::json!({ "edits": edits })
}

fn should_print_human_summary(
    cli: &Cli,
    summary: &RunSummary,
    failures: &[FailedTarget],
    successful_results: usize,
) -> bool {
    if cli.report_format != ReportFormat::Human {
        return false;
    }

    let stdout_mode = !cli.list_changed_files
        && !cli.list_input_files
        && !cli.check
        && !cli.in_place
        && !cli.diff;
    if stdout_mode {
        return cli.quiet || cli.summary || !failures.is_empty();
    }

    cli.quiet
        || !failures.is_empty()
        || cli.check
        || cli.in_place
        || (cli.diff && successful_results > 1)
        || summary.selected > 1
}

fn render_human_summary(summary: &RunSummary) -> String {
    let mut rendered = format!(
        "summary: selected={}, changed={}, unchanged={}",
        summary.selected, summary.changed, summary.unchanged
    );
    if summary.skipped > 0 {
        let _ = write!(rendered, ", skipped={}", summary.skipped);
    }
    let _ = write!(rendered, ", failed={}", summary.failed);
    if summary.elapsed.as_millis() > 0 {
        let _ = write!(rendered, " in {:.2}s", summary.elapsed.as_secs_f64());
    }
    rendered
}

fn render_stat_summary(summary: &RunSummary) -> String {
    let files_word = if summary.changed == 1 {
        "file changed"
    } else {
        "files changed"
    };
    let lines_word = if summary.total_changed_lines == 1 {
        "line reformatted"
    } else {
        "lines reformatted"
    };
    format!(
        "{} {}, {} {}",
        summary.changed, files_word, summary.total_changed_lines, lines_word
    )
}

fn format_elapsed(elapsed: std::time::Duration) -> String {
    let ms = elapsed.as_millis();
    if ms == 0 {
        "<1ms".to_owned()
    } else if ms < 1000 {
        format!("{ms}ms")
    } else {
        format!("{:.2}s", elapsed.as_secs_f64())
    }
}

fn render_explain_output(
    result: &ProcessedTarget,
    progress: &ProgressReporter,
) -> Result<(), cmakefmt::Error> {
    progress.eprintln(&format!(
        "Formatting decisions for {}\n",
        result.display_name
    ))?;

    let mut found_any = false;
    for line in &result.debug_lines {
        if let Some(rest) = line.strip_prefix("formatter: ") {
            progress.eprintln(&format!("  {rest}"))?;
            found_any = true;
        }
    }

    if !found_any {
        progress.eprintln("  (no formatting decisions — file may be empty or fully disabled)")?;
    }
    progress.eprintln("")?;
    Ok(())
}

fn render_summary_line(result: &ProcessedTarget, colorize: bool) -> String {
    let display_name = &result.display_name;
    let would_change = result.would_change;
    let skipped = result.skipped;
    let skip_reason = result.skip_reason.as_deref();
    let changed_lines = result.changed_lines.len();
    let source_lines = result.source_lines;
    let formatted_lines = result.formatted_lines;
    let elapsed = result.elapsed;
    let elapsed_str = format_elapsed(elapsed);

    if skipped {
        let reason = skip_reason.unwrap_or("skipped");
        if colorize {
            return format!(
                "\u{1b}[2m-\u{1b}[0m {display_name}\n  \u{2514}\u{2500} \u{1b}[2mskipped ({reason})\u{1b}[0m"
            );
        }
        return format!("[-]  {display_name}\n     skipped ({reason})");
    }

    if would_change {
        let line_counts = if source_lines == formatted_lines {
            format!("{source_lines} lines")
        } else {
            format!("{source_lines} \u{2192} {formatted_lines} lines")
        };
        let detail = format!("{changed_lines} lines changed, {line_counts}, {elapsed_str}");
        if colorize {
            return format!("\u{1b}[1;93m!\u{1b}[0m {display_name}\n  \u{2514}\u{2500} {detail}");
        }
        return format!("[!]  {display_name}\n     {detail}");
    }

    // Unchanged
    let detail = format!("unchanged, {source_lines} lines, {elapsed_str}");
    if colorize {
        format!(
            "\u{1b}[1;92m\u{2714}\u{1b}[0m \u{1b}[2m{display_name}\u{1b}[0m\n  \u{2514}\u{2500} \u{1b}[2m{detail}\u{1b}[0m"
        )
    } else {
        format!("[ok] {display_name}\n     {detail}")
    }
}

fn render_summary_failed_line(display_name: &str, colorize: bool) -> String {
    if colorize {
        format!(
            "\u{1b}[1;91m\u{2717}\u{1b}[0m {display_name}\n  \u{2514}\u{2500} \u{1b}[91mparse error\u{1b}[0m"
        )
    } else {
        format!("[!!] {display_name}\n     parse error")
    }
}

fn describe_config_context(config_context: &ConfigContext) -> String {
    match config_context.mode {
        ConfigSourceMode::Disabled => "config sources: disabled by --no-config".to_owned(),
        ConfigSourceMode::DefaultsOnly => "config sources: defaults only".to_owned(),
        ConfigSourceMode::Explicit | ConfigSourceMode::Discovered => format!(
            "config sources: {}",
            config_context
                .sources
                .iter()
                .map(|path| path.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

fn describe_cli_overrides(cli: &Cli) -> String {
    let mut parts = Vec::new();
    if let Some(line_width) = cli.line_width {
        parts.push(format!("line_width={line_width}"));
    }
    if let Some(tab_size) = cli.tab_size {
        parts.push(format!("tab_size={tab_size}"));
    }
    if let Some(command_case) = cli.command_case {
        parts.push(format!("command_case={command_case:?}"));
    }
    if let Some(keyword_case) = cli.keyword_case {
        parts.push(format!("keyword_case={keyword_case:?}"));
    }
    if let Some(dangle_parens) = cli.dangle_parens {
        parts.push(format!("dangle_parens={dangle_parens}"));
    }

    if parts.is_empty() {
        "cli overrides: none".to_owned()
    } else {
        format!("cli overrides: {}", parts.join(", "))
    }
}

fn debug_parallel_suffix(parallel_jobs: usize) -> String {
    if parallel_jobs > 1 {
        format!(" (parallel jobs: {parallel_jobs})")
    } else {
        String::new()
    }
}

fn log_debug(message: impl AsRef<str>) {
    eprintln!("debug: {}", message.as_ref());
}

fn render_cli_error(err: &cmakefmt::Error) -> String {
    match err {
        cmakefmt::Error::Parse(parse) => render_parse_error(
            &parse.display_name,
            &parse.source_text,
            parse.start_line,
            &parse.diagnostic,
        ),
        cmakefmt::Error::Config(config) => {
            render_file_parse_error("config", &config.path, &config.details)
        }
        cmakefmt::Error::Spec(spec) => {
            render_file_parse_error("spec", &spec.path, &spec.details)
        }
        cmakefmt::Error::Formatter(message) => render_formatter_error(message),
        cmakefmt::Error::Io(source) => format!("error: I/O failure: {source}"),
        cmakefmt::Error::LayoutTooWide {
            line_no,
            width,
            limit,
        } => format!(
            "error: line {line_no} is {width} characters wide, exceeding the limit of {limit}\n\
             hint: set line_width = {width} (or higher), add the command to always_wrap, or disable require_valid_layout"
        ),
        _ => format!("error: {err}"),
    }
}

fn render_parse_error(
    display_name: &str,
    source_text: &str,
    start_line: usize,
    diagnostic: &cmakefmt::error::ParseDiagnostic,
) -> String {
    let local_line = diagnostic.line;
    let local_column = diagnostic.column;
    let absolute_line = start_line + local_line.saturating_sub(1);
    let source_lines: Vec<&str> = source_text.lines().collect();
    let line_text = source_lines
        .get(local_line.saturating_sub(1))
        .copied()
        .or_else(|| source_lines.last().copied())
        .unwrap_or_default();
    let (summary, mut hints) = classify_parse_failure(display_name, line_text, diagnostic);

    // If the error is at or near the end of the file, look for an unmatched
    // opening parenthesis. When found, show the error at the unclosed `(`
    // instead of at EOF — that's where the user needs to look.
    let is_near_eof = local_line >= source_lines.len().saturating_sub(1);
    let unmatched = if is_near_eof {
        find_unmatched_open_paren(source_text, start_line)
    } else {
        None
    };

    let mut rendered = String::new();
    if let Some((open_line, open_col, _)) = &unmatched {
        let _ = writeln!(
            rendered,
            "error: {summary}\n  --> {display_name}:{open_line}:{open_col}"
        );
        if !source_text.is_empty() {
            let open_local_line = open_line.saturating_sub(start_line) + 1;
            rendered.push('\n');
            rendered.push_str(&render_source_snippet(
                source_text,
                start_line,
                open_local_line,
                *open_col,
            ));
            rendered.push('\n');
        }
        hints.insert(0, "unclosed `(` — the closing `)` is missing".to_owned());
    } else {
        let _ = writeln!(
            rendered,
            "error: {summary}\n  --> {display_name}:{absolute_line}:{local_column}"
        );
        if !source_text.is_empty() {
            rendered.push('\n');
            rendered.push_str(&render_source_snippet(
                source_text,
                start_line,
                local_line,
                local_column,
            ));
            rendered.push('\n');
        }
    }
    for hint in hints {
        let _ = writeln!(rendered, "hint: {hint}");
    }
    let _ = writeln!(rendered, "parser detail: {}", diagnostic.message);
    if display_name != "<stdin>" {
        let _ = writeln!(rendered, "repro: cmakefmt --debug --check {display_name}");
    }
    rendered.trim_end().to_owned()
}

fn render_file_parse_error(
    kind: &str,
    path: &Path,
    source: &cmakefmt::error::FileParseError,
) -> String {
    let contents = std::fs::read_to_string(path).ok();
    let detail = source.message.as_ref();
    let mut rendered = String::new();
    let _ = writeln!(
        rendered,
        "error: invalid {kind} file ({})\n  --> {}",
        source.format,
        path.display()
    );

    if let (Some(contents), Some(line), Some(column)) =
        (contents.as_deref(), source.line, source.column)
    {
        let _ = writeln!(rendered, "      at {line}:{column}");
        rendered.push('\n');
        rendered.push_str(&render_source_snippet(contents, 1, line, column));
        rendered.push('\n');
    }

    let mut hints = Vec::new();
    if let Some((field, expected)) = extract_unknown_field_hint(detail) {
        if let Some(updated) = renamed_config_key(&field) {
            hints.push(format!(
                "`{field}` is not a valid cmakefmt key; use `{updated}` or run `cmakefmt config convert`"
            ));
        } else if let Some(suggestion) = best_match(&field, &expected) {
            hints.push(format!(
                "unknown key `{field}`; did you mean `{suggestion}`?"
            ));
        } else {
            hints.push(format!("unknown key `{field}` in {kind} file"));
        }
    }
    if kind == "config" {
        hints.push(
            "config files are applied in order; later files override earlier ones".to_owned(),
        );
    }
    for hint in hints {
        let _ = writeln!(rendered, "hint: {hint}");
    }
    let _ = writeln!(rendered, "detail: {detail}");
    rendered.trim_end().to_owned()
}

fn render_formatter_error(message: &str) -> String {
    let mut rendered = String::new();
    let _ = writeln!(rendered, "error: {message}");
    if let Some(pattern) = extract_invalid_regex_pattern(message) {
        let _ = writeln!(
            rendered,
            "hint: check the --path-regex pattern {pattern:?}; Rust regex syntax does not support every PCRE feature"
        );
    } else if message.contains("no such file or directory") {
        let _ = writeln!(
            rendered,
            "hint: pass an existing file or directory, or omit input paths to recurse from the current working directory"
        );
    }
    rendered.trim_end().to_owned()
}

/// Scan `source` for the last unmatched opening parenthesis, skipping
/// characters inside strings and comments. Returns `(line, column, context)`
/// where context is the trimmed source line containing the `(`.
fn find_unmatched_open_paren(source: &str, start_line: usize) -> Option<(usize, usize, String)> {
    // Stack of (line, column) for each unmatched '('.
    let mut paren_stack: Vec<(usize, usize)> = Vec::new();
    let mut line = 1usize;
    let mut col = 1usize;
    let chars: Vec<char> = source.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let ch = chars[i];
        match ch {
            '\n' => {
                line += 1;
                col = 1;
                i += 1;
            }
            '#' => {
                // Skip comment to end of line.
                i += 1;
                col += 1;
                while i < chars.len() && chars[i] != '\n' {
                    i += 1;
                    col += 1;
                }
            }
            '"' => {
                // Skip quoted string.
                i += 1;
                col += 1;
                while i < chars.len() {
                    if chars[i] == '\\' && i + 1 < chars.len() {
                        i += 2;
                        col += 2;
                    } else if chars[i] == '"' {
                        i += 1;
                        col += 1;
                        break;
                    } else if chars[i] == '\n' {
                        line += 1;
                        col = 1;
                        i += 1;
                    } else {
                        i += 1;
                        col += 1;
                    }
                }
            }
            '(' => {
                paren_stack.push((line, col));
                i += 1;
                col += 1;
            }
            ')' => {
                paren_stack.pop();
                i += 1;
                col += 1;
            }
            _ => {
                i += 1;
                col += 1;
            }
        }
    }

    // The last unmatched '(' is the most likely culprit.
    let (open_line, open_col) = paren_stack.last().copied()?;
    let source_lines: Vec<&str> = source.lines().collect();
    let context = source_lines
        .get(open_line.saturating_sub(1))
        .map(|l| l.trim().to_owned())
        .unwrap_or_default();
    let absolute_line = start_line + open_line.saturating_sub(1);
    Some((absolute_line, open_col, context))
}

fn classify_parse_failure(
    display_name: &str,
    line_text: &str,
    diagnostic: &cmakefmt::error::ParseDiagnostic,
) -> (String, Vec<String>) {
    let detail = diagnostic.message.as_ref();
    let trimmed = line_text.trim();
    let mut hints = Vec::new();

    if line_text.contains("\\\"") {
        hints.push(
            "possible malformed quoted argument or escaped quote sequence inside this command"
                .to_owned(),
        );
        hints.push(
            "if the caret looks late, the real problem may be earlier in the same command invocation"
                .to_owned(),
        );
        return ("failed to parse a quoted argument".to_owned(), hints);
    }

    if trimmed.contains("[=[") || trimmed.contains("[[") || trimmed.contains("]=]") {
        hints.push(
            "check that bracket argument or bracket comment delimiters use matching `=` counts"
                .to_owned(),
        );
        return (
            "failed to parse a bracket argument or comment".to_owned(),
            hints,
        );
    }

    if display_name.ends_with(".cmake.in") && trimmed.starts_with('@') && trimmed.ends_with('@') {
        hints.push("top-level configure-file placeholders like @PACKAGE_INIT@ are only valid as standalone template lines".to_owned());
        return (
            "failed to parse a configure-file template line".to_owned(),
            hints,
        );
    }

    if trimmed.contains('(') || trimmed.contains(')') {
        hints.push(
            "check for an unbalanced command invocation or control-flow condition".to_owned(),
        );
        hints.push(
            "the reported location can be after the real problem if an earlier line left the parser out of sync"
                .to_owned(),
        );
        return ("failed to parse a command invocation".to_owned(), hints);
    }

    if detail.contains("quoted element") {
        hints.push("a quoted string may be unterminated or contain malformed escapes".to_owned());
    }

    ("failed to parse CMake input".to_owned(), hints)
}

fn render_source_snippet(
    source: &str,
    start_line: usize,
    focus_line: usize,
    focus_column: usize,
) -> String {
    let lines: Vec<&str> = source.lines().collect();
    if lines.is_empty() {
        return String::new();
    }

    let focus_index = focus_line
        .saturating_sub(1)
        .min(lines.len().saturating_sub(1));
    let start_index = focus_index.saturating_sub(1);
    let end_index = (focus_index + 2).min(lines.len());
    let max_line_no = start_line + end_index.saturating_sub(1);
    let width = max_line_no.to_string().len();
    let mut rendered = String::new();

    for index in start_index..end_index {
        let absolute_line = start_line + index;
        let marker = if index == focus_index { '>' } else { ' ' };
        let _ = writeln!(
            rendered,
            "{marker} {absolute_line:>width$} | {}",
            lines[index],
            width = width
        );
        if index == focus_index {
            let visible_column = if focus_line > lines.len() {
                lines[index].chars().count() + 1
            } else {
                focus_column
            };
            let caret_padding = visible_column.saturating_sub(1);
            let _ = writeln!(
                rendered,
                "  {space:>width$} | {pad}^",
                space = "",
                pad = " ".repeat(caret_padding),
                width = width
            );
        }
    }

    rendered.trim_end().to_owned()
}

fn extract_unknown_field_hint(detail: &str) -> Option<(String, Vec<String>)> {
    let field = extract_between(detail, "unknown field `", "`")
        .or_else(|| extract_between(detail, "unknown field '", "'"))?;
    let expected = detail
        .split("expected one of")
        .nth(1)
        .map(|tail| {
            tail.split(',')
                .map(|part| {
                    part.trim()
                        .trim_matches('`')
                        .trim_matches('\'')
                        .trim_matches('"')
                        .to_owned()
                })
                .filter(|part| !part.is_empty())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    Some((field, expected))
}

fn extract_between(input: &str, start: &str, end: &str) -> Option<String> {
    let tail = input.split(start).nth(1)?;
    let field = tail.split(end).next()?;
    Some(field.to_owned())
}

fn best_match<'a>(needle: &str, candidates: &'a [String]) -> Option<&'a str> {
    candidates
        .iter()
        .filter_map(|candidate| {
            let distance = levenshtein(needle, candidate);
            (distance <= 6).then_some((distance, candidate.as_str()))
        })
        .min_by_key(|(distance, candidate)| (*distance, candidate.len()))
        .map(|(_, candidate)| candidate)
}

fn levenshtein(left: &str, right: &str) -> usize {
    let left: Vec<char> = left.chars().collect();
    let right: Vec<char> = right.chars().collect();
    let mut prev: Vec<usize> = (0..=right.len()).collect();
    let mut curr = vec![0; right.len() + 1];

    for (i, lch) in left.iter().enumerate() {
        curr[0] = i + 1;
        for (j, rch) in right.iter().enumerate() {
            let cost = usize::from(lch != rch);
            curr[j + 1] = (prev[j + 1] + 1).min(curr[j] + 1).min(prev[j] + cost);
        }
        std::mem::swap(&mut prev, &mut curr);
    }

    prev[right.len()]
}

fn renamed_config_key(key: &str) -> Option<&'static str> {
    match key {
        "use_tabchars" => Some("use_tabs"),
        "max_lines_hwrap" => Some("max_hanging_wrap_lines"),
        "max_pargs_hwrap" => Some("max_hanging_wrap_positional_args"),
        "max_subgroups_hwrap" => Some("max_hanging_wrap_groups"),
        "min_prefix_chars" => Some("min_prefix_length"),
        "max_prefix_chars" => Some("max_prefix_length"),
        "separate_ctrl_name_with_space" => Some("space_before_control_paren"),
        "separate_fn_name_with_space" => Some("space_before_definition_paren"),
        _ => None,
    }
}

fn extract_invalid_regex_pattern(message: &str) -> Option<&str> {
    let tail = message.strip_prefix("invalid file regex ")?;
    let start = tail.find('"')?;
    let end = tail[start + 1..].find('"')?;
    Some(&tail[start..=start + end + 1])
}

fn normalize_semantics(
    mut file: parser::ast::File,
    registry: &CommandRegistry,
) -> parser::ast::File {
    // Strip standalone comments and blank lines — they have no CMake semantic
    // meaning and may change structure when the formatter reflows them.
    file.statements.retain(|s| {
        !matches!(
            s,
            parser::ast::Statement::Comment(_) | parser::ast::Statement::BlankLines(_)
        )
    });

    for statement in &mut file.statements {
        match statement {
            parser::ast::Statement::Command(command) => {
                command.span = (0, 0);
                command.name.make_ascii_lowercase();
                normalize_command_literals(command);
                normalize_keyword_args(command, registry);
            }
            parser::ast::Statement::TemplatePlaceholder(value) => normalize_line_endings(value),
            parser::ast::Statement::Comment(_) | parser::ast::Statement::BlankLines(_) => {
                unreachable!()
            }
        }
    }

    file
}

fn normalize_command_literals(command: &mut parser::ast::CommandInvocation) {
    // Strip trailing and inline comments — they have no CMake semantic meaning.
    command.trailing_comment = None;
    command
        .arguments
        .retain(|a| !matches!(a, parser::ast::Argument::InlineComment(_)));

    for argument in &mut command.arguments {
        match argument {
            parser::ast::Argument::Bracket(bracket) => normalize_line_endings(&mut bracket.raw),
            parser::ast::Argument::Quoted(value) | parser::ast::Argument::Unquoted(value) => {
                normalize_line_endings(value)
            }
            parser::ast::Argument::InlineComment(_) => unreachable!(),
        }
    }
}

fn normalize_line_endings(value: &mut String) {
    if value.contains('\r') {
        *value = value.replace("\r\n", "\n");
    }
}

fn normalize_keyword_args(
    command: &mut parser::ast::CommandInvocation,
    registry: &CommandRegistry,
) {
    let spec = registry.get(&command.name);
    let first_arg = command.arguments.iter().find_map(first_arg_text);
    let form = spec.form_for(first_arg);
    let keyword_set = collect_keywords(form);

    for arg in &mut command.arguments {
        if let parser::ast::Argument::Unquoted(value) = arg {
            let upper = value.to_ascii_uppercase();
            if keyword_set.contains(upper.as_str()) {
                *value = upper;
            }
        }
    }
}

fn first_arg_text(argument: &parser::ast::Argument) -> Option<&str> {
    match argument {
        parser::ast::Argument::Quoted(_)
        | parser::ast::Argument::Bracket(_)
        | parser::ast::Argument::InlineComment(_) => None,
        parser::ast::Argument::Unquoted(value) => Some(value.as_str()),
    }
}

fn collect_keywords(form: &cmakefmt::spec::CommandForm) -> BTreeSet<String> {
    let mut keywords = BTreeSet::new();
    collect_form_keywords(form, &mut keywords);
    keywords
}

fn collect_form_keywords(form: &cmakefmt::spec::CommandForm, keywords: &mut BTreeSet<String>) {
    keywords.extend(form.flags.iter().cloned());

    for (name, spec) in &form.kwargs {
        keywords.insert(name.clone());
        collect_kwarg_keywords(spec, keywords);
    }
}

fn collect_kwarg_keywords(spec: &cmakefmt::spec::KwargSpec, keywords: &mut BTreeSet<String>) {
    keywords.extend(spec.flags.iter().cloned());

    for (name, child) in &spec.kwargs {
        keywords.insert(name.clone());
        collect_kwarg_keywords(child, keywords);
    }
}

#[cfg(test)]
mod tests {
    use clap::{CommandFactory, Parser};

    use super::{should_enable_progress_bar, streams_stdout_during_run, Cli};
    use cmakefmt::{default_config_template, default_config_template_for, DumpConfigFormat};

    #[test]
    fn dump_config_covers_config_backed_long_flags() {
        let template = default_config_template();
        let non_config_flags = [
            "check",
            "config-file",
            "color",
            "changed",
            "debug",
            "diff",
            "explain",
            "path-regex",
            "files-from",
            "generate-man-page",
            "help",
            "ignore-path",
            "keep-going",
            "cache",
            "cache-location",
            "cache-strategy",
            "lines",
            "list-changed-files",
            "list-input-files",
            "list-unknown-commands",
            "no-config",
            "no-editorconfig",
            "no-gitignore",
            "sorted",
            "parallel",
            "progress-bar",
            "quiet",
            "summary",
            "stat",
            "report-format",
            "required-version",
            "verify",
            "no-verify",
            "require-pragma",
            "since",
            "staged",
            "preview",
            "stdin-path",
            "version",
            "watch",
            "in-place",
        ];

        for arg in Cli::command().get_arguments() {
            let Some(long) = arg.get_long() else {
                continue;
            };

            if non_config_flags.contains(&long) {
                continue;
            }

            let template_key = long.replace('-', "_");
            assert!(
                template.contains(&template_key),
                "CLI flag --{long} is not represented in default_config_template(); \
                 update src/config/file.rs or add --{long} to the non-config flag allowlist in src/main.rs tests"
            );
        }
    }

    #[test]
    fn toml_dump_config_covers_config_backed_long_flags() {
        let template = default_config_template_for(DumpConfigFormat::Toml);
        for key in [
            "line_width",
            "tab_size",
            "use_tabs",
            "max_empty_lines",
            "max_hanging_wrap_lines",
            "max_hanging_wrap_positional_args",
            "max_hanging_wrap_groups",
            "dangle_parens",
            "dangle_align",
            "min_prefix_length",
            "max_prefix_length",
            "space_before_control_paren",
            "space_before_definition_paren",
            "command_case",
            "keyword_case",
        ] {
            assert!(
                template.contains(key),
                "TOML dump template is missing {key}"
            );
        }
    }

    #[test]
    fn progress_bar_policy_disables_live_stdout_on_a_terminal() {
        for args in [
            &["cmakefmt", "--progress-bar", "CMakeLists.txt"][..],
            &["cmakefmt", "--progress-bar", "--diff", "CMakeLists.txt"][..],
            &[
                "cmakefmt",
                "--progress-bar",
                "--list-changed-files",
                "CMakeLists.txt",
            ][..],
        ] {
            let cli = Cli::parse_from(args);
            assert!(streams_stdout_during_run(&cli));
            assert!(
                !should_enable_progress_bar(&cli, 2, true, true),
                "progress bar should be disabled for args: {:?}",
                args
            );
        }
    }

    #[test]
    fn progress_bar_policy_allows_non_streaming_modes_on_a_terminal() {
        for args in [
            &["cmakefmt", "--progress-bar", "--check", "CMakeLists.txt"][..],
            &["cmakefmt", "--progress-bar", "--summary", "CMakeLists.txt"][..],
            &["cmakefmt", "--progress-bar", "--quiet", "CMakeLists.txt"][..],
            &["cmakefmt", "--progress-bar", "--in-place", "CMakeLists.txt"][..],
            &[
                "cmakefmt",
                "--progress-bar",
                "--report-format",
                "json",
                "CMakeLists.txt",
            ][..],
        ] {
            let cli = Cli::parse_from(args);
            assert!(
                should_enable_progress_bar(&cli, 2, true, true),
                "progress bar should be enabled for args: {:?}",
                args
            );
        }
    }

    #[test]
    fn progress_bar_policy_allows_streaming_stdout_when_stdout_is_piped() {
        let cli = Cli::parse_from(["cmakefmt", "--progress-bar", "--diff", "CMakeLists.txt"]);
        assert!(streams_stdout_during_run(&cli));
        assert!(should_enable_progress_bar(&cli, 2, false, true));
    }

    #[test]
    fn progress_bar_policy_requires_stderr_terminal_and_multiple_targets() {
        let cli = Cli::parse_from(["cmakefmt", "--progress-bar", "--check", "CMakeLists.txt"]);
        assert!(!should_enable_progress_bar(&cli, 1, true, true));
        assert!(!should_enable_progress_bar(&cli, 2, true, false));
    }

    // ── summary rendering ──────────────────────────────────────────────────

    use super::{format_elapsed, render_summary_failed_line, render_summary_line, ProcessedTarget};
    use std::time::Duration;

    #[allow(clippy::too_many_arguments)]
    fn test_target(
        name: &str,
        would_change: bool,
        skipped: bool,
        skip_reason: Option<&str>,
        changed_lines: usize,
        source_lines: usize,
        formatted_lines: usize,
        elapsed: Duration,
    ) -> ProcessedTarget {
        ProcessedTarget {
            path: None,
            display_name: name.to_owned(),
            formatted: String::new(),
            highlighted_output: None,
            unified_diff: None,
            changed_lines: vec![0; changed_lines],
            would_change,
            skipped,
            skip_reason: skip_reason.map(str::to_owned),
            debug_lines: Vec::new(),
            source_lines,
            formatted_lines,
            elapsed,
        }
    }

    #[test]
    fn summary_changed_file_no_color() {
        let target = test_target(
            "src/CMakeLists.txt",
            true,
            false,
            None,
            12,
            84,
            86,
            Duration::from_millis(2),
        );
        let line = render_summary_line(&target, false);
        assert!(line.starts_with("[!]  src/CMakeLists.txt"));
        assert!(line.contains("12 lines changed"));
        assert!(line.contains("84 \u{2192} 86 lines"));
        assert!(line.contains("2ms"));
        assert!(line.contains('\n'));
    }

    #[test]
    fn summary_changed_file_same_line_count_no_color() {
        let target = test_target(
            "CMakeLists.txt",
            true,
            false,
            None,
            3,
            42,
            42,
            Duration::from_millis(5),
        );
        let line = render_summary_line(&target, false);
        assert!(line.contains("3 lines changed"));
        assert!(line.contains("42 lines"));
        // Should not contain an arrow when line count is unchanged
        assert!(!line.contains('\u{2192}'));
    }

    #[test]
    fn summary_unchanged_file_no_color() {
        let target = test_target(
            "tests/CMakeLists.txt",
            false,
            false,
            None,
            0,
            42,
            42,
            Duration::from_millis(1),
        );
        let line = render_summary_line(&target, false);
        assert!(line.starts_with("[ok] tests/CMakeLists.txt"));
        assert!(line.contains("unchanged"));
        assert!(line.contains("42 lines"));
        assert!(line.contains("1ms"));
    }

    #[test]
    fn summary_skipped_file_no_color() {
        let target = test_target(
            "docs/CMakeLists.txt",
            false,
            true,
            Some("missing format opt-in pragma"),
            0,
            10,
            10,
            Duration::ZERO,
        );
        let line = render_summary_line(&target, false);
        assert!(line.starts_with("[-]  docs/CMakeLists.txt"));
        assert!(line.contains("skipped (missing format opt-in pragma)"));
    }

    #[test]
    fn summary_failed_file_no_color() {
        let line = render_summary_failed_line("lib/CMakeLists.txt", false);
        assert!(line.starts_with("[!!] lib/CMakeLists.txt"));
        assert!(line.contains("parse error"));
    }

    #[test]
    fn summary_changed_file_with_color() {
        let target = test_target(
            "src/CMakeLists.txt",
            true,
            false,
            None,
            5,
            50,
            52,
            Duration::from_millis(3),
        );
        let line = render_summary_line(&target, true);
        // Bold bright yellow exclamation mark
        assert!(line.contains("\u{1b}[1;93m!\u{1b}[0m"));
        assert!(line.contains("src/CMakeLists.txt"));
        assert!(line.contains("5 lines changed"));
    }

    #[test]
    fn summary_unchanged_file_with_color() {
        let target = test_target(
            "tests/CMakeLists.txt",
            false,
            false,
            None,
            0,
            42,
            42,
            Duration::from_millis(1),
        );
        let line = render_summary_line(&target, true);
        // Bold bright green checkmark
        assert!(line.contains("\u{1b}[1;92m\u{2714}\u{1b}[0m"));
        assert!(line.contains("unchanged"));
    }

    #[test]
    fn summary_skipped_file_with_color() {
        let target = test_target(
            "docs/CMakeLists.txt",
            false,
            true,
            Some("missing pragma"),
            0,
            10,
            10,
            Duration::ZERO,
        );
        let line = render_summary_line(&target, true);
        // Dim hyphen
        assert!(line.contains("\u{1b}[2m-\u{1b}[0m"));
        assert!(line.contains("skipped (missing pragma)"));
    }

    #[test]
    fn summary_failed_file_with_color() {
        let line = render_summary_failed_line("lib/CMakeLists.txt", true);
        // Bold bright red ballot x
        assert!(line.contains("\u{2717}"));
        assert!(line.contains("\u{1b}[1;91m"));
        assert!(line.contains("parse error"));
    }

    #[test]
    fn summary_line_has_tree_branch() {
        let target = test_target(
            "CMakeLists.txt",
            true,
            false,
            None,
            1,
            10,
            10,
            Duration::from_millis(1),
        );
        let line = render_summary_line(&target, true);
        // Should contain the tree branch connector
        assert!(line.contains("\u{2514}\u{2500}"));
    }

    #[test]
    fn summary_failed_line_has_tree_branch() {
        let line = render_summary_failed_line("CMakeLists.txt", true);
        assert!(line.contains("\u{2514}\u{2500}"));
    }

    #[test]
    fn summary_no_color_uses_indentation_not_branch() {
        let target = test_target(
            "CMakeLists.txt",
            false,
            false,
            None,
            0,
            10,
            10,
            Duration::from_millis(1),
        );
        let line = render_summary_line(&target, false);
        let lines: Vec<&str> = line.split('\n').collect();
        assert_eq!(lines.len(), 2);
        assert!(lines[1].starts_with("     "));
    }

    #[test]
    fn format_elapsed_sub_millisecond() {
        assert_eq!(format_elapsed(Duration::ZERO), "<1ms");
        assert_eq!(format_elapsed(Duration::from_micros(500)), "<1ms");
    }

    #[test]
    fn format_elapsed_milliseconds() {
        assert_eq!(format_elapsed(Duration::from_millis(1)), "1ms");
        assert_eq!(format_elapsed(Duration::from_millis(42)), "42ms");
        assert_eq!(format_elapsed(Duration::from_millis(999)), "999ms");
    }

    #[test]
    fn format_elapsed_seconds() {
        assert_eq!(format_elapsed(Duration::from_millis(1000)), "1.00s");
        assert_eq!(format_elapsed(Duration::from_millis(2500)), "2.50s");
    }
}