verctl-core 0.9.2

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
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
use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};
use std::str::FromStr;
use std::{fmt, fs};

use anyhow::{Context, Result, bail, ensure};
use ctl_core::input::{FieldPath, Input};
use ctl_core::validate;
use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::value::MapAccessDeserializer;
use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Serialize, de};

use crate::driver::{CommandSpec, Driver, Format, Text};
use crate::publisher_spec::{self as publisher, PublisherSpec, RELEASE_ONLY};
use crate::{asset_rules as assets, detect};

mod artifact_table;
pub use artifact_table::ArtifactTable;

/// A driver's read or write step: a mise task or an argv.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
// ast-grep-ignore: serde-buffered-input (TODO(`VER-171`))
pub enum CommandField {
    /// A `mise run` task name.
    Mise(String),
    /// A program and its arguments, run without a shell.
    Argv(Vec<String>),
}

impl CommandField {
    fn into_spec(self) -> Result<CommandSpec> {
        match self {
            Self::Mise(task) => {
                if task.is_empty() {
                    bail!("mise task name is empty");
                }
                Ok(CommandSpec::Mise(task))
            }
            Self::Argv(argv) => {
                ensure!(!argv.is_empty(), "driver argv is empty");
                Ok(CommandSpec::Argv(argv))
            }
        }
    }
}

/// A version driver as declared, before it becomes a [`Driver`]. `format` and
/// `keys` edit the manifest in place. `read` and `write` run commands instead
/// and take precedence.
#[derive(Debug, Clone, Default, Deserialize)]
#[non_exhaustive]
pub struct DriverSpec {
    /// `toml` or `json`, edited at `keys`. `gomod` (the `// vX.Y.Z` comment on
    /// a `go.mod` module line) and `version` (a file containing only the
    /// version) take no keys.
    pub format: Option<String>,
    /// Key paths containing the version, tried in order.
    pub keys: Option<Vec<String>>,
    /// Command that takes the manifest on stdin and prints the version.
    pub read: Option<CommandField>,
    /// Command that takes the manifest on stdin and prints it with the new
    /// version.
    pub write: Option<CommandField>,
    /// Command run after the bumps, such as a lockfile refresh. Inferred from
    /// the tree for stock manifests when omitted.
    pub after: Option<String>,
}

impl DriverSpec {
    /// Build the [`Driver`]. `name` only labels the errors.
    ///
    /// # Errors
    ///
    /// Returns an error when a `read` and `write` pair has an empty mise task
    /// name or an empty argv. Without that pair, it returns an error when
    /// `format` is missing or not `toml`, `json`, `gomod`, or `version`, when
    /// `keys` is missing or empty for `toml` or `json`, or when `gomod` or
    /// `version` has `keys`.
    pub fn into_driver(self, name: &str) -> Result<Driver> {
        if let (Some(read), Some(write)) = (self.read, self.write) {
            return Ok(Driver::Command {
                read: read.into_spec()?,
                write: write.into_spec()?,
                after: self.after,
            });
        }
        let format = match self.format.as_deref() {
            Some("toml") => Format::Toml,
            Some("json") => Format::Json,
            Some(text @ ("gomod" | "version")) => {
                ensure!(
                    self.keys.is_none(),
                    "driver {name:?} has format {text}, which reads the whole file and takes no keys"
                );
                let text = if text == "gomod" {
                    Text::GoMod
                } else {
                    Text::Version
                };
                return Ok(Driver::Text {
                    text,
                    after: self.after,
                });
            }
            Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
            None => bail!("driver {name:?} needs format+keys or read+write"),
        };
        let keys = self
            .keys
            .filter(|keys| !keys.is_empty())
            .with_context(|| format!("driver {name:?} needs keys"))?;
        Ok(Driver::Path {
            format,
            keys,
            after: self.after,
        })
    }

    fn stock(name: &str) -> Option<Self> {
        match name {
            "cargo" => Some(Self {
                format: Some("toml".into()),
                keys: Some(vec![
                    "workspace.package.version".into(),
                    "package.version".into(),
                ]),
                ..Self::default()
            }),
            "npm" => Some(Self {
                format: Some("json".into()),
                keys: Some(vec!["version".into()]),
                ..Self::default()
            }),
            "pyproject" => Some(Self {
                format: Some("toml".into()),
                keys: Some(vec!["project.version".into()]),
                ..Self::default()
            }),
            "go" => Some(Self {
                format: Some("gomod".into()),
                ..Self::default()
            }),
            "version" => Some(Self {
                format: Some("version".into()),
                ..Self::default()
            }),
            _ => None,
        }
    }

    fn merge(self, over: Self) -> Self {
        Self {
            format: over.format.or(self.format),
            keys: over.keys.or(self.keys),
            read: over.read.or(self.read),
            write: over.write.or(self.write),
            after: over.after.or(self.after),
        }
    }
}

/// One released package: its manifest, how that manifest contains the version,
/// and how it is published.
#[derive(Debug, Clone, Deserialize)]
#[non_exhaustive]
// ast-grep-ignore: serde-buffered-input (TODO(`VER-171`))
pub struct PackageSpec {
    /// The name fragments, tags, and the changelog use for the package.
    pub name: String,
    /// The manifest, relative to the directory containing `.ctl/`.
    pub path: PathBuf,
    /// A `drivers` entry or stock driver name. Omit to infer it from the
    /// manifest file name.
    pub driver: Option<String>,
    /// Stock `cargo` / `bun`, a `publishers` key, or omit to infer. `none`
    /// releases the package on GitHub only: tag, Release, and assets, with no
    /// registry upload.
    pub publisher: Option<String>,
    /// Pretty noun (`crate`, `package`, `wheel`). Defaults from the publisher.
    pub noun: Option<String>,
    /// How the package is published, beyond what its manifest implies.
    ///
    /// A mapping contains options of the publisher the package resolves to,
    /// which keeps its upload command and its registry check: `verify: false`
    /// for cargo. A list replaces the whole upload command, and the registry
    /// check goes with it unless `query` is set. When omitted, the publisher
    /// runs with its defaults.
    #[serde(default)]
    pub publish: Option<Publish>,
    /// Fills the publisher's `{registry}` placeholder and is named in the plan.
    /// Empty means none.
    pub registry: Option<String>,
    /// Asks the registry whether a version is published, in place of the
    /// publisher's query or the crates.io index read. When omitted, the
    /// publisher decides; an empty list turns the check off for this package.
    pub query: Option<Vec<String>>,
    /// Package CHANGELOG.md. Defaults to next to the manifest.
    pub changelog: Option<PathBuf>,
    /// Lets this package leave `0.0.0` with a `minor` fragment, so its first
    /// release is `0.1.0`. When omitted, a package at `0.0.0` takes only
    /// `patch` and first releases `0.0.1`. Inert once the package has released.
    #[serde(default)]
    pub first_minor: bool,
    /// The tag of the candidate versions this package releases, such as `rc`:
    /// `verctl version` writes `<base>-<tag>.<count>` while it is set. When
    /// omitted, the package releases stable versions, and a current prerelease
    /// version becomes the stable one.
    pub prerelease: Option<Prerelease>,
    /// The version is on one marker line of the file, such as
    /// `# version: 1.2.0`, `// version: 1.2.0`, or `<!-- version: 1.2.0 -->`.
    /// So a file of any type can be a package, such as one reusable workflow
    /// or one script.
    ///
    /// When unset, a file is read by its stock or named driver, and a stray
    /// marker line in it means nothing. It takes no `driver` or driver fields,
    /// and with no publisher the package releases on GitHub only.
    #[serde(default)]
    pub marker: bool,
    /// The crates.io logins this package's crates must list as owners, which
    /// `check registry` proves. It replaces the top-level `owners` for this
    /// package. When omitted, the package expects the top-level list.
    pub owners: Option<Vec<String>>,
    /// Inline driver fields. They override the named driver's.
    #[serde(flatten)]
    pub spec: DriverSpec,
    /// Every key under the package that no field above reads. A struct that
    /// flattens another cannot deny unknown fields, so this map collects them
    /// and `no_unknown_package_keys` refuses the load when it contains one.
    #[serde(flatten)]
    #[expect(
        clippy::zero_sized_map_values,
        reason = "the keys are all that is read, and serde has no set to flatten into"
    )]
    unknown: BTreeMap<String, IgnoredAny>,
}

/// The tag of a candidate version: lowercase ASCII letters.
///
/// Letters keep `<tag>.<count>` a valid semver prerelease with a separate
/// numeric count, keep the tag a valid npm dist-tag, and make tags compare in
/// semver order as words do (`alpha < beta < rc`). A package's rule in
/// `a_prerelease_is_lowercase_letters` refuses any other tag at load, so a
/// tag read from a loaded config always passes [`Prerelease::is_valid`].
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(transparent)]
pub struct Prerelease(String);

impl Prerelease {
    /// A tag, or the reason `tag` is not one.
    ///
    /// # Errors
    ///
    /// Returns an error when `tag` is empty or contains anything but lowercase
    /// ASCII letters.
    pub fn new(tag: &str) -> Result<Self> {
        let tag = Self(tag.to_owned());
        ensure!(tag.is_valid(), "{}", Self::RULE);
        Ok(tag)
    }

    /// The tag as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Whether the tag is one or more lowercase ASCII letters, and neither `x`
    /// nor `latest`.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self.0.is_empty()
            && !matches!(self.0.as_str(), "x" | "latest")
            && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
    }

    /// Two words are refused besides the letter rule. npm reads `x` alone as
    /// the version range "any" and refuses it as a dist-tag. `latest` is the
    /// dist-tag every plain install resolves, so a candidate under it would
    /// reach every consumer.
    const RULE: &'static str = "a prerelease tag is lowercase ASCII letters only, such as rc, beta, or next; never x, which npm reads as a version range, and never latest, which every plain install resolves; remove digits, dots, and capitals";
}

impl PackageSpec {
    /// The upload command this package wrote in place of its publisher's.
    #[must_use]
    pub fn publish_command(&self) -> Option<&[String]> {
        match &self.publish {
            Some(Publish::Command(argv)) => Some(argv),
            Some(Publish::Options(_)) | None => None,
        }
    }

    /// The options this package wrote for its publisher.
    #[must_use]
    pub fn publish_options(&self) -> Option<&PublishOptions> {
        match &self.publish {
            Some(Publish::Options(options)) => Some(options),
            Some(Publish::Command(_)) | None => None,
        }
    }

    /// The package changelog, resolved against `root`.
    #[must_use]
    pub fn changelog_path(&self, root: &Path) -> PathBuf {
        if let Some(path) = &self.changelog {
            return root.join(path);
        }
        root.join(&self.path)
            .parent()
            .unwrap_or(root)
            .join("CHANGELOG.md")
    }

    /// The version driver. It is the stock or named driver with this package's
    /// own fields over it. A lockfile follow-up is inferred when none is set.
    ///
    /// # Errors
    ///
    /// Returns an error when the merged driver is incomplete or invalid, as
    /// described for [`DriverSpec::into_driver`]. A package whose file is
    /// not `Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, or
    /// `VERSION` needs a driver of its own.
    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
        if self.marker {
            return Ok(Driver::Text {
                text: Text::Marker,
                after: self.spec.after.clone(),
            });
        }
        let inferred = self
            .path
            .file_name()
            .and_then(|name| name.to_str())
            .and_then(stock_name_for_file);
        let driver_name = self.driver.as_deref().or(inferred);
        let mut spec = driver_name
            .and_then(|name| config.driver_spec(name))
            .unwrap_or_default();
        spec = spec.merge(self.spec.clone());
        if spec.after.is_none() {
            spec.after = detect::follow_up(&root.join(&self.path));
        }
        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
    }

    /// The version this package's file contains now, read through its driver.
    /// Every command that reads a current version reads it here, so each
    /// error shows the package and its file.
    ///
    /// # Errors
    ///
    /// Returns an error naming the package when its driver cannot be
    /// resolved, its file cannot be read, or the driver finds no version in
    /// it.
    pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
        let path = root.join(&self.path);
        let context = || format!("package {}: {}", self.name, path.display());
        let driver = self.resolve(config, root).with_context(context)?;
        let raw = driver.source(&path).with_context(context)?;
        let version = driver.read(&raw).with_context(context)?.trim().to_owned();
        Ok(Current {
            driver,
            path,
            raw,
            version,
        })
    }
}

/// Publisher options as a package wrote them: each key with its value, not
/// yet read by the publisher they belong to.
pub type PublishOptions = BTreeMap<String, serde_json::Value>;

/// What a package wrote under `publish`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Publish {
    /// Options of the publisher the package resolves to. The publisher reads
    /// them, so an option another publisher has is an error at load.
    Options(PublishOptions),
    /// The whole upload command, run in place of the publisher's.
    Command(Vec<String>),
}

/// Untagged reads both shapes and then reports "matched no variant", naming a
/// type nobody wrote. So the shape is read here and reported in the words a
/// repo uses.
const PUBLISH_SHAPES: &str =
    "a mapping of publisher options, or a list that is the whole upload command";

impl<'de> Deserialize<'de> for Publish {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(PublishVisitor)
    }
}

struct PublishVisitor;

impl<'de> Visitor<'de> for PublishVisitor {
    type Value = Publish;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{PUBLISH_SHAPES}")
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
        let mut argv = Vec::new();
        while let Some(part) = seq.next_element::<String>()? {
            argv.push(part);
        }
        Ok(Publish::Command(argv))
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
        let mut options = PublishOptions::new();
        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
            options.insert(key, value);
        }
        Ok(Publish::Options(options))
    }
}

/// A package's version as its file contains it now, from
/// [`PackageSpec::current`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Current {
    /// The driver that read the version and writes the next one.
    pub driver: Driver,
    /// The version file, joined to the repository root.
    pub path: PathBuf,
    /// The file's text: empty for a `VERSION` file that does not exist yet.
    pub raw: String,
    /// The version, trimmed.
    pub version: String,
}

/// One machine, declared once under `runners`. The key names it; this
/// is how GitHub finds it. Every label is required at once, so a three-label
/// runner is one machine carrying three labels, not three machines.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Runner {
    /// Every label at once. A machine with none cannot be found at all.
    #[garde(custom(at_least_one("label")))]
    pub labels: Vec<String>,
}

/// One job, declared under `ci`. The key names it; `runners` names the
/// machines from `runners` it runs on, one check each. No `os`/`arch`/
/// `triple`: validation runs a machine's checks, it does not cross-compile.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Job {
    /// Names from `runners` this job runs on. Omit for one `ubuntu-26.04`
    /// machine.
    pub runners: Option<Vec<String>>,
}

/// Native GitHub Release tarballs, plus the recipe every target shares. Omit
/// for libraries. Each named sub-mapping is one target.
///
/// A tarball contains the one `binary`, or the `files` packed from `dir`. Use
/// `files` when a release needs more than its binary, such as a second
/// executable, a service unit, or a licence. A target that ships other files
/// lists its own `files`, which replace the shared list for that target.
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
// ast-grep-ignore: serde-buffered-input (TODO(`VER-171`))
pub struct Assets {
    /// The binary name. Defaults to the first package's name.
    pub bin: Option<String>,
    /// Ran once per target before `build`. Stock rust recipe uses rustup.
    pub prepare: Option<Vec<String>>,
    /// How to produce the binary. Stock rust recipe is `cargo build --release`.
    pub build: Option<Vec<String>>,
    /// Path to the built binary, with `{bin}`, `{triple}`, `{os}`, and
    /// `{arch}`. Omit for `target/{triple}/release/{bin}`. Unused when `dir`
    /// and `files` specify what to pack, so it may not be set beside them.
    #[garde(custom(binary_is_not_beside_files))]
    pub binary: Option<String>,
    /// The directory `files` are packed from, relative to the directory
    /// containing `.ctl/`, with the same placeholders as `binary`. Omit, with
    /// `files`, to pack the one `binary`.
    #[serde(default)]
    #[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
    pub dir: Option<PathBuf>,
    /// Paths under `dir` packed into the tarball of every target that lists
    /// none of its own, with the same placeholders. Each keeps its place under
    /// `dir`. A directory is packed whole. Omit, with `dir`, to pack the one
    /// `binary`, or when every target lists its own.
    #[serde(default)]
    #[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
    pub files: Vec<PathBuf>,
    /// Files written from a command's output and packed into the tarball of
    /// every target beside the binary, such as a usage spec or a man page the
    /// built binary prints. Omit when the tarball contains nothing generated.
    #[serde(default)]
    #[garde(dive, custom(generated_paths_are_sound))]
    pub generated: Vec<Generated>,
    /// Every remaining sub-mapping: `assets.linux-x64` and friends. A typo'd
    /// recipe key lands here and fails as an unknown target, loudly. The
    /// map is flattened, so garde names a target's field
    /// `assets.targets.<id>`, though the file has no `targets` key.
    /// [`Config::load`] declares this field to ctl-core as flattened,
    /// so a problem names `assets.<id>` and lands on that key's line.
    #[serde(flatten)]
    #[garde(dive, custom(asset_targets_are_sound))]
    pub targets: BTreeMap<String, AssetTarget>,
}

impl Assets {
    /// The keys under `assets` that are settings, every other key being a
    /// target id. A reader that takes only the target ids of an old config
    /// leaves these out.
    pub const SETTINGS: [&'static str; 7] = [
        "bin",
        "prepare",
        "build",
        "binary",
        "dir",
        "files",
        "generated",
    ];
}

/// One file `release asset` writes from a command's output and packs into a
/// tarball. A host that installs the tarball then gets a file it cannot
/// generate at install time, such as a man page, which mise installs only from
/// a file.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Generated {
    /// Where the file lands under the directory the tarball is cut from, with
    /// `{bin}`, `{id}`, `{os}`, `{arch}`, and `{triple}`. The load checks it
    /// for each target: it stays inside the tarball, names one file, and
    /// replaces nothing the tarball packs.
    pub path: String,
    /// The command whose standard output is the file's content, run without a
    /// shell. `{binary}` is the binary the target built, or the one
    /// `--prebuilt-self` staged, and the placeholders of `path` and
    /// `{version}` are replaced too.
    #[garde(custom(at_least_one("argument")))]
    pub run: Vec<String>,
}

pub use crate::asset_rules::AssetFormat;

/// One build target: the platform it produces and the single machine that
/// builds it. One asset, one machine, so `runner` is not a list.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct AssetTarget {
    /// Name from `runners` of the machine that builds this target.
    pub runner: Option<String>,
    /// Operating system name. Defaults from a known target id.
    pub os: Option<String>,
    /// CPU architecture name. Defaults from a known target id.
    pub arch: Option<String>,
    /// Target triple. Defaults from a known target id.
    pub triple: Option<String>,
    /// Output format of this target's asset: `tar.gz` (default), `zip`, or
    /// `raw`.
    #[serde(default)]
    pub format: AssetFormat,
    /// Ran before `build` for this target alone, in place of the shared
    /// `assets.prepare`, with the same placeholders. Use it when one platform
    /// needs a toolchain the others do not, such as a musl C compiler.
    pub prepare: Option<Vec<String>>,
    /// How to produce this target's binary or asset, in place of the shared
    /// `assets.build`, with the same placeholders.
    pub build: Option<Vec<String>>,
    /// The uploaded asset's file name, with `{bin}`, `{version}`, `{os}`,
    /// `{arch}`, and `{id}`, where `{os}` renders `macos` for `darwin`.
    /// Applies to every format and cannot be set beside `tarball`.
    #[garde(inner(custom(an_asset_name)))]
    pub name: Option<String>,
    /// The tarball's file name, with `{bin}`, `{version}`, `{os}`, and
    /// `{arch}`, where `{os}` renders `macos` for `darwin`. Omit for
    /// `{bin}_{version}_{os}_{arch}.tar.gz`. Set it when two targets share an
    /// os and an arch, such as a glibc and a musl build, which would otherwise
    /// render one name.
    #[garde(inner(custom(a_tarball_name)))]
    pub tarball: Option<String>,
    /// Path to the existing file staged as-is when `format` is `raw`, relative
    /// to the repository root, with `{bin}`, `{version}`, `{id}`, `{os}`,
    /// `{arch}`, and `{triple}`. Required when `format` is `raw` and `external`
    /// is `false`.
    #[serde(default)]
    #[garde(inner(custom(inside_the_repo)))]
    pub file: Option<PathBuf>,
    /// Whether an external job builds this target outside `verctl release
    /// asset`. An external target stays in `declared` and release completeness
    /// checks, while `status --github-output` omits it from the `assets` build
    /// matrix.
    #[serde(default)]
    pub external: bool,
    /// The paths this target's archive contains under `assets.dir`, in place of
    /// `assets.files`, with the same placeholders. Use it when a platform
    /// ships other files, such as a tool that builds only on Linux. Unset,
    /// the target packs `assets.files`; an empty list would pack nothing.
    #[serde(default)]
    #[garde(
        custom(target_files_come_with_dir),
        inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
    )]
    pub files: Option<Vec<PathBuf>>,
    /// A table copied unread into this target's `[[artifact]]` entry of the
    /// packslip release.toml, such as `requires: { os_min: "11.0" }`. packslip
    /// reads and validates every key in it, so a key packslip adds later needs
    /// no verctl code. The entry's `path` is the asset's, which verctl
    /// writes, so the table sets none. Omit to add nothing to the entry.
    #[serde(default)]
    #[garde(custom(a_packslip_table))]
    pub packslip: ArtifactTable,
}

/// How the Release's packslip is made: the committed file that names what
/// ships, and whether the tarballs are attested.
///
/// A mapping, so a repository changes one part without restating the other.
/// The path form `packslip: <path>` is refused with the mapping to write.
#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Packslip {
    /// A packslip release.toml, relative to the directory containing `.ctl/`,
    /// that names what does not change per release: the executables and the
    /// resources that ship beside them. [`Config::load`] checks that git tracks
    /// the file and that it parses as a TOML table. Omit to list `assets.bin`
    /// and no resource.
    #[garde(inner(custom(inside_the_repo)))]
    pub manifest: Option<PathBuf>,
    /// How the tarballs are attested. Omit for `true`.
    pub attest: Attest,
    /// The public key that verifies a key-signed bundle: the line of the
    /// `release.pub` that `packslip keygen` wrote. packslip cannot derive it
    /// from the secret key, and the bundle carries only a hash of it. The
    /// release needs it when it signs with a key, and keyless signing ignores
    /// it. Omit when the release signs keyless.
    #[garde(inner(custom(a_public_key_line)))]
    pub pubkey: Option<String>,
}

/// A `packslip.pubkey` that has text in it.
fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
    if line.trim().is_empty() {
        return Err(garde::Error::new(
            "cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
        ));
    }
    Ok(())
}

/// The keys a `packslip` mapping reads, once its value is known to be one.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PackslipKeys {
    #[serde(default)]
    manifest: Option<PathBuf>,
    #[serde(default)]
    attest: Attest,
    #[serde(default)]
    pubkey: Option<String>,
}

impl<'de> Deserialize<'de> for Packslip {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(PackslipVisitor)
    }
}

struct PackslipVisitor;

impl<'de> Visitor<'de> for PackslipVisitor {
    type Value = Packslip;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
        Err(E::custom(format!(
            "packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
        )))
    }

    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
        let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
        Ok(Packslip {
            manifest: keys.manifest,
            attest: keys.attest,
            pubkey: keys.pubkey,
        })
    }
}

/// Where the tarballs' build provenance is attested, which the packslip
/// links by digest.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attest {
    /// The `publish` job attests the tarballs this run built.
    #[default]
    True,
    /// Each asset job attests its own tarball as it builds it, so a
    /// hand-written workflow whose jobs attest needs no step in `publish`.
    Link,
    /// Nothing is attested or linked.
    False,
}

impl Attest {
    /// The word a file, a flag, and a plan output write.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::True => "true",
            Self::Link => "link",
            Self::False => "false",
        }
    }
}

impl fmt::Display for Attest {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for Attest {
    type Err = String;

    fn from_str(word: &str) -> Result<Self, String> {
        match word {
            "true" => Ok(Self::True),
            "link" => Ok(Self::Link),
            "false" => Ok(Self::False),
            other => Err(format!(
                "packslip.attest must be true, link, or false, not {other:?}"
            )),
        }
    }
}

impl Serialize for Attest {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for Attest {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(AttestVisitor)
    }
}

struct AttestVisitor;

impl Visitor<'_> for AttestVisitor {
    type Value = Attest;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("packslip.attest: true, link, or false")
    }

    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
        Ok(if v { Attest::True } else { Attest::False })
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
        v.parse().map_err(E::custom)
    }
}

/// Release assets built from someone else's source, at that source's version,
/// such as a library built from a pinned upstream release. Mise can then
/// install it as a `github:` tool. The key is the set's `{name}`. Fragments
/// never bump it, and `release` never reads it; `status --vendored <name>`
/// plans it, and `release asset <target> --vendored <name>` builds and uploads
/// it.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Vendored {
    /// The upstream version, written by hand: `{version}` in every template.
    #[garde(
        custom(cannot_be_empty("it names the release and the archives")),
        custom(one_plain_name)
    )]
    pub version: String,
    /// Release tag, with `{name}` and `{version}`. Omit for
    /// `{name}-{version}`.
    #[serde(default = "Vendored::default_tag")]
    #[garde(
        custom(cannot_be_empty("it names the release")),
        custom(only_placeholders(&["{name}", "{version}"]))
    )]
    pub tag: String,
    /// Archive file name, with `{name}`, `{version}`, and `{id}`. Omit for
    /// `{name}-{version}-{id}.tar.gz`.
    #[serde(default = "Vendored::default_archive")]
    #[garde(
        custom(one_archive_per_target),
        custom(only_placeholders(&["{name}", "{version}", "{id}"]))
    )]
    pub archive: String,
    /// Run once per target before packing. It uses no shell, and `{name}`,
    /// `{version}`, and `{id}` are replaced. Omit when an earlier workflow step
    /// builds.
    #[serde(default)]
    pub build: Vec<String>,
    /// The directory the files are packed from, relative to the directory
    /// containing `.ctl/`, with the same placeholders.
    #[garde(custom(inside_the_repo))]
    pub dir: PathBuf,
    /// Paths under `dir` packed into the archive, each kept at its place under
    /// `dir`. A directory is packed whole.
    #[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
    pub files: Vec<PathBuf>,
    /// The Release body, a file relative to the directory containing `.ctl/`.
    /// Omit for a Release with no body.
    #[garde(inner(custom(inside_the_repo)))]
    pub notes: Option<PathBuf>,
    /// One entry per platform; the key is `{id}`, such as `linux-x64`.
    #[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
    pub targets: BTreeMap<String, VendoredTarget>,
}

impl Vendored {
    fn default_tag() -> String {
        "{name}-{version}".to_owned()
    }

    fn default_archive() -> String {
        "{name}-{version}-{id}.tar.gz".to_owned()
    }
}

/// One platform of a vendored set and the single machine that builds it.
#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct VendoredTarget {
    /// Name from `runners` of the machine that builds this target. verctl
    /// has no built-in vendored platform, so there is no default machine.
    #[garde(custom(runner_is_declared))]
    pub runner: String,
}

/// Two targets under one archive name would overwrite each other, and `tar
/// czf` writes only a gzipped tarball.
fn one_archive_per_target(archive: &str, config: &Config) -> garde::Result {
    validate::one_file_name(archive, config)?;
    if !archive.contains("{id}") {
        return Err(garde::Error::new(
            "must contain {id}, or every target writes the same archive",
        ));
    }
    if !archive.ends_with(".tar.gz") {
        return Err(garde::Error::new(
            "must end in .tar.gz, the only archive verctl writes",
        ));
    }
    Ok(())
}

/// A brace left after the known placeholders is a typo that would reach a tag
/// or a file name unchanged. The tag takes no `{id}`, since every target
/// uploads to one Release.
fn only_placeholders(allowed: &'static [&'static str]) -> impl Fn(&str, &Config) -> garde::Result {
    move |template, _| {
        let rest = allowed
            .iter()
            .fold(template.to_owned(), |rest, placeholder| {
                rest.replace(placeholder, "")
            });
        if rest.contains(['{', '}']) {
            return Err(garde::Error::new(format!(
                "has a '{{' or '}}' that is not {}",
                allowed.join(", ")
            )));
        }
        Ok(())
    }
}

/// `{name}`, `{version}`, and `{id}` are substituted into `archive` and
/// `dir` after the load checked those templates. A value containing a path
/// separator or a parent step would therefore move the archive or the packed
/// directory outside the repository.
fn one_plain_name(value: &str, _: &Config) -> garde::Result {
    if value.is_empty() || value == "." || value == ".." || value.contains(['/', '\\']) {
        return Err(garde::Error::new(format!(
            "{value:?} must be one plain name, with no / or \\ and not . or .."
        )));
    }
    Ok(())
}

fn every_key_is_one_plain_name<V>(map: &BTreeMap<String, V>, config: &Config) -> garde::Result {
    map.keys().try_for_each(|key| one_plain_name(key, config))
}

fn at_least_one_target(targets: &BTreeMap<String, VendoredTarget>, _: &Config) -> garde::Result {
    if targets.is_empty() {
        return Err(garde::Error::new("must declare at least one target"));
    }
    Ok(())
}

/// A target's asset file name is `{bin}`, `{version}`, `{os}`, `{arch}`, and
/// `{id}` in one plain file name.
fn an_asset_name(template: &str, config: &Config) -> garde::Result {
    validate::one_file_name(template, config)?;
    only_placeholders(&["{bin}", "{version}", "{os}", "{arch}", "{id}"])(template, config)
}

/// Cross-field rules on each declared asset target.
fn asset_targets_are_sound(targets: &BTreeMap<String, AssetTarget>, _: &Config) -> garde::Result {
    assets::targets_problem(targets)
        .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}

/// A target's tarball name is `{bin}`, `{version}`, `{os}`, and `{arch}` in a
/// plain `.tar.gz` file name, for `format: tar.gz`.
fn a_tarball_name(template: &str, config: &Config) -> garde::Result {
    validate::one_file_name(template, config)?;
    only_placeholders(&["{bin}", "{version}", "{os}", "{arch}"])(template, config)?;
    if !template.ends_with(".tar.gz") {
        return Err(garde::Error::new(
            "must end in .tar.gz, the only archive verctl writes for tarball",
        ));
    }
    Ok(())
}

/// Two targets that render one name would overwrite each other's asset, so
/// the load names both. The built-in targets count: `linux-x64: {}` renders
/// `{bin}_{version}_linux_x64.tar.gz`.
#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
fn every_tarball_is_its_own(assets: &Option<Assets>, config: &Config) -> garde::Result {
    let Some(assets) = assets else {
        return Ok(());
    };
    let Some(package) = config.packages.first() else {
        return Ok(());
    };
    let bin = assets.bin.as_deref().unwrap_or(&package.name);
    if let Some((first, second, name)) = assets::asset_name_clash(assets, bin) {
        return Err(garde::Error::new(format!(
            "assets.{first} and assets.{second} both write {name}: set `name` on one of them"
        )));
    }
    Ok(())
}

/// The bundle is an asset of the Release that carries the tarballs, so a
/// `packslip` without a target to carry has no Release to sign.
#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
fn packslip_needs_assets(packslip: &Option<Packslip>, config: &Config) -> garde::Result {
    let has_targets = config
        .assets
        .as_ref()
        .is_some_and(|assets| !assets.targets.is_empty());
    if packslip.is_some() && !has_targets {
        return Err(garde::Error::new(
            "needs at least one assets target: the bundle is an asset of the Release that carries the tarballs",
        ));
    }
    Ok(())
}

/// The release.toml that `packslip.manifest` names, read from `path` and
/// parsed, with `named` as the path its errors show.
///
/// A manifest sets no `artifact`, since the path of an entry changes every
/// version. A target's `packslip` table replaces it.
///
/// # Errors
///
/// Returns an error when the file cannot be read, is not a TOML table, or sets
/// `artifact`.
pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
    let text = fs::read_to_string(path)
        .with_context(|| format!("packslip.manifest: read {}", named.display()))?;
    let document = text
        .parse::<toml_edit::DocumentMut>()
        .with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
    ensure!(
        !document.contains_key("artifact"),
        "packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
        named.display()
    );
    Ok(document)
}

/// The table of a target's `packslip` reaches the release.toml unread. This
/// refuses only the `path` verctl writes. The table's own parse refuses a value
/// TOML cannot express.
fn a_packslip_table(table: &ArtifactTable, _: &Config) -> garde::Result {
    if table.contains_key("path") {
        return Err(garde::Error::new(
            "sets `packslip.path`, the tarball's own path, which verctl writes: delete it",
        ));
    }
    Ok(())
}

/// Every `assets.generated` path, expanded for each target, stays inside the
/// tarball and names a file nothing else in it names.
fn generated_paths_are_sound(_: &[Generated], config: &Config) -> garde::Result {
    let Some(assets) = &config.assets else {
        return Ok(());
    };
    let Some(package) = config.packages.first() else {
        return Ok(());
    };
    let bin = assets.bin.as_deref().unwrap_or(&package.name);
    assets::generated_problem(assets, bin)
        .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
fn dir_comes_with_files(dir: &Option<PathBuf>, config: &Config) -> garde::Result {
    let packs_files = config.assets.as_ref().is_some_and(|assets| {
        if !assets.files.is_empty() {
            return true;
        }
        let mut archive_targets = assets
            .targets
            .values()
            .filter(|target| target.format != AssetFormat::Raw && !target.external)
            .peekable();
        archive_targets.peek().is_some() && archive_targets.all(|target| target.files.is_some())
    });
    if dir.is_some() && !packs_files {
        return Err(garde::Error::new(
            "must come with files, the paths packed from it, or a files list on every target",
        ));
    }
    Ok(())
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
fn target_files_come_with_dir(files: &Option<Vec<PathBuf>>, config: &Config) -> garde::Result {
    let has_dir = config
        .assets
        .as_ref()
        .is_some_and(|assets| assets.dir.is_some());
    if files.is_some() && !has_dir {
        return Err(garde::Error::new(
            "must come with assets.dir, the directory they are packed from",
        ));
    }
    Ok(())
}

fn files_come_with_dir(files: &[PathBuf], config: &Config) -> garde::Result {
    let has_dir = config
        .assets
        .as_ref()
        .is_some_and(|assets| assets.dir.is_some());
    if !files.is_empty() && !has_dir {
        return Err(garde::Error::new(
            "must come with dir, the directory they are packed from",
        ));
    }
    Ok(())
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
fn binary_is_not_beside_files(binary: &Option<String>, config: &Config) -> garde::Result {
    let (Some(_), Some(assets)) = (binary, config.assets.as_ref()) else {
        return Ok(());
    };
    if let Some(id) = assets
        .targets
        .iter()
        .find_map(|(id, target)| target.files.is_some().then_some(id))
    {
        return Err(garde::Error::new(format!(
            "must be omitted when assets.{id}.files lists what the tarball contains; list the binary in files",
        )));
    }
    if assets.dir.is_some() || !assets.files.is_empty() {
        return Err(garde::Error::new(
            "must be omitted when dir and files list what the tarball contains; list the binary in files",
        ));
    }
    Ok(())
}

fn runner_is_declared(runner: &str, config: &Config) -> garde::Result {
    if config.runners.contains_key(runner) {
        return Ok(());
    }
    let declared = config.runners.keys().cloned().collect::<Vec<_>>();
    Err(garde::Error::new(format!(
        "{runner:?} is not declared in runners ({})",
        if declared.is_empty() {
            "none declared".to_owned()
        } else {
            format!("declared: {}", declared.join(", "))
        }
    )))
}

/// A config that releases no package and vendors nothing has nothing to do.
fn something_to_release(packages: &[PackageSpec], config: &Config) -> garde::Result {
    if packages.is_empty() && config.vendored.is_empty() {
        return Err(garde::Error::new(
            "must declare at least one package, or a vendored set",
        ));
    }
    Ok(())
}

/// The whole file, and the context every rule in it is checked against. A
/// pattern is only unused, and an id only unknown, relative to the rest of the
/// config. `Config::parse` reads the shape with serde and then validates it
/// once, here, so a complaint names the field that has to change.
///
/// A section verctl does not know stops the load instead of being dropped.
/// Ignoring `pattern:` for `patterns:` would ship a release with the pins it
/// declares never rewritten.
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Self as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Config {
    /// Custom drivers by name. A stock name (`cargo`, `npm`, `pyproject`,
    /// `go`, `version`) is overridden field by field.
    #[serde(default)]
    pub drivers: BTreeMap<String, DriverSpec>,
    /// What this repo releases. Omit only when the repo declares `vendored`;
    /// a config with neither has nothing to do.
    #[serde(default)]
    #[garde(
        custom(something_to_release),
        custom(no_unknown_package_keys),
        custom(release_only_names_no_registry),
        custom(publish_options_fit_the_publisher),
        custom(python_names_its_publisher),
        custom(a_marker_names_no_driver),
        custom(a_prerelease_is_lowercase_letters),
        custom(package_owners_are_logins)
    )]
    pub packages: Vec<PackageSpec>,
    /// The crates.io logins every package's crates must list as owners, which
    /// `check registry` proves. A package's own `owners` replaces it. When
    /// omitted here and on a package, that package has no owner proof.
    #[serde(default)]
    #[garde(inner(custom(owners_are_logins)))]
    pub owners: Option<Vec<String>>,
    /// The file under `.github/workflows/` whose run publishes, which a
    /// crates.io trusted publisher entry must name for `check trust` to pass.
    /// crates.io matches the entry against the calling workflow that the OIDC
    /// token's `workflow_ref` claim names
    /// (`crates_io_trustpub/src/github/workflows.rs`), so a reusable workflow
    /// it calls does not count. When omitted, it is `release.yml`, the caller
    /// file the template renders.
    #[serde(default = "Config::default_release_workflow")]
    #[garde(custom(a_workflow_file_name))]
    pub release_workflow: String,
    /// The checks `release` and `release --dry-run` run before the first
    /// write, from `registry` and `trust`. Only registry state can change
    /// between the merge and the release, so the checks that prove anything
    /// else run before the merge and are not listed here. `trust` runs only
    /// when `VERCTL_OWNER_TOKEN` contains an owner's token, and is reported as
    /// skipped otherwise. When omitted, it is `[registry, trust]`; `[]` runs
    /// no check.
    #[serde(default = "ReleaseCheck::default_list")]
    #[garde(custom(each_release_check_once))]
    pub release_checks: Vec<ReleaseCheck>,
    /// Publish recipes by name, for a package's `publisher` to select.
    #[serde(default)]
    #[garde(custom(none_is_not_a_publisher))]
    pub publishers: BTreeMap<String, PublisherSpec>,
    /// Machines, declared once and named. Entirely repo-owned: verctl ships no
    /// built-in names.
    #[serde(default)]
    #[garde(dive)]
    pub runners: BTreeMap<String, Runner>,
    /// Release tarball recipe. Omit for libraries.
    #[serde(default)]
    #[garde(dive, custom(every_tarball_is_its_own))]
    pub assets: Option<Assets>,
    /// The packslip the Release carries. When it is set, the Release that
    /// carries the tarballs also carries `packslip.sigstore.json`, signed by
    /// the release workflow. `{}` signs a packslip that lists `assets.bin`
    /// and attests the tarballs. Omit to publish no packslip.
    #[serde(default)]
    #[garde(dive, custom(packslip_needs_assets))]
    pub packslip: Option<Packslip>,
    /// Asset sets built from someone else's source at its own version, by
    /// name. Omit when the repo vendors nothing.
    #[serde(default)]
    #[garde(custom(every_key_is_one_plain_name), dive)]
    pub vendored: BTreeMap<String, Vendored>,
    /// PR and push validation. Empty means one `verify` on `ubuntu-26.04`.
    #[serde(default)]
    pub ci: BTreeMap<String, Job>,
    /// Work done after the version bumps.
    #[serde(default)]
    #[garde(custom(no_version_label))]
    pub prepare: Prepare,
    /// The Version PR's title and commit message. Omit for
    /// `chore(release): version packages` as both.
    #[serde(default)]
    pub proposal: Proposal,
    /// Whose names changelog entries never credit. Omit to list no one.
    #[serde(default)]
    pub changelog: Changelog,
    /// Where served-file templates live. Omit for the convention.
    #[serde(default)]
    #[garde(dive)]
    pub templates: Templates,
    /// How release tags are named. Omit for `v{version}`: one tag when every
    /// released package shares a version. Put `{name}` in the template for one
    /// tag (and one Release) per package.
    #[serde(default)]
    #[garde(dive)]
    pub tags: Tags,
    /// Version spellings, named once and listed by the files that carry them,
    /// so a spelling three files share is written once.
    #[serde(default)]
    #[garde(custom(every_pattern_says_where_the_version_goes))]
    #[garde(custom(every_pattern_bounds_the_version))]
    #[garde(custom(every_pattern_is_listed))]
    pub patterns: BTreeMap<String, PinPattern>,
    /// Collocated tool pins rewritten when `package` is bumped.
    #[serde(default)]
    #[garde(dive)]
    pub pins: Vec<Pin>,
}

/// Where the version goes, said once: no placeholder is a spelling that tracks
/// nothing, two is a spelling with no single version to put anywhere.
fn every_pattern_says_where_the_version_goes(
    patterns: &BTreeMap<String, PinPattern>,
    _: &Config,
) -> garde::Result {
    for (id, pattern) in patterns {
        let found = pattern.r#match.matches(PLACEHOLDER).count();
        if found != 1 {
            return Err(garde::Error::new(format!(
                "{id}: match says {PLACEHOLDER} {found} times, and must say it once"
            )));
        }
    }
    Ok(())
}

/// Where the version starts and ends, as the pattern declares it.
/// `{version}` is a version verctl writes: digits and dots, then an optional
/// candidate prerelease `-<tag>.<count>`. Without literal text on each side
/// that a version cannot contain, the pattern could end a version early or
/// start it late.
///
/// For example, `v{version}.5x` reads `v1.2.3.5x` as 1.2.3 and keeps `.5x`
/// after the new version. The file cannot settle it, because
/// `download/v{version}-linux` against `download/v1.2.3-linux-x64.tar.gz` is a
/// correct pin of 1.2.3.
fn every_pattern_bounds_the_version(
    patterns: &BTreeMap<String, PinPattern>,
    _: &Config,
) -> garde::Result {
    for (id, pattern) in patterns {
        let Some((before, after)) = pattern.r#match.split_once(PLACEHOLDER) else {
            continue;
        };
        if after.contains(PLACEHOLDER) {
            continue;
        }
        if let Some(problem) = unbounded(before, after, pattern) {
            return Err(garde::Error::new(format!("{id}: {problem}")));
        }
    }
    Ok(())
}

/// What leaves one side of the placeholder open, if anything does.
///
/// A side's literal is the text between `{version}` and the pattern's edge on
/// that side. A version and its prerelease or build contain only digits, `.`,
/// `-`, and `+`. So the side is bounded when its literal contains some other
/// character. Under `whole_line` the line start or end bounds a side whose
/// literal is empty.
///
/// The character next to `{version}` also matters. A digit there, or a `.`
/// with a digit beyond it, lets the regex end a version early or start it
/// late. `v{version}.5x` reads `v1.2.3.5x` as 1.2.3, so that side is open.
fn unbounded(before: &str, after: &str, pattern: &PinPattern) -> Option<String> {
    let sides = [
        (
            before,
            before.chars().rev().collect::<String>(),
            "before",
            "starts",
        ),
        (after, after.to_owned(), "after", "ends"),
    ];
    for (text, outward, side, edge) in sides {
        if text.is_empty() {
            if pattern.whole_line {
                continue;
            }
            return Some(format!(
                "nothing {side} {PLACEHOLDER} marks where the version {edge}: add the text {side} it to match, or set whole_line: true"
            ));
        }
        if text
            .chars()
            .all(|next| matches!(next, '0'..='9' | '.' | '-' | '+'))
        {
            return Some(format!(
                "{text:?} {side} {PLACEHOLDER} contains only digits, '.', '-', and '+', which a version can continue into: add more of the text {side} it to match"
            ));
        }
        let mut nearest = outward.chars();
        if matches!(
            (nearest.next(), nearest.next()),
            (Some('0'..='9'), _) | (Some('.'), Some('0'..='9'))
        ) {
            return Some(format!(
                "{text:?} {side} {PLACEHOLDER} puts a digit, or a '.' and a digit, next to the version, so a longer version would match only in part: put a character other than a digit or '.' next to {PLACEHOLDER}"
            ));
        }
    }
    None
}

/// A declared pattern nothing lists is dead configuration instead of a spare.
/// It reads like a tracked spelling while no file is checked against it.
fn every_pattern_is_listed(
    patterns: &BTreeMap<String, PinPattern>,
    config: &Config,
) -> garde::Result {
    let listed: BTreeSet<&str> = config
        .pins
        .iter()
        .flat_map(|pin| pin.pattern_ids.iter().map(String::as_str))
        .collect();
    for id in patterns.keys() {
        if !listed.contains(id.as_str()) {
            return Err(garde::Error::new(format!(
                "{id:?} is declared and no pin lists it"
            )));
        }
    }
    Ok(())
}

/// A file that serves a package version and must track it.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Pin {
    /// The file, relative to the directory containing `.ctl/`.
    #[garde(custom(inside_the_repo))]
    pub file: PathBuf,
    /// A mise `[tools]` entry, in a file that parses as TOML. Its own
    /// `?ref=v…` includes move with it.
    pub tool: Option<String>,
    /// `patterns` ids this file lists, so the file a spelling belongs to is
    /// written down instead of implied by table placement.
    #[serde(default, rename = "patterns")]
    #[garde(
        custom(each_id_is_declared),
        custom(no_id_is_listed_twice),
        custom(something_to_rewrite(self.tool.as_deref()))
    )]
    pub pattern_ids: Vec<String>,
    /// The patterns those ids name, filled in by `Config::load`, the only way
    /// to build a pin that rewrites anything.
    #[serde(skip)]
    pub patterns: Vec<PinPattern>,
    /// The package whose version this file serves.
    pub package: String,
}

/// A name is only a name if something declares it. `none` names release-only
/// packages. A `publishers.none` recipe could never run, because every package
/// that names it uploads nothing.
fn none_is_not_a_publisher(
    publishers: &BTreeMap<String, PublisherSpec>,
    _: &Config,
) -> garde::Result {
    if publishers.contains_key(RELEASE_ONLY) {
        return Err(garde::Error::new(
            "publishers.none is reserved for release-only packages; rename that publisher",
        ));
    }
    Ok(())
}

/// A key under a package that nothing reads. Ignoring `publsher: none` would
/// publish a package to its registry that the file meant to release on GitHub
/// only.
fn no_unknown_package_keys(packages: &[PackageSpec], _: &Config) -> garde::Result {
    for package in packages {
        if !package.unknown.is_empty() {
            let keys: Vec<&str> = package.unknown.keys().map(String::as_str).collect();
            return Err(garde::Error::new(format!(
                "package {:?} has {} verctl does not read: {}; check the spelling",
                package.name,
                if keys.len() == 1 { "a key" } else { "keys" },
                keys.join(", ")
            )));
        }
    }
    Ok(())
}

/// The problem with an `owners` list, if it has one: a list with no login
/// proves nothing, and a login listed twice is a typo or a stale edit.
fn owners_problem(owners: &[String]) -> Option<String> {
    if owners.is_empty() {
        return Some(
            "must list at least one crates.io login; omit the key to expect no owners".to_owned(),
        );
    }
    let mut seen = BTreeSet::new();
    owners
        .iter()
        .find(|login| !seen.insert(login.as_str()))
        .map(|login| format!("lists {login:?} twice; remove one"))
}

/// The top-level `owners`, when set.
fn owners_are_logins(owners: &[String], _: &Config) -> garde::Result {
    owners_problem(owners).map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}

/// Each package's own `owners`, named as `packages[<name>].owners`, because
/// the field is on one entry of the list.
fn package_owners_are_logins(packages: &[PackageSpec], _: &Config) -> garde::Result {
    for package in packages {
        if let Some(problem) = package.owners.as_deref().and_then(owners_problem) {
            return Err(garde::Error::new(format!(
                "packages[{name}].owners {problem}",
                name = package.name
            )));
        }
    }
    Ok(())
}

/// A check `release` runs before its first write, as `release_checks` names
/// it.
///
/// Not `#[non_exhaustive]`: the release proof matches every check, so a new
/// one fails its build until it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum ReleaseCheck {
    /// `check registry`: each crates.io crate exists and lists its owners.
    Registry,
    /// `check trust`: each crates.io crate has a trusted publisher naming
    /// the repository and `release_workflow`.
    Trust,
}

impl ReleaseCheck {
    /// Every check, in the order the proof runs them.
    pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];

    /// The name `.ctl/ver.yaml` and the report use.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Registry => "registry",
            Self::Trust => "trust",
        }
    }

    /// The `release_checks` a file that sets none gets: every check.
    fn default_list() -> Vec<Self> {
        Self::ALL.to_vec()
    }
}

/// A name outside the set fails here, naming the field and the names it
/// takes. serde's own wording names neither, because a parse problem carries
/// no field path.
impl TryFrom<String> for ReleaseCheck {
    type Error = String;

    fn try_from(name: String) -> Result<Self, Self::Error> {
        Self::ALL
            .into_iter()
            .find(|check| check.name() == name)
            .ok_or_else(|| {
                format!(
                    "release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
                )
            })
    }
}

/// `release_checks` names each check once: a repeated name is a typo or a
/// stale edit.
fn each_release_check_once(checks: &[ReleaseCheck], _: &Config) -> garde::Result {
    let mut seen = BTreeSet::new();
    checks
        .iter()
        .find(|check| !seen.insert(check.name()))
        .map_or_else(
            || Ok(()),
            |check| {
                Err(garde::Error::new(format!(
                    "lists {:?} twice; remove one",
                    check.name()
                )))
            },
        )
}

/// `release_workflow` is the file name crates.io compares, so a path or a
/// file that is not a workflow could never match an entry.
fn a_workflow_file_name(name: &str, config: &Config) -> garde::Result {
    if validate::one_file_name(name, config).is_err() {
        return Err(garde::Error::new(
            "must be a file name under .github/workflows/, such as release.yml, with no directory",
        ));
    }
    if !Path::new(name)
        .extension()
        .is_some_and(|extension| extension == "yml" || extension == "yaml")
    {
        return Err(garde::Error::new(
            "must name a workflow file, ending in .yml or .yaml",
        ));
    }
    Ok(())
}

/// A candidate tag that is not lowercase ASCII letters. `rc1` would make the
/// version `0.8.0-rc1.1`, which counts on no further, and `rc.1` would hide
/// the count inside the tag.
fn a_prerelease_is_lowercase_letters(packages: &[PackageSpec], _: &Config) -> garde::Result {
    for package in packages {
        if let Some(tag) = package.prerelease.as_ref().filter(|tag| !tag.is_valid()) {
            return Err(garde::Error::new(format!(
                "package {:?} has prerelease {:?}, which is not a tag; {}",
                package.name,
                tag.as_str(),
                Prerelease::RULE
            )));
        }
    }
    Ok(())
}

/// `publisher: none`, declared or inferred from its version source, uploads
/// nothing. A registry or an upload command on the same package would be a
/// setting nothing reads.
fn release_only_names_no_registry(packages: &[PackageSpec], config: &Config) -> garde::Result {
    for package in packages {
        if publisher::publisher_name(config, package) == RELEASE_ONLY
            && (package.registry.is_some() || package.publish.is_some())
        {
            return Err(garde::Error::new(format!(
                "package {:?} has publisher: none, which uploads to no registry; remove its registry and publish",
                package.name
            )));
        }
    }
    Ok(())
}

/// An option belongs to one publisher. One the package's publisher does not
/// have would be a setting nothing reads, so it fails here, in that
/// publisher's words.
fn publish_options_fit_the_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
    for package in packages {
        if let Err(problem) = publisher::check_options(config, package) {
            return Err(garde::Error::new(problem));
        }
    }
    Ok(())
}

/// `marker: true` shows where the version is, so a `driver` or driver fields
/// beside it would be a second answer nothing reads. `after` is the
/// exception: it is what runs after the bump, not where the version is.
fn a_marker_names_no_driver(packages: &[PackageSpec], _: &Config) -> garde::Result {
    for package in packages {
        let spec = &package.spec;
        if package.marker
            && (package.driver.is_some()
                || spec.format.is_some()
                || spec.keys.is_some()
                || spec.read.is_some()
                || spec.write.is_some())
        {
            return Err(garde::Error::new(format!(
                "package {:?} has marker: true, which reads the version from its marker line; remove its driver, format, keys, read, and write",
                package.name
            )));
        }
    }
    Ok(())
}

/// verctl has no stock Python publisher, so a `pyproject.toml` package that
/// names none would release a tag while nothing reached the Python Package
/// Index. It names one, through `publisher`, `publish`, or a `publishers`
/// entry under its own name, or says `publisher: none` to release on GitHub
/// only.
fn python_names_its_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
    for package in packages {
        if package.path.file_name() == Some(OsStr::new("pyproject.toml"))
            && package.publisher.is_none()
            && package.publish_command().is_none()
            && !config.publishers.contains_key(&package.name)
        {
            return Err(garde::Error::new(format!(
                "package {:?} needs a publisher: verctl has no stock Python publisher; set publisher to a publishers entry, or to none to release on GitHub only",
                package.name
            )));
        }
    }
    Ok(())
}

fn each_id_is_declared(ids: &[String], config: &Config) -> garde::Result {
    for id in ids {
        if !config.patterns.contains_key(id) {
            return Err(garde::Error::new(format!("no patterns.{id}")));
        }
    }
    Ok(())
}

/// Listing a spelling twice does not set a count: arity belongs to the pattern.
fn no_id_is_listed_twice(ids: &[String], _: &Config) -> garde::Result {
    let mut seen = BTreeSet::new();
    for id in ids {
        if !seen.insert(id.as_str()) {
            return Err(garde::Error::new(format!("lists {id:?} twice")));
        }
    }
    Ok(())
}

/// A pin with neither a `tool` nor a pattern names a file and asks for nothing.
fn something_to_rewrite(tool: Option<&str>) -> impl Fn(&[String], &Config) -> garde::Result + '_ {
    move |ids, _| {
        if tool.is_some() || !ids.is_empty() {
            return Ok(());
        }
        Err(garde::Error::new("needs a tool or a pattern to rewrite"))
    }
}

/// The directory every ctl CLI shares, so a repo root gains one entry however
/// many of them it uses. verctl owns the files it names here and nothing else.
pub const DIR: &str = ".ctl";

/// verctl's declarations, named after the task an operator runs (`mise run
/// ver`) rather than after the crate that reads them.
pub const FILE: &str = ".ctl/ver.yaml";

/// The directory a config governs: what every `path` in it is relative to.
///
/// Declarations sit in `<root>/.ctl/`, so the directory containing the file is
/// a level too deep and its parent is the root. `-c crates/foo/.ctl/ver.yaml`
/// therefore still governs `crates/foo`. A file outside a `.ctl` directory is
/// read where it sits, which is what an ad-hoc `-c` requires.
#[must_use]
pub fn root_of(config: &Path) -> PathBuf {
    let dir = here(config.parent());
    if dir.file_name() == Some(OsStr::new(DIR)) {
        return here(dir.parent()).to_path_buf();
    }
    dir.to_path_buf()
}

fn here(path: Option<&Path>) -> &Path {
    path.filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// What a `pins` pattern puts where the version goes.
pub const PLACEHOLDER: &str = "{version}";

/// What a tag template puts where the package name goes.
pub const NAME_PLACEHOLDER: &str = "{name}";

/// How release tags are named. The arity falls out of the template: no
/// `{name}` means one tag for the release; `{name}` means one tag per package.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Tags {
    /// Literal text with `{version}` and optionally `{name}`. Defaults to
    /// `v{version}`, so a repo that writes nothing keeps today's behaviour.
    #[serde(default = "Tags::default_template")]
    #[garde(
        custom(cannot_be_empty(
            "it is the shape of every release tag, like \"v{version}\" or \"{name}@{version}\""
        )),
        custom(tag_template_placeholders)
    )]
    pub template: String,
}

impl Tags {
    fn default_template() -> String {
        format!("v{PLACEHOLDER}")
    }

    /// Whether the template names the package, so each package gets its own
    /// tag.
    #[must_use]
    pub fn uses_name(&self) -> bool {
        self.template.contains(NAME_PLACEHOLDER)
    }

    /// Substitute `{version}` and, when given, `{name}`. The load already
    /// proved those are the only braces, so a leftover `{` here is a bug.
    ///
    /// # Errors
    ///
    /// Returns an error when the template needs `{name}` and `name` is `None`,
    /// or when braces remain after substitution.
    pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
        let mut out = self.template.replace(PLACEHOLDER, version);
        if let Some(name) = name {
            out = out.replace(NAME_PLACEHOLDER, name);
        } else if out.contains(NAME_PLACEHOLDER) {
            bail!(
                "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
                self.template
            );
        }
        ensure!(
            !out.contains('{') && !out.contains('}'),
            "tags.template {:?} still has braces after substitution",
            self.template
        );
        Ok(out)
    }
}

impl Default for Tags {
    fn default() -> Self {
        Self {
            template: Self::default_template(),
        }
    }
}

/// A tag template may only say `{version}` and `{name}`, must say at least one
/// of them, and must say `{version}`. A name with no version cannot date a
/// release.
fn tag_template_placeholders(template: &str, _: &Config) -> garde::Result {
    let mut saw_version = false;
    let mut saw_name = false;
    let mut rest = template;
    while let Some(start) = rest.find('{') {
        let after = &rest[start + 1..];
        let Some(end) = after.find('}') else {
            return Err(garde::Error::new("has an opening '{' with no closing '}'"));
        };
        let name = &after[..end];
        match name {
            "version" => saw_version = true,
            "name" => saw_name = true,
            _ => {
                return Err(garde::Error::new(format!(
                    "names {{{name}}}, and the only placeholders are {PLACEHOLDER} and {NAME_PLACEHOLDER}"
                )));
            }
        }
        rest = &after[end + 1..];
    }
    if !saw_version && !saw_name {
        return Err(garde::Error::new(format!(
            "has no placeholder — put {PLACEHOLDER} where the version goes"
        )));
    }
    if !saw_version {
        return Err(garde::Error::new(format!(
            "must say {PLACEHOLDER} — a tag with only {NAME_PLACEHOLDER} cannot date a release"
        )));
    }
    let leftover = template
        .replace(PLACEHOLDER, "")
        .replace(NAME_PLACEHOLDER, "");
    if leftover.contains('{') || leftover.contains('}') {
        return Err(garde::Error::new(format!(
            "has a '{{' or '}}' that is not {PLACEHOLDER} or {NAME_PLACEHOLDER}"
        )));
    }
    let _ = saw_name;
    Ok(())
}

/// Where the templates for served files live, and how they are marked. The
/// defaults are the whole convention: a repo that follows it writes nothing.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Templates {
    /// The directory every template lives in, flat. Each one declares its own
    /// target, so nothing sits beside the file it generates.
    #[serde(default = "Templates::default_source")]
    #[garde(custom(inside_the_repo))]
    pub source: PathBuf,
    /// What marks a source file as a template of its target.
    #[serde(default = "Templates::default_suffix")]
    #[garde(custom(cannot_be_empty(
        "it is what marks a file in the source tree as a template, like \".jinja\""
    )))]
    pub suffix: String,
}

impl Templates {
    fn default_source() -> PathBuf {
        Path::new(DIR).join("templates")
    }

    fn default_suffix() -> String {
        ".jinja".to_owned()
    }
}

impl Default for Templates {
    fn default() -> Self {
        Self {
            source: Self::default_source(),
            suffix: Self::default_suffix(),
        }
    }
}

/// One version spelling in a file, and how often the file may say it.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PinPattern {
    /// The text around a version, `{version}` where the version is. Literal
    /// text instead of a regex, so nothing about the file's format is
    /// assumed. Exactly one placeholder, checked over `patterns` so the
    /// complaint names the id.
    ///
    /// A side is bounded when the text between `{version}` and the pattern's
    /// edge contains a character that is not a digit, `.`, `-`, or `+`. The
    /// character next to `{version}` must not be a digit, or a `.` with a
    /// digit beyond it.
    ///
    /// Under `whole_line` the line start or end bounds a side whose literal is
    /// empty. The load refuses a pattern with an open side.
    pub r#match: String,
    /// How often the file must say it. A pin that lost its only mention, or
    /// drifted to one nobody declared, fails the release rather than serving
    /// a stale version.
    #[serde(default)]
    pub occurrences: Occurrences,
    /// Whether the match is a whole line rather than text inside one.
    ///
    /// When unset, a pattern matches anywhere, which is what an inline
    /// spelling needs: `github:org/tool@1.2.3` is inside a longer line.
    ///
    /// A pattern that owns its line sets this flag instead of anchoring on
    /// whatever text happens to be next to it. The alternative is spelling the
    /// neighbour into `match`, which then breaks when the neighbour moves.
    ///
    /// The flag also makes a partial version fail instead of rewriting,
    /// because a line ending in `0.1.1_local` does not end where the version
    /// does.
    #[serde(default)]
    pub whole_line: bool,
}

/// How many times a pattern must match. A count is not always the useful
/// shape. A document whose examples come and go needs "one or more".
/// Retiring a spelling needs "none".
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub enum Occurrences {
    /// Exactly one. What a pin normally is, so it is the default.
    #[default]
    Once,
    /// One or more, however many. For a file whose mentions grow and shrink
    /// on their own, where only "still tracked" is worth asserting.
    Many,
    /// None. A spelling that must stay gone, so its return fails a release
    /// instead of being served.
    Never,
    /// Exactly this many, for a file that says it a known number of times.
    Exactly(usize),
    /// This many or more.
    AtLeast(usize),
}

/// The vocabulary, spelled out. A derived enum cannot read both shapes a repo
/// writes. An unbounded word is a plain scalar. A bound is a mapping that a
/// newtype variant would only accept as a YAML tag (`!exactly 2`).
///
/// Untagged reads both and then reports "matched no variant", naming a type
/// nobody wrote. So the arity is read here and reports errors in the words a
/// repo uses.
const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";

impl<'de> Deserialize<'de> for Occurrences {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(OccurrencesVisitor)
    }
}

struct OccurrencesVisitor;

impl<'de> Visitor<'de> for OccurrencesVisitor {
    type Value = Occurrences;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{ARITY}")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
        match v {
            "once" => Ok(Occurrences::Once),
            "many" => Ok(Occurrences::Many),
            "never" => Ok(Occurrences::Never),
            _ => Err(E::custom(format!("must be {ARITY}"))),
        }
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
        use serde::de::Error;
        let wrong = || A::Error::custom(format!("must be {ARITY}"));
        let key: String = map.next_key()?.ok_or_else(wrong)?;
        #[expect(
            clippy::map_err_ignore,
            reason = "the report names the accepted shapes; the number parse error adds nothing"
        )]
        let count: usize = map.next_value().map_err(|_| wrong())?;
        if map.next_key::<IgnoredAny>()?.is_some() {
            return Err(wrong());
        }
        match key.as_str() {
            "exactly" => Ok(Occurrences::Exactly(count)),
            "at_least" => Ok(Occurrences::AtLeast(count)),
            _ => Err(wrong()),
        }
    }
}

impl Occurrences {
    /// Whether `found` occurrences satisfy this rule.
    #[must_use]
    pub const fn allows(self, found: usize) -> bool {
        match self {
            Self::Once => found == 1,
            Self::Many => found >= 1,
            Self::Never => found == 0,
            Self::Exactly(count) => found == count,
            Self::AtLeast(count) => found >= count,
        }
    }
}

impl fmt::Display for Occurrences {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Once => f.write_str("exactly once"),
            Self::Many => f.write_str("one or more"),
            Self::Never => f.write_str("never"),
            Self::Exactly(count) => write!(f, "exactly {count} times"),
            Self::AtLeast(count) => write!(f, "{count} or more times"),
        }
    }
}

/// Whose names changelog entries never credit. Release notes credit no
/// maintainer, and only this list identifies who one is: GitHub's
/// `author_association` reads a private organization member as `CONTRIBUTOR`
/// through an App token.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Changelog {
    /// GitHub logins never credited: maintainers and the Apps that open pull
    /// requests. Omit to list no one.
    #[serde(default)]
    pub internal_authors: Vec<String>,
}

impl Changelog {
    /// Whether `login` is listed, ignoring case as GitHub logins do.
    #[must_use]
    pub fn is_internal(&self, login: &str) -> bool {
        self.internal_authors
            .iter()
            .any(|listed| listed.eq_ignore_ascii_case(login))
    }
}

/// Extra work after version bumps, committed on the Version PR.
///
/// Unknown keys fail the load, as in every other block.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Prepare {
    /// argv after all bumps (for example `["mise", "run", "version-sync"]`).
    pub after: Option<Vec<String>>,
    /// Extra paths `after` may write. Anything else dirty fails.
    #[serde(default)]
    pub stage: Vec<String>,
    /// Collect gitignored paths that match `stage`. Off by default.
    #[serde(default)]
    pub stage_ignored: bool,
    /// Removed: the Version PR is not labeled, since nothing reads the label.
    /// Kept only for files that still set it. Such a file fails the load with
    /// a message to delete it, instead of serde's bare unknown-field error.
    /// `true` when the key is present with any value, null included;
    /// absent means the file is current.
    #[serde(default, deserialize_with = "key_present")]
    version_label: bool,
}

/// Whether a key is present, whatever its value. serde reads an explicit null
/// into `Option::None`, the same as an absent key. An `Option` therefore
/// contains the same value for `version_label: ~` as for a file that never set
/// it. serde calls this only when the key is in the document.
fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
    IgnoredAny::deserialize(deserializer).map(|_| true)
}

/// The Version PR's title and commit message.
///
/// Both default to what verctl wrote before the block existed, so a
/// repository that sets neither sees the same pull request.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Proposal {
    /// The pull request title. Unset or empty means
    /// [`Proposal::DEFAULT_TITLE`].
    #[serde(default)]
    pub title: Option<String>,
    /// The commit message on the Version PR branch. Unset or empty means the
    /// resolved title.
    #[serde(default)]
    pub commit_message: Option<String>,
}

impl Proposal {
    /// The title used when `title` is unset or empty.
    pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";

    /// The resolved title: the configured one, or [`Proposal::DEFAULT_TITLE`].
    #[must_use]
    pub fn title(&self) -> &str {
        self.title
            .as_deref()
            .filter(|title| !title.is_empty())
            .unwrap_or(Self::DEFAULT_TITLE)
    }

    /// The resolved commit message: the configured one, or the title.
    #[must_use]
    pub fn commit_message(&self) -> &str {
        self.commit_message
            .as_deref()
            .filter(|message| !message.is_empty())
            .unwrap_or_else(|| self.title())
    }
}

/// `prepare.version_label` labeled the Version PR until nothing read the
/// label; a file that still sets it is told to delete it.
fn no_version_label(prepare: &Prepare, _: &Config) -> garde::Result {
    if prepare.version_label {
        return Err(garde::Error::new(
            "prepare.version_label is removed: the Version PR is no longer labeled; delete this key",
        ));
    }
    Ok(())
}

impl Config {
    /// Read and validate the file at `path`.
    ///
    /// This parses the schema and checks that any `packslip.manifest` parses
    /// as TOML. Callers inside a git checkout should use
    /// `verctl_release::forge::load_config` (or call
    /// [`Config::verify_packslip_tracked`]) to also verify that
    /// `packslip.manifest` is tracked by git.
    ///
    /// # Errors
    ///
    /// Returns an error when the file cannot be read, when its YAML does not
    /// match the schema, or when validation fails. Each complaint names the
    /// line it comes from.
    pub fn load(path: &Path) -> Result<Self> {
        let config = Self::from_input(Input::read(path)?)?;
        config.packslip_manifest_is_sound(&root_of(path))?;
        Ok(config)
    }

    /// The `packslip.manifest` must be a file git tracks, so the release
    /// workflow, which checks out the commit, reads it there, and it must
    /// parse as a TOML table. Only `load` checks: `parse` reads text in
    /// memory and has no tree to check.
    fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
        let Some(manifest) = self
            .packslip
            .as_ref()
            .and_then(|packslip| packslip.manifest.as_ref())
        else {
            return Ok(());
        };
        read_packslip_manifest(&root.join(manifest), manifest).map(drop)
    }

    /// Verify that `packslip.manifest`, when configured, is among the paths git
    /// tracks.
    ///
    /// # Errors
    ///
    /// Returns an error naming `packslip.manifest` when it is not in `tracked`.
    pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
        let Some(manifest) = self
            .packslip
            .as_ref()
            .and_then(|packslip| packslip.manifest.as_ref())
        else {
            return Ok(());
        };
        let plain = |path: &Path| {
            path.components()
                .filter(|part| !matches!(part, Component::CurDir))
                .collect::<PathBuf>()
        };
        let wanted = plain(manifest);
        let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
        ensure!(
            is_tracked,
            "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
            manifest.display()
        );
        Ok(())
    }

    /// A config from text in memory, named as the file a repo writes.
    ///
    /// # Errors
    ///
    /// Returns an error when `raw` does not match the schema or fails
    /// validation, as described for [`Config::load`].
    pub fn parse(raw: &str) -> Result<Self> {
        Self::from_input(Input::new(".ctl/ver.yaml", raw))
    }

    /// The one parse boundary. ctl-core's declared input reads the shape and
    /// validates it once against the whole document, placing each complaint
    /// on its line. A document is therefore read exactly one way.
    ///
    /// `assets.targets` is the one flattened map whose entries garde dives
    /// into, so it is declared here, and a target's problem names the path
    /// the file contains.
    fn from_input(input: Input) -> Result<Self> {
        let input = input.flattened(FieldPath::root().key("assets").key("targets"));
        let mut config: Self = input.parse()?;
        input.check(&config, &config)?;
        config.resolve_patterns();
        Ok(config)
    }

    /// Turn every pin's `patterns` ids into the patterns they name, so no
    /// consumer looks an id up again. Validation already proved every name
    /// resolves, which is why this cannot fail.
    fn resolve_patterns(&mut self) {
        let declared = self.patterns.clone();
        for pin in &mut self.pins {
            pin.patterns = pin
                .pattern_ids
                .iter()
                .filter_map(|id| declared.get(id).cloned())
                .collect();
        }
    }

    /// The `release_workflow` a file that sets none gets.
    fn default_release_workflow() -> String {
        "release.yml".to_owned()
    }

    /// The crates.io logins `package` must list as owners: its own `owners`,
    /// or else the top-level list. `None` when neither is set, so the package
    /// has no owner proof.
    #[must_use]
    pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
        package.owners.as_deref().or(self.owners.as_deref())
    }

    /// The package declared as `name`.
    ///
    /// # Errors
    ///
    /// Returns an error when no declared package has that name.
    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
        self.packages
            .iter()
            .find(|package| package.name == name)
            .with_context(|| format!("package {name:?} is not in verctl config"))
    }

    /// The spec for `name`: a stock driver, a declared one, or a declared one
    /// over the stock.
    #[must_use]
    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
        match (DriverSpec::stock(name), self.drivers.get(name)) {
            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
            (Some(stock), None) => Some(stock),
            (None, Some(over)) => Some(over.clone()),
            (None, None) => None,
        }
    }
}

fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
    match file_name {
        "Cargo.toml" => Some("cargo"),
        "package.json" => Some("npm"),
        "pyproject.toml" => Some("pyproject"),
        "go.mod" => Some("go"),
        "VERSION" => Some("version"),
        _ => None,
    }
}

/// Build a stock [`Driver`] by its built-in name (`cargo`, `npm`, `pyproject`,
/// `go`, or `version`).
///
/// # Errors
///
/// Returns an error when `name` is not a built-in driver or its specification
/// cannot be compiled.
pub fn stock_driver(name: &str) -> Result<Driver> {
    DriverSpec::stock(name)
        .with_context(|| format!("unknown stock driver {name:?}"))?
        .into_driver(name)
}

#[cfg(test)]
mod tests {
    use indoc::{formatdoc, indoc};

    use super::*;

    /// A whole config, so what is under test is what a repo actually writes.
    fn load(body: &str) -> Result<Config> {
        Config::parse(body)
    }

    /// The one package every fixture below needs, and nothing else.
    const PACKAGE: &str = indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
    "};

    /// `publisher: none` uploads nothing, so a registry or an upload command
    /// beside it fails the load instead of being ignored.
    #[test]
    fn a_release_only_package_names_no_registry() {
        let config = load(indoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                publisher: none
        "})
        .unwrap();
        assert_eq!(config.packages[0].publisher.as_deref(), Some("none"));
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            publishers:
              none:
                argv: ["true"]
        "#})
        .expect_err("publishers.none is reserved");
        assert!(
            format!("{error:#}").contains("publishers.none is reserved"),
            "{error:#}"
        );
        for extra in ["registry: crates-io", "publish: [cargo, publish]"] {
            let error = load(&formatdoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    publisher: none
                    {extra}
            "})
            .expect_err(extra);
            assert!(
                format!("{error:#}").contains("has publisher: none"),
                "{extra}: {error:#}"
            );
        }
    }

    /// `packslip` is a mapping of `manifest`, `attest` and `pubkey`, and the
    /// path form it replaced fails with the mapping to write.
    #[test]
    fn packslip_is_a_mapping_and_the_path_form_shows_it() {
        let with = |packslip: &str| {
            load(&formatdoc! {"
                {PACKAGE}
                assets:
                  linux-x64: {{}}
                packslip: {packslip}
            "})
        };
        let both = with("{ manifest: .ctl/packslip.toml, attest: link }").unwrap();
        let both = both.packslip.expect("packslip");
        assert_eq!(
            both.manifest.as_deref(),
            Some(Path::new(".ctl/packslip.toml"))
        );
        assert_eq!(both.attest, Attest::Link);
        let off = with("{ attest: false }")
            .unwrap()
            .packslip
            .expect("packslip");
        assert_eq!((off.manifest, off.attest), (None, Attest::False));
        let empty = with("{}").unwrap().packslip.expect("packslip");
        assert_eq!(
            (empty.manifest, empty.attest, empty.pubkey),
            (None, Attest::True, None)
        );
        let keyed = with("{ pubkey: RWQexample }")
            .unwrap()
            .packslip
            .expect("packslip");
        assert_eq!(keyed.pubkey.as_deref(), Some("RWQexample"));
        let report = format!("{:#}", with(".ctl/packslip.toml").expect_err("path form"));
        assert!(
            report.contains("packslip: { manifest: .ctl/packslip.toml }"),
            "{report}"
        );
    }

    /// A `pubkey` with no text in it fails the load, naming the field.
    #[test]
    fn a_blank_pubkey_fails_the_load() {
        for blank in ["''", "'  '"] {
            let error = load(&formatdoc! {"
                {PACKAGE}
                assets:
                  linux-x64: {{}}
                packslip: {{ pubkey: {blank} }}
            "})
            .expect_err(blank);
            let report = format!("{error:#}");
            assert!(report.contains("packslip.pubkey"), "{blank}: {report}");
            assert!(report.contains("cannot be empty"), "{blank}: {report}");
        }
    }

    /// An `attest` that is not `true`, `link`, or `false` names the field and
    /// the three values.
    #[test]
    fn an_unknown_attest_mode_names_the_three_values() {
        let error = load(&formatdoc! {"
            {PACKAGE}
            assets:
              linux-x64: {{}}
            packslip: {{ attest: maybe }}
        "})
        .expect_err("maybe is no mode");
        let report = format!("{error:#}");
        assert!(report.contains("packslip.attest"), "{report}");
        assert!(report.contains("true, link, or false"), "{report}");
    }

    /// A target's `packslip` table is kept as written, and renders as TOML.
    #[test]
    fn a_target_packslip_table_is_kept_unread() {
        let config = load(&formatdoc! {r#"
            {PACKAGE}
            assets:
              darwin-arm64:
                packslip:
                  requires: {{ os_min: "11.0" }}
        "#})
        .unwrap();
        let table = config.assets.expect("assets").targets["darwin-arm64"]
            .packslip
            .clone();
        assert_eq!(table.to_string(), "requires = { os_min = \"11.0\" }\n");
    }

    /// A target that sets no `packslip` has an empty table.
    #[test]
    fn a_target_without_a_packslip_table_has_an_empty_one() {
        let config = load(&formatdoc! {"
            {PACKAGE}
            assets:
              linux-x64: {{}}
        "})
        .unwrap();
        let table = &config.assets.expect("assets").targets["linux-x64"].packslip;
        assert_eq!(table.entries().count(), 0);
    }

    /// The tarball's `path` is verctl's to write, and TOML has no null.
    #[test]
    fn a_target_packslip_table_refuses_a_path_and_a_null() {
        for (key, said) in [
            ("path: elsewhere.tar.gz", "packslip.path"),
            ("requires: ~", "null has no TOML form"),
        ] {
            let error = load(&formatdoc! {"
                {PACKAGE}
                assets:
                  darwin-arm64:
                    packslip:
                      {key}
            "})
            .expect_err(key);
            let report = format!("{error:#}");
            assert!(report.contains(said), "{key}: {report}");
        }
    }

    /// A candidate tag is lowercase letters. Another spelling fails the load,
    /// naming the package and the field.
    #[test]
    fn a_prerelease_is_lowercase_letters() {
        for tag in ["rc", "alpha", "beta", "next", "canary"] {
            let config = load(&formatdoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    prerelease: {tag}
            "})
            .expect(tag);
            let spec = config.find("demo").expect("demo");
            assert_eq!(spec.prerelease.as_ref().map(Prerelease::as_str), Some(tag));
        }
        for tag in ["rc1", "RC", "rc.1", "1", "x", "latest", "\"\""] {
            let error = load(&formatdoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    prerelease: {tag}
            "})
            .expect_err(tag);
            let message = format!("{error:#}");
            assert!(
                message.contains("package \"demo\" has prerelease")
                    && message.contains("lowercase ASCII letters"),
                "{tag}: {message}"
            );
        }
    }

    /// `marker: true` already marks where the version is. A driver beside it
    /// fails the load instead of being ignored. `after` still applies.
    #[test]
    fn a_marker_names_no_driver() {
        for extra in [
            "driver: cargo",
            "format: toml",
            "keys: [project.version]",
            "read: [cat]",
            "write: [cat]",
        ] {
            let error = load(&formatdoc! {"
                packages:
                  - name: ci
                    path: ci.yml
                    marker: true
                    {extra}
            "})
            .expect_err(extra);
            assert!(
                format!("{error:#}").contains("has marker: true"),
                "{extra}: {error:#}"
            );
        }
        load(indoc! {"
            packages:
              - name: ci
                path: ci.yml
                marker: true
                after: mise run render
        "})
        .expect("after runs beside a marker");
    }

    /// No stock recipe uploads to the Python Package Index, so a Python
    /// package names its publisher, or `none`, before anything is released.
    #[test]
    fn a_python_package_names_its_publisher() {
        let error = load(indoc! {"
            packages:
              - name: demo
                path: pyproject.toml
        "})
        .expect_err("no publisher");
        assert!(
            format!("{error:#}").contains("needs a publisher"),
            "{error:#}"
        );
        for named in [
            "publisher: none",
            "publish: [uv, publish]",
            "publisher: pypi",
        ] {
            load(&formatdoc! {"
                packages:
                  - name: demo
                    path: pyproject.toml
                    {named}
                publishers:
                  pypi:
                    argv: [uv, publish]
            "})
            .unwrap_or_else(|error| panic!("{named}: {error:#}"));
        }
        load(indoc! {"
            packages:
              - name: demo
                path: pyproject.toml
            publishers:
              demo:
                argv: [uv, publish]
        "})
        .expect("a publishers entry under the package name");
    }

    /// A `path` is relative to the repository, not to the directory the
    /// declarations happen to sit in, so `.ctl` never lands in front of it.
    #[test]
    fn the_root_is_the_directory_holding_the_ctl_dir() {
        let cases = [
            (".ctl/ver.yaml", "."),
            ("crates/foo/.ctl/ver.yaml", "crates/foo"),
            ("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
            ("ver.yaml", "."),
            ("/tmp/scratch/ver.yaml", "/tmp/scratch"),
        ];
        for (config, expected) in cases {
            assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
        }
    }

    /// Every arity a repo can write, in the spelling it writes it.
    #[test]
    fn every_occurrence_form_parses_and_means_what_it_says() {
        let config = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              omitted:
                match: "a@{{version}} --"
              once:
                match: "b@{{version}} --"
                occurrences: once
              many:
                match: "c@{{version}} --"
                occurrences: many
              never:
                match: "d@{{version}} --"
                occurrences: never
              twice:
                match: "e@{{version}} --"
                occurrences: {{exactly: 2}}
              floor:
                match: "f@{{version}} --"
                occurrences: {{at_least: 2}}

            pins:
              - file: README.md
                package: demo
                patterns: [omitted, once, many, never, twice, floor]
        "#})
        .unwrap();
        let allowed: Vec<Vec<usize>> = config.pins[0]
            .patterns
            .iter()
            .map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
            .collect();
        assert_eq!(
            allowed,
            [
                vec![1],       // omitted: exactly once
                vec![1],       // once
                vec![1, 2, 3], // many
                vec![0],       // never
                vec![2],       // exactly 2
                vec![2, 3],    // at least 2
            ]
        );
    }

    /// A section verctl does not know is a typo. A typo that loads is a
    /// release that does none of what the section was meant to do.
    #[test]
    fn a_misspelled_section_stops_the_load() {
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            pattern:
              install:
                match: "demo@{{version}} --"
        "#})
        .expect_err("pattern is not a section");
        assert!(format!("{error:#}").contains("pattern"), "{error:#}");
    }

    /// A bound is one key and its number. A second key means the arity was
    /// mistyped, and falling through to whichever variant the first key
    /// satisfies would pin a count nobody wrote.
    #[test]
    fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
        let error = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              wrong:
                match: "a@{{version}} --"
                occurrences: {{exactly: 2, at_leats: 3}}

            pins:
              - file: README.md
                package: demo
                patterns: [wrong]
        "#})
        .expect_err("at_leats is not a key");
        assert!(format!("{error:#}").contains(ARITY), "{error:#}");
    }

    /// A count that is not a whole number is the same mistake as a wrong
    /// key. It is reported in the same words instead of serde's.
    #[test]
    fn a_bound_with_a_bad_count_names_the_arity() {
        for count in ["-1", "many"] {
            let error = load(&formatdoc! {r#"
                {PACKAGE}
                patterns:
                  wrong:
                    match: "a@{{version}} --"
                    occurrences: {{exactly: {count}}}

                pins:
                  - file: README.md
                    package: demo
                    patterns: [wrong]
            "#})
            .expect_err("the count is not a whole number");
            assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
        }
    }

    #[test]
    fn an_unknown_arity_is_not_silently_a_default() {
        let broken = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              wrong:
                match: "a@{{version}} --"
                occurrences: sometimes

            pins:
              - file: README.md
                package: demo
                patterns: [wrong]
        "#});
        let _ = broken.expect_err("unknown occurrences");
    }

    /// One spelling, named once, carried by two files: what ids are for.
    #[test]
    fn one_named_pattern_serves_every_file_that_lists_it() {
        let config = load(&formatdoc! {r#"
            {PACKAGE}
            patterns:
              install:
                match: "demo@{{version}} --"
              mention:
                match: "v{{version}} --"
                occurrences: many

            pins:
              - file: README.md
                package: demo
                patterns: [install, mention]
              - file: docs/install.md
                package: demo
                patterns: [install]
        "#})
        .unwrap();
        let carried: Vec<Vec<&str>> = config
            .pins
            .iter()
            .map(|pin| {
                pin.patterns
                    .iter()
                    .map(|pattern| pattern.r#match.as_str())
                    .collect()
            })
            .collect();
        assert_eq!(
            carried,
            [
                vec!["demo@{version} --", "v{version} --"],
                vec!["demo@{version} --"]
            ],
            "each file carries the patterns it lists, in the order it lists them"
        );
    }

    /// Each side of `{version}` needs text a version cannot contain, or the
    /// line under `whole_line`. Every refusal names the pattern and the side.
    #[test]
    fn a_pattern_marks_where_the_version_starts_and_ends() {
        let only = "contains only digits, '.', '-', and '+'";
        let cases = [
            ("name-{version}.tar.gz", false, None),
            ("download/v{version}-linux", false, None),
            ("v{version}.tar", false, None),
            ("demo@{version} --", false, None),
            ("`demo@{version}`", false, None),
            ("verctl-{version}", true, None),
            ("version: {version}", true, None),
            ("{version}", true, None),
            (
                "{version}",
                false,
                Some("nothing before {version}".to_owned()),
            ),
            (
                "verctl-{version}",
                false,
                Some("nothing after {version}".to_owned()),
            ),
            (
                "version: {version}",
                false,
                Some("skill: nothing after {version}".to_owned()),
            ),
            (
                "verctl@{version}.",
                false,
                Some(format!("\".\" after {{version}} {only}")),
            ),
            (
                "v{version}-",
                false,
                Some(format!("\"-\" after {{version}} {only}")),
            ),
            (
                "v{version}+",
                false,
                Some(format!("\"+\" after {{version}} {only}")),
            ),
            (
                "-{version}",
                false,
                Some(format!("\"-\" before {{version}} {only}")),
            ),
            (
                "{version}.1",
                false,
                Some("nothing before {version}".to_owned()),
            ),
            (
                "{version}.1",
                true,
                Some(format!("\".1\" after {{version}} {only}")),
            ),
            (
                "version: {version}-",
                true,
                Some(format!("\"-\" after {{version}} {only}")),
            ),
        ];
        assert_bounds(cases);
    }

    /// A digit, or a `.` and a digit, next to `{version}` lets a longer version
    /// match in part, whatever the rest of the literal contains.
    #[test]
    fn a_digit_next_to_the_version_leaves_the_side_open() {
        let near = "puts a digit, or a '.' and a digit, next to the version";
        assert_bounds([
            ("v{version}.tar", false, None),
            ("v{version}-1x", false, None),
            (
                "v{version}.5x",
                false,
                Some(format!("\".5x\" after {{version}} {near}")),
            ),
            (
                "v{version}1x",
                false,
                Some(format!("\"1x\" after {{version}} {near}")),
            ),
            (
                "x1.{version}-linux",
                false,
                Some(format!("\"x1.\" before {{version}} {near}")),
            ),
            (
                "x1{version}-linux",
                false,
                Some(format!("\"x1\" before {{version}} {near}")),
            ),
            (
                "{version}.1x",
                true,
                Some(format!("\".1x\" after {{version}} {near}")),
            ),
        ]);
    }

    /// Loads one `skill` pattern per case and checks that it loads, or that
    /// the refusal names the needle.
    fn assert_bounds<const N: usize>(cases: [(&str, bool, Option<String>); N]) {
        for (text, whole_line, refusal) in cases {
            let loaded = load(&formatdoc! {"
                {PACKAGE}
                patterns:
                  skill:
                    match: '{text}'
                    whole_line: {whole_line}

                pins:
                  - file: README.md
                    package: demo
                    patterns: [skill]
            "});
            match (loaded, refusal) {
                (Ok(_), None) => {}
                (Err(error), Some(needle)) => {
                    let report = format!("{error:#}");
                    assert!(report.contains(needle.as_str()), "{text}: {report}");
                }
                (outcome, _) => panic!("{text} (whole_line: {whole_line}): {outcome:?}"),
            }
        }
    }

    /// Every rule the schema declares, each naming what a repo has to fix.
    #[test]
    #[expect(
        clippy::too_many_lines,
        reason = "one case per rule; a table, not logic"
    )]
    fn a_config_that_breaks_a_rule_stops_the_load() {
        let cases = [
            (
                "an id no patterns section declares",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}} --"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install, instal]
                "#},
                "pins[0].pattern_ids: no patterns.instal",
            ),
            (
                "the same id listed twice",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}} --"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install, install]
                "#},
                r#"pins[0].pattern_ids: lists "install" twice"#,
            ),
            (
                "a pattern no pin lists",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}} --"
                      orphan:
                        match: "old@{{version}} --"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install]
                "#},
                r#"patterns: "orphan" is declared and no pin lists it"#,
            ),
            (
                "a pin with nothing to rewrite",
                formatdoc! {"
                    {PACKAGE}
                    pins:
                      - file: README.md
                        package: demo
                "},
                "pins[0].pattern_ids: needs a tool or a pattern to rewrite",
            ),
            (
                "a spelling with nowhere to put the version",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@1.2.3"

                    pins:
                      - file: README.md
                        package: demo
                        patterns: [install]
                "#},
                "patterns: install: match says {version} 0 times",
            ),
            (
                "a pin reaching out of the repository",
                formatdoc! {r#"
                    {PACKAGE}
                    patterns:
                      install:
                        match: "demo@{{version}} --"

                    pins:
                      - file: ../elsewhere/README.md
                        package: demo
                        patterns: [install]
                "#},
                "pins[0].file: must stay inside the repository",
            ),
            (
                "a machine no label can find",
                formatdoc! {"
                    {PACKAGE}
                    runners:
                      ghost:
                        labels: []
                "},
                "runners.ghost.labels: must declare at least one label",
            ),
            (
                "a suffix that makes every file a template",
                formatdoc! {r#"
                    {PACKAGE}
                    templates:
                      suffix: ""
                "#},
                "templates.suffix: cannot be empty — it is what marks a file",
            ),
            (
                "a tag template naming a placeholder that does not exist",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "v{{ver}}"
                "#},
                "tags.template: names {ver}, and the only placeholders are {version} and {name}",
            ),
            (
                "a tag template with no placeholder",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "latest"
                "#},
                "tags.template: has no placeholder",
            ),
            (
                "a tag template with only the package name",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "{{name}}"
                "#},
                "tags.template: must say {version}",
            ),
            (
                "an empty tag template",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: ""
                "#},
                "tags.template: cannot be empty",
            ),
            (
                "a tag template with a leftover brace",
                formatdoc! {r#"
                    {PACKAGE}
                    tags:
                      template: "v{{version}}}}"
                "#},
                "tags.template: has a '{' or '}' that is not {version} or {name}",
            ),
        ];
        for (scenario, body, expected) in cases {
            let error = load(&body).expect_err(scenario);
            assert!(
                format!("{error:#}").contains(expected),
                "{scenario}: {error:#}"
            );
        }
    }

    /// A vendored set with every required key over one declared machine and
    /// no package, plus `extra` as one more key of the set.
    fn vendored(extra: &str) -> String {
        formatdoc! {"
            runners:
              linux:
                labels: [ubuntu-26.04]
            vendored:
              lib:
                version: 1.4.0
                dir: out
                files: [lib]
                targets:
                  linux-x64:
                    runner: linux
                {extra}
        "}
    }

    #[test]
    fn a_vendored_set_alone_is_a_config_and_takes_the_default_names() {
        let config = load(&vendored("")).unwrap();
        assert!(config.packages.is_empty());
        let set = &config.vendored["lib"];
        assert_eq!(set.tag, "{name}-{version}");
        assert_eq!(set.archive, "{name}-{version}-{id}.tar.gz");
        assert_eq!(set.build, Vec::<String>::new());
        assert_eq!(set.notes, None);
    }

    #[test]
    fn a_config_with_no_package_and_no_vendored_set_fails() {
        let error = load("runners: {}\n").unwrap_err();
        assert!(
            format!("{error:#}").contains("must declare at least one package, or a vendored set"),
            "{error:#}"
        );
    }

    #[test]
    fn a_vendored_set_without_targets_fails() {
        let error = load(indoc! {"
            vendored:
              lib:
                version: 1.4.0
                dir: out
                files: [lib]
                targets: {}
        "})
        .unwrap_err();
        assert!(
            format!("{error:#}").contains("must declare at least one target"),
            "{error:#}"
        );
    }

    #[test]
    fn a_vendored_set_rejects_what_it_cannot_publish() {
        let base = vendored("");
        let cases = [
            (
                "archive without the target",
                vendored("archive: lib.tar.gz"),
                "must contain {id}",
            ),
            (
                "archive in another format",
                vendored("archive: \"{id}.zip\""),
                "must end in .tar.gz",
            ),
            (
                "archive in a directory",
                vendored("archive: \"dist/{id}.tar.gz\""),
                "must be one file name",
            ),
            (
                "archive with a typo",
                vendored("archive: \"{ids}.tar.gz\""),
                "that is not {name}, {version}, {id}",
            ),
            (
                "tag that varies by target",
                vendored("tag: \"lib-{id}\""),
                "that is not {name}, {version}",
            ),
            ("empty tag", vendored("tag: \"\""), "cannot be empty"),
            (
                "notes outside the repo",
                vendored("notes: ../notes.md"),
                "must stay inside the repository",
            ),
            ("unknown key", vendored("bin: lib"), "bin"),
            (
                "empty version",
                base.replace("version: 1.4.0", "version: \"\""),
                "cannot be empty",
            ),
            (
                "dir outside the repo",
                base.replace("dir: out", "dir: /tmp"),
                "must stay inside the repository",
            ),
            (
                "no files",
                base.replace("files: [lib]", "files: []"),
                "must declare at least one file",
            ),
            (
                "a file outside the repo",
                base.replace("files: [lib]", "files: [../secret]"),
                "must stay inside the repository",
            ),
            (
                "version with a path separator",
                base.replace("version: 1.4.0", "version: 1.4/../../x"),
                "must be one plain name",
            ),
            (
                "target key with a parent step",
                base.replace("linux-x64:", "\"..\":"),
                "must be one plain name",
            ),
            (
                "target key with a path separator",
                base.replace("linux-x64:", "a/b:"),
                "must be one plain name",
            ),
            (
                "set name with a path separator",
                base.replace("  lib:", "  \"../lib\":"),
                "must be one plain name",
            ),
            (
                "undeclared machine",
                base.replace("runner: linux", "runner: big"),
                "\"big\" is not declared in runners (declared: linux)",
            ),
        ];
        for (scenario, body, expected) in cases {
            let error = load(&body).expect_err(scenario);
            assert!(
                format!("{error:#}").contains(expected),
                "{scenario}: {error:#}"
            );
        }
    }

    /// The package config followed by `section`, an `assets` mapping.
    fn assets(section: &str) -> String {
        format!("{PACKAGE}{section}")
    }

    #[test]
    fn asset_files_are_packed_from_their_dir() {
        let config = load(&assets(indoc! {"
            assets:
              dir: target/{triple}/release
              files: [demo, demod, LICENSE]
              linux-x64: {}
        "}))
        .unwrap();
        let recipe = config.assets.unwrap();
        assert_eq!(recipe.dir, Some(PathBuf::from("target/{triple}/release")));
        assert_eq!(
            recipe.files,
            [
                PathBuf::from("demo"),
                PathBuf::from("demod"),
                PathBuf::from("LICENSE")
            ]
        );
        assert_eq!(recipe.targets.keys().collect::<Vec<_>>(), ["linux-x64"]);
    }

    #[test]
    fn a_target_lists_its_own_files() {
        let config = load(&assets(indoc! {"
            assets:
              dir: out/{triple}
              darwin-arm64:
                files: [proof]
              linux-x64:
                files: [bench, proof]
        "}))
        .unwrap();
        let recipe = config.assets.unwrap();
        assert_eq!(recipe.files, Vec::<PathBuf>::new());
        assert_eq!(
            recipe.targets["darwin-arm64"].files,
            Some(vec![PathBuf::from("proof")])
        );
        assert_eq!(
            recipe.targets["linux-x64"].files,
            Some(vec![PathBuf::from("bench"), PathBuf::from("proof")])
        );
    }

    #[test]
    fn asset_files_reject_what_they_cannot_pack() {
        let cases = [
            (
                "dir without files",
                indoc! {"
                    assets:
                      dir: out
                      linux-x64: {}
                "},
                "must come with files",
            ),
            (
                "dir with no files",
                indoc! {"
                    assets:
                      dir: out
                      files: []
                      linux-x64: {}
                "},
                "must come with files",
            ),
            (
                "files without dir",
                indoc! {"
                    assets:
                      files: [demo]
                      linux-x64: {}
                "},
                "must come with dir",
            ),
            (
                "binary beside files",
                indoc! {"
                    assets:
                      binary: out/{bin}
                      dir: out
                      files: [demo]
                      linux-x64: {}
                "},
                "list the binary in files",
            ),
            (
                "dir outside the repo",
                indoc! {"
                    assets:
                      dir: /tmp
                      files: [demo]
                      linux-x64: {}
                "},
                "must stay inside the repository",
            ),
            (
                "a file outside the repo",
                indoc! {"
                    assets:
                      dir: out
                      files: [../secret]
                      linux-x64: {}
                "},
                "must stay inside the repository",
            ),
        ];
        for (scenario, section, expected) in cases {
            let error = load(&assets(section)).expect_err(scenario);
            assert!(
                format!("{error:#}").contains(expected),
                "{scenario}: {error:#}"
            );
        }
    }

    #[test]
    fn asset_target_files_reject_what_they_cannot_pack() {
        let cases = [
            (
                "target files without dir",
                indoc! {"
                    assets:
                      linux-x64:
                        files: [demo]
                "},
                "assets.linux-x64.files: must come with assets.dir",
            ),
            (
                "an empty target list",
                indoc! {"
                    assets:
                      dir: out
                      files: [demo]
                      linux-x64:
                        files: []
                "},
                "assets.linux-x64.files: must declare at least one file",
            ),
            (
                "binary beside target files",
                indoc! {"
                    assets:
                      binary: out/{bin}
                      darwin-arm64: {}
                      linux-x64:
                        files: [demo]
                "},
                "assets.binary: must be omitted when assets.linux-x64.files lists what the tarball contains",
            ),
            (
                "a target file outside the repo",
                indoc! {"
                    assets:
                      dir: out
                      linux-x64:
                        files: [../secret]
                "},
                "assets.linux-x64.files[0]: must stay inside the repository",
            ),
            (
                "dir with a target that lists no files",
                indoc! {"
                    assets:
                      dir: out
                      darwin-arm64: {}
                      linux-x64:
                        files: [demo]
                "},
                "must come with files",
            ),
        ];
        for (scenario, section, expected) in cases {
            let error = load(&assets(section)).expect_err(scenario);
            assert!(
                format!("{error:#}").contains(expected),
                "{scenario}: {error:#}"
            );
        }
    }

    /// The targets map is flattened under `assets`, so the file has no
    /// `targets` key. The problem names the path the file contains and sits on
    /// the line of `files`, the sixth after the three package lines.
    #[test]
    fn an_asset_target_problem_sits_on_its_own_line() {
        let error = load(&assets(indoc! {"
            assets:
              linux-x64:
                files: [demo]
        "}))
        .expect_err("target files without dir");
        assert!(
            format!("{error:#}")
                .contains(".ctl/ver.yaml:6:12: assets.linux-x64.files: must come with assets.dir"),
            "{error:#}"
        );
    }

    const ONE_PACKAGE: &str = indoc! {"
        packages:
          - name: demo
            path: Cargo.toml
    "};

    #[test]
    fn a_proposal_left_out_is_todays_title_and_message() {
        let config = load(ONE_PACKAGE).unwrap();
        assert_eq!(config.proposal.title(), "chore(release): version packages");
        assert_eq!(
            config.proposal.commit_message(),
            "chore(release): version packages"
        );
    }

    #[test]
    fn a_title_alone_is_also_the_commit_message() {
        let config = load(&formatdoc! {"
            {ONE_PACKAGE}proposal:
              title: 'chore: release'
        "})
        .unwrap();
        assert_eq!(config.proposal.title(), "chore: release");
        assert_eq!(config.proposal.commit_message(), "chore: release");
    }

    #[test]
    fn an_empty_title_and_message_are_unset() {
        let config = load(&formatdoc! {"
            {ONE_PACKAGE}proposal:
              title: ''
              commit_message: ''
        "})
        .unwrap();
        assert_eq!(config.proposal.title(), "chore(release): version packages");
        assert_eq!(
            config.proposal.commit_message(),
            "chore(release): version packages"
        );
    }

    #[test]
    fn a_commit_message_differs_from_the_title() {
        let config = load(&formatdoc! {"
            {ONE_PACKAGE}proposal:
              title: 'chore: release'
              commit_message: 'chore: release [skip ci]'
        "})
        .unwrap();
        assert_eq!(config.proposal.title(), "chore: release");
        assert_eq!(config.proposal.commit_message(), "chore: release [skip ci]");
    }

    #[test]
    fn a_version_label_is_refused_with_what_to_do() {
        for value in [" release", "", " ~", " null"] {
            let error = load(&formatdoc! {"
                {ONE_PACKAGE}prepare:
                  version_label:{value}
            "})
            .unwrap_err();
            let error = format!("{error:#}");
            assert!(
                error.contains("prepare.version_label is removed"),
                "{value:?}: {error}"
            );
            assert!(error.contains("no longer labeled"), "{value:?}: {error}");
            assert!(error.contains("delete this key"), "{value:?}: {error}");
        }
    }

    /// A misspelled key under a package, whether its own or a flattened
    /// driver field, fails the load and names the key and the package.
    #[test]
    fn an_unknown_key_under_a_package_fails() {
        for (line, key) in [
            ("publsher: none", "publsher"),
            ("foramt: toml", "foramt"),
            // ast-grep-ignore: no-escaped-newline (TODO(`VER-171`))
            ("keys: [package.version]\n    kes: [x]", "kes"),
        ] {
            let error = load(&formatdoc! {"
                packages:
                  - name: demo
                    path: Cargo.toml
                    {line}
            "})
            .unwrap_err();
            let error = format!("{error:#}");
            assert!(error.contains(key), "{line}: {error}");
            assert!(error.contains("\"demo\""), "{line}: {error}");
        }
        load(indoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                format: toml
                keys: [package.version]
                publisher: none
        "})
        .unwrap();
    }

    #[test]
    fn an_unknown_key_under_a_pin_fails() {
        let error = load(&formatdoc! {"
            {ONE_PACKAGE}pins:
              - file: README.md
                package: demo
                tool: github:acme/demo
                pattern: [readme]
        "})
        .unwrap_err();
        assert!(format!("{error:#}").contains("pattern"), "{error:#}");
    }

    #[test]
    fn an_unknown_key_under_a_pattern_fails() {
        let error = load(&formatdoc! {"
            {ONE_PACKAGE}patterns:
              readme:
                match: 'demo@{{version}} in CI'
                ocurrences: many
            pins:
              - file: README.md
                package: demo
                patterns: [readme]
        "})
        .unwrap_err();
        assert!(format!("{error:#}").contains("ocurrences"), "{error:#}");
    }

    #[test]
    fn an_unknown_key_under_prepare_fails() {
        let error = load(&formatdoc! {"
            {ONE_PACKAGE}prepare:
              stages: [docs]
        "})
        .unwrap_err();
        assert!(format!("{error:#}").contains("stages"), "{error:#}");
    }

    #[test]
    fn an_unknown_key_under_proposal_fails() {
        let error = load(&formatdoc! {"
            {ONE_PACKAGE}proposal:
              label: release
        "})
        .unwrap_err();
        assert!(format!("{error:#}").contains("label"), "{error:#}");
    }

    #[test]
    fn publish_reads_options_or_a_whole_command() {
        let config = load(indoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                publish:
                  verify: false
              - name: tool
                path: tool/pyproject.toml
                publish: [uv, publish]
              - name: quiet
                path: quiet/Cargo.toml
                publish: []
        "})
        .unwrap();
        let options = config.packages[0].publish_options().unwrap();
        assert_eq!(options.get("verify"), Some(&serde_json::Value::Bool(false)));
        assert_eq!(config.packages[0].publish_command(), None);
        assert_eq!(
            config.packages[1].publish_command(),
            Some(["uv".to_owned(), "publish".to_owned()].as_slice())
        );
        assert_eq!(config.packages[2].publish_command(), Some([].as_slice()));
    }

    #[test]
    fn publish_of_another_shape_names_both() {
        let error = load(indoc! {"
            packages:
              - name: demo
                path: Cargo.toml
                publish: fast
        "})
        .unwrap_err();
        assert!(
            format!("{error:#}").contains(
                "a mapping of publisher options, or a list that is the whole upload command"
            ),
            "{error:#}"
        );
    }

    /// Each option belongs to the publisher the package resolves to from the
    /// file alone, and the load names what to remove.
    #[test]
    fn options_are_checked_against_the_publisher_at_load() {
        for (yaml, message) in [
            (
                indoc! {"
                    packages:
                      - name: web
                        path: package.json
                        publish:
                          verify: false
                "},
                r#"package "web" publishes with bun, which has no publish options; remove publish.verify"#,
            ),
            (
                indoc! {"
                    packages:
                      - name: demo
                        path: Cargo.toml
                        publish:
                          allow_dirty: true
                "},
                r#"package "demo": cargo has no publish option "allow_dirty"; its options are: verify"#,
            ),
            (
                indoc! {"
                    packages:
                      - name: demo
                        path: Cargo.toml
                        publish:
                          verify: no thanks
                "},
                r#"package "demo": publish.verify is true or false"#,
            ),
            (
                indoc! {"
                    publishers:
                      cargo:
                        argv: [cargo, publish, --workspace]
                    packages:
                      - name: demo
                        path: Cargo.toml
                        publish:
                          verify: false
                "},
                r#"package "demo": publishers.cargo replaces the upload command, which takes no options; remove publish, or the argv"#,
            ),
        ] {
            let error = load(yaml).unwrap_err();
            assert!(format!("{error:#}").contains(message), "{error:#}");
        }
    }

    /// Two packages, `core` and `app`, under `top` and with `app` set to
    /// `app` (each a line of YAML, or empty).
    fn with_owners(top: &str, app: &str) -> Result<Config> {
        load(&formatdoc! {"
            {top}
            packages:
              - name: core
                path: core/Cargo.toml
              - name: app
                path: app/Cargo.toml
                {app}
        "})
    }

    /// The top-level `owners` applies to every package, and a package's own
    /// list replaces it for that package alone. With neither, a package has
    /// no owner proof.
    #[test]
    fn owners_default_to_the_top_level_list() {
        let config = with_owners("owners: [any-victor]", "").unwrap();
        for name in ["core", "app"] {
            let package = config.find(name).unwrap();
            assert_eq!(
                config.owners_of(package),
                Some(["any-victor".to_owned()].as_slice()),
                "{name}"
            );
        }
        let config = with_owners("owners: [any-victor]", "owners: [any-victor, alice]").unwrap();
        assert_eq!(
            config.owners_of(config.find("app").unwrap()),
            Some(["any-victor".to_owned(), "alice".to_owned()].as_slice())
        );
        assert_eq!(
            config.owners_of(config.find("core").unwrap()),
            Some(["any-victor".to_owned()].as_slice())
        );
        let config = with_owners("", "").unwrap();
        assert_eq!(config.owners_of(config.find("app").unwrap()), None);
    }

    /// An empty list or a login listed twice fails the load and names the
    /// field, at the top level and on a package.
    #[test]
    fn an_empty_or_repeated_owners_list_fails_naming_the_field() {
        for (top, app, expected) in [
            (
                "owners: []",
                "",
                "owners: must list at least one crates.io login",
            ),
            (
                "owners: [any-victor, any-victor]",
                "",
                r#"owners: lists "any-victor" twice"#,
            ),
            (
                "",
                "owners: []",
                "packages[app].owners must list at least one crates.io login",
            ),
            (
                "owners: [any-victor]",
                "owners: [alice, alice]",
                r#"packages[app].owners lists "alice" twice"#,
            ),
        ] {
            let error = format!("{:#}", with_owners(top, app).unwrap_err());
            assert!(error.contains(expected), "{top} {app}: {error}");
        }
    }

    /// `release_workflow` is `release.yml` when omitted, takes another file
    /// name, and refuses a path or a file that is not a workflow, naming the
    /// field.
    #[test]
    fn release_workflow_is_a_workflow_file_name() {
        assert_eq!(load(PACKAGE).unwrap().release_workflow, "release.yml");
        for name in ["self-release.yml", "publish.yaml"] {
            let config = load(&formatdoc! {"
                {PACKAGE}release_workflow: {name}
            "})
            .unwrap();
            assert_eq!(config.release_workflow, name);
        }
        for (name, problem) in [
            (
                ".github/workflows/release.yml",
                "be a file name under .github/workflows/",
            ),
            (
                "release.toml",
                "name a workflow file, ending in .yml or .yaml",
            ),
            ("\"\"", "be a file name under .github/workflows/"),
        ] {
            let error = load(&formatdoc! {"
                {PACKAGE}release_workflow: {name}
            "})
            .unwrap_err();
            let error = format!("{error:#}");
            assert!(
                error.contains(&format!("release_workflow: must {problem}")),
                "{name}: {error}"
            );
        }
    }

    /// `release_checks` is `[registry, trust]` when omitted, takes `[]` and
    /// any one name, and refuses a name listed twice or one release does not
    /// run, naming the field.
    #[test]
    fn release_checks_name_the_checks_release_runs() {
        assert_eq!(
            load(PACKAGE).unwrap().release_checks,
            [ReleaseCheck::Registry, ReleaseCheck::Trust]
        );
        for (list, expected) in [
            ("[]", [].as_slice()),
            ("[registry]", [ReleaseCheck::Registry].as_slice()),
            (
                "[trust, registry]",
                [ReleaseCheck::Trust, ReleaseCheck::Registry].as_slice(),
            ),
        ] {
            let config = load(&formatdoc! {"
                {PACKAGE}release_checks: {list}
            "})
            .unwrap();
            assert_eq!(config.release_checks, expected, "{list}");
        }
        let error = format!(
            "{:#}",
            load(&formatdoc! {"
                {PACKAGE}release_checks: [registry, registry]
            "})
            .unwrap_err()
        );
        assert!(
            error.contains(r#"release_checks: lists "registry" twice"#),
            "{error}"
        );
        let error = format!(
            "{:#}",
            load(&formatdoc! {"
                {PACKAGE}release_checks: [versions]
            "})
            .unwrap_err()
        );
        for name in ["release_checks", "versions", "registry", "trust"] {
            assert!(error.contains(name), "{name}: {error}");
        }
    }

    #[test]
    fn asset_formats_and_names_load_and_validate() {
        let config = load(&formatdoc! {"
            {PACKAGE}assets:
              linux-x64: {{}}
              darwin-arm64:
                format: zip
              macos-pkg:
                format: raw
                file: build/App.pkg
              external-pkg:
                format: raw
                external: true
                name: Other.pkg
        "})
        .unwrap();
        let targets = &config.assets.as_ref().unwrap().targets;
        assert_eq!(targets["linux-x64"].format, AssetFormat::TarGz);
        assert_eq!(targets["darwin-arm64"].format, AssetFormat::Zip);
        assert_eq!(targets["macos-pkg"].format, AssetFormat::Raw);
        assert!(!targets["macos-pkg"].external);
        assert!(targets["external-pkg"].external);
        assert_eq!(
            assets::asset_name(
                "darwin-arm64",
                &targets["darwin-arm64"],
                "demo",
                "1.2.3",
                Some("darwin"),
                Some("arm64"),
                Some("aarch64-apple-darwin"),
            ),
            Some("demo_1.2.3_macos_arm64.zip".to_owned())
        );
        assert_eq!(
            assets::asset_name(
                "macos-pkg",
                &targets["macos-pkg"],
                "demo",
                "1.2.3",
                None,
                None,
                None,
            ),
            Some("App.pkg".to_owned())
        );
        assert_eq!(
            assets::asset_name(
                "external-pkg",
                &targets["external-pkg"],
                "demo",
                "1.2.3",
                None,
                None,
                None,
            ),
            Some("Other.pkg".to_owned())
        );
    }

    #[test]
    fn invalid_asset_format_and_name_combinations_fail_load() {
        for (snippet, expected) in [
            (
                indoc! {"
                    assets:
                      linux-x64:
                        format: 7z
                "},
                "tar.gz, zip, or raw",
            ),
            (
                indoc! {"
                    assets:
                      linux-x64:
                        name: demo.tar.gz
                        tarball: demo.tar.gz
                "},
                "assets.linux-x64.tarball",
            ),
            (
                indoc! {"
                    assets:
                      macos-pkg:
                        format: raw
                        tarball: App.tar.gz
                        file: build/App.pkg
                "},
                "assets.macos-pkg.tarball",
            ),
            (
                indoc! {"
                    assets:
                      macos-pkg:
                        format: raw
                "},
                "assets.macos-pkg.file",
            ),
            (
                indoc! {"
                    assets:
                      macos-pkg:
                        format: raw
                        external: true
                "},
                "assets.macos-pkg.name",
            ),
        ] {
            let error = format!(
                "{:#}",
                load(&format!("{PACKAGE}{snippet}")).expect_err(expected)
            );
            assert!(error.contains(expected), "{snippet} | error: {error}");
        }
    }

    #[test]
    fn invalid_raw_file_and_generated_combinations_fail_load() {
        for (snippet, expected) in [
            (
                indoc! {"
                    assets:
                      linux-x64:
                        format: tar.gz
                        file: build/demo
                "},
                "assets.linux-x64.file",
            ),
            (
                indoc! {"
                    assets:
                      dir: dist
                      files: [demo]
                      macos-pkg:
                        format: raw
                        file: build/App.pkg
                        files: [App.pkg]
                "},
                "assets.macos-pkg.files",
            ),
            (
                indoc! {"
                    assets:
                      macos-pkg:
                        format: raw
                        file: ../App.pkg
                "},
                "must stay inside the repository",
            ),
            (
                indoc! {r#"
                    assets:
                      generated:
                        - path: share/usage/{bin}.kdl
                          run: ["{binary}", --usage-spec]
                      macos-pkg:
                        format: raw
                        file: build/App.pkg
                "#},
                "assets.generated",
            ),
            (
                indoc! {"
                    assets:
                      first-pkg:
                        format: raw
                        file: build/App.pkg
                      second-pkg:
                        format: raw
                        external: true
                        name: App.pkg
                "},
                "App.pkg",
            ),
        ] {
            let error = format!(
                "{:#}",
                load(&format!("{PACKAGE}{snippet}")).expect_err(expected)
            );
            assert!(error.contains(expected), "{snippet} | error: {error}");
        }
    }
}