anodizer 0.28.0

A Rust-native release automation tool inspired by GoReleaser
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
use super::*;
use anodizer_core::config::{Config, CrateConfig, WorkspaceConfig};
use std::fs;
use tempfile::tempdir;

fn make_crate(name: &str, tag_template: &str, depends_on: Option<Vec<&str>>) -> CrateConfig {
    CrateConfig {
        name: name.to_string(),
        path: ".".to_string(),
        tag_template: Some(tag_template.to_string()),
        depends_on: depends_on.map(|d| d.iter().map(|s| s.to_string()).collect()),
        ..Default::default()
    }
}

fn make_config(crates: Vec<CrateConfig>) -> Config {
    Config {
        project_name: "test".to_string(),
        crates,
        ..Default::default()
    }
}

fn test_logger() -> StageLogger {
    StageLogger::new("check", Verbosity::Quiet)
}

/// A guaranteed-nonexistent directory: `discover_cargo_workspace_member_names`
/// finds no `Cargo.toml` there, so [`check_workspace_membership`] no-ops —
/// keeping every other test in this module independent of the
/// workspace-membership guard, which has its own dedicated tests below.
const NO_WORKSPACE_BASE: &str = "/nonexistent/anodizer-check-config-test-base";

/// Write a hermetic on-disk Cargo workspace at `root`: a root
/// `Cargo.toml` declaring `members`, and each `(member_path, package_name,
/// intra_workspace_deps)` tuple's own `Cargo.toml`, with each dep written
/// as `dep.workspace = true` (this repo's own dependency shape).
fn write_disk_workspace(root: &std::path::Path, members: &[(&str, &str, &[&str])]) {
    fs::create_dir_all(root).unwrap();
    let member_list = members
        .iter()
        .map(|(path, _, _)| format!("\"{path}\""))
        .collect::<Vec<_>>()
        .join(", ");
    fs::write(
        root.join("Cargo.toml"),
        format!("[workspace]\nmembers = [{member_list}]\n"),
    )
    .unwrap();
    for (path, name, deps) in members {
        let dir = root.join(path);
        fs::create_dir_all(&dir).unwrap();
        let mut body = format!("[package]\nname = \"{name}\"\n");
        if !deps.is_empty() {
            body.push_str("[dependencies]\n");
            for dep in *deps {
                body.push_str(&format!("{dep}.workspace = true\n"));
            }
        }
        fs::write(dir.join("Cargo.toml"), body).unwrap();
    }
}

/// `check_crate_paths` resolves `CrateConfig.path` against the PROCESS
/// cwd, not `base_dir` — so fixture crate paths must be absolute
/// (`base_dir.join(rel)`) to exist regardless of where `cargo test` runs
/// from. `Path::join` with an absolute `path` (as `check_workspace_membership`
/// does via `base_dir.join(&c.path)`) discards `base_dir` and returns the
/// absolute path unchanged, so this also resolves correctly there.
fn p(root: &std::path::Path, rel: &str) -> String {
    root.join(rel).to_string_lossy().to_string()
}

/// Opt a fixture crate into an active cargo publisher — the gate
/// `check_workspace_membership` requires before it will raise a
/// missing-dependency error for that crate.
fn with_active_cargo_publisher(mut c: CrateConfig) -> CrateConfig {
    c.publish = Some(anodizer_core::config::PublishConfig {
        cargo: Some(anodizer_core::config::CargoPublishConfig::default()),
        ..Default::default()
    });
    c
}

#[test]
fn check_workspace_membership_direct_missing_dep_names_both_crates() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/main", "main", &["helper"]),
            ("crates/helper", "helper", &[]),
        ],
    );
    let config = make_config(vec![with_active_cargo_publisher(CrateConfig {
        name: "main".to_string(),
        path: p(root, "crates/main"),
        tag_template: Some("v{{ .Version }}".to_string()),
        ..Default::default()
    })]);
    let all_names = flatten_crate_names(&config);
    let mut errors = vec![];
    check_workspace_membership(&config, root, &all_names, &mut errors);
    assert_eq!(
        errors.len(),
        1,
        "expected exactly one missing-membership error: {errors:?}"
    );
    assert!(
        errors[0].contains("helper"),
        "error should name the missing crate: {}",
        errors[0]
    );
    assert!(
        errors[0].contains("main"),
        "error should name the dependent crate: {}",
        errors[0]
    );
}

// ---- single-crate mode: exactly one top-level `crates:` entry ----

#[test]
fn check_workspace_membership_single_crate_mode_missing_dep_fails() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/main", "main", &["helper"]),
            ("crates/helper", "helper", &[]),
        ],
    );
    let config = make_config(vec![with_active_cargo_publisher(CrateConfig {
        name: "main".to_string(),
        path: p(root, "crates/main"),
        tag_template: Some("v{{ .Version }}".to_string()),
        ..Default::default()
    })]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_err(),
        "single-crate config missing an on-disk workspace dep should fail"
    );
}

#[test]
fn check_workspace_membership_single_crate_mode_complete_passes() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/main", "main", &["helper"]),
            ("crates/helper", "helper", &[]),
        ],
    );
    let config = make_config(vec![
        with_active_cargo_publisher(CrateConfig {
            name: "main".to_string(),
            path: p(root, "crates/main"),
            tag_template: Some("v{{ .Version }}".to_string()),
            depends_on: Some(vec!["helper".to_string()]),
            ..Default::default()
        }),
        with_active_cargo_publisher(CrateConfig {
            name: "helper".to_string(),
            path: p(root, "crates/helper"),
            tag_template: Some("helper-v{{ .Version }}".to_string()),
            ..Default::default()
        }),
    ]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_ok(),
        "complete single-crate-mode membership should pass: {:?}",
        result.err()
    );
}

// ---- lockstep mode: multiple top-level `crates:` entries, one version ----

#[test]
fn check_workspace_membership_lockstep_multi_crate_missing_dep_fails() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/api", "api", &["shared"]),
            ("crates/cli", "cli", &["shared"]),
            ("crates/shared", "shared", &[]),
        ],
    );
    let config = make_config(vec![
        with_active_cargo_publisher(CrateConfig {
            name: "api".to_string(),
            path: p(root, "crates/api"),
            tag_template: Some("v{{ .Version }}".to_string()),
            ..Default::default()
        }),
        with_active_cargo_publisher(CrateConfig {
            name: "cli".to_string(),
            path: p(root, "crates/cli"),
            tag_template: Some("v{{ .Version }}".to_string()),
            ..Default::default()
        }),
    ]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_err(),
        "lockstep config missing an on-disk workspace dep should fail"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("2 error(s)"),
        "expected one error per dependent crate referencing 'shared': {}",
        msg
    );
}

#[test]
fn check_workspace_membership_lockstep_multi_crate_complete_passes() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/api", "api", &["shared"]),
            ("crates/cli", "cli", &["shared"]),
            ("crates/shared", "shared", &[]),
        ],
    );
    let config = make_config(vec![
        with_active_cargo_publisher(CrateConfig {
            name: "api".to_string(),
            path: p(root, "crates/api"),
            tag_template: Some("v{{ .Version }}".to_string()),
            depends_on: Some(vec!["shared".to_string()]),
            ..Default::default()
        }),
        with_active_cargo_publisher(CrateConfig {
            name: "cli".to_string(),
            path: p(root, "crates/cli"),
            tag_template: Some("v{{ .Version }}".to_string()),
            depends_on: Some(vec!["shared".to_string()]),
            ..Default::default()
        }),
        with_active_cargo_publisher(CrateConfig {
            name: "shared".to_string(),
            path: p(root, "crates/shared"),
            tag_template: Some("shared-v{{ .Version }}".to_string()),
            ..Default::default()
        }),
    ]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_ok(),
        "complete lockstep membership should pass: {:?}",
        result.err()
    );
}

// ---- per-crate mode: nested `workspaces:` groups, independent cadence ----

#[test]
fn check_workspace_membership_per_crate_workspace_missing_dep_fails() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/frontend", "frontend", &["util"]),
            ("crates/util", "util", &[]),
        ],
    );
    let mut config = make_config(vec![]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "web".to_string(),
        crates: vec![with_active_cargo_publisher(CrateConfig {
            name: "frontend".to_string(),
            path: p(root, "crates/frontend"),
            tag_template: Some("frontend-v{{ .Version }}".to_string()),
            ..Default::default()
        })],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_err(),
        "per-crate workspace config missing an on-disk dep should fail"
    );
}

#[test]
fn check_workspace_membership_per_crate_workspace_complete_passes() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/frontend", "frontend", &["util"]),
            ("crates/util", "util", &[]),
        ],
    );
    let mut config = make_config(vec![]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "web".to_string(),
        crates: vec![
            with_active_cargo_publisher(CrateConfig {
                name: "frontend".to_string(),
                path: p(root, "crates/frontend"),
                tag_template: Some("frontend-v{{ .Version }}".to_string()),
                depends_on: Some(vec!["util".to_string()]),
                ..Default::default()
            }),
            with_active_cargo_publisher(CrateConfig {
                name: "util".to_string(),
                path: p(root, "crates/util"),
                tag_template: Some("util-v{{ .Version }}".to_string()),
                ..Default::default()
            }),
        ],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), root);
    assert!(
        result.is_ok(),
        "complete per-crate workspace membership should pass: {:?}",
        result.err()
    );
}

// ---- publisher-gating: only crates with an active cargo publisher are checked ----

#[test]
fn check_workspace_membership_no_active_publisher_skips_check() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/main", "main", &["helper"]),
            ("crates/helper", "helper", &[]),
        ],
    );
    // `main` has a genuine missing on-disk dep ("helper"), but no active
    // cargo publisher — the check must not flag it (nothing will ever be
    // `cargo publish`ed, so a missing crates: entry for its dep is moot).
    let config = make_config(vec![CrateConfig {
        name: "main".to_string(),
        path: p(root, "crates/main"),
        tag_template: Some("v{{ .Version }}".to_string()),
        ..Default::default()
    }]);
    let all_names = flatten_crate_names(&config);
    let mut errors = vec![];
    check_workspace_membership(&config, root, &all_names, &mut errors);
    assert!(
        errors.is_empty(),
        "crate with no active cargo publisher must not be checked for workspace membership: {errors:?}"
    );
}

#[test]
fn check_workspace_membership_dep_with_cargo_skip_still_errors() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    write_disk_workspace(
        root,
        &[
            ("crates/main", "main", &["helper"]),
            ("crates/helper", "helper", &[]),
        ],
    );
    // "helper" IS present in `crates:`, but its cargo publisher is
    // explicitly skipped — `main` publishing to crates.io would still
    // fail because "helper" is never uploaded to the registry.
    let mut helper = CrateConfig {
        name: "helper".to_string(),
        path: p(root, "crates/helper"),
        tag_template: Some("helper-v{{ .Version }}".to_string()),
        ..Default::default()
    };
    helper.publish = Some(anodizer_core::config::PublishConfig {
        cargo: Some(anodizer_core::config::CargoPublishConfig {
            skip: Some(anodizer_core::config::StringOrBool::Bool(true)),
            ..Default::default()
        }),
        ..Default::default()
    });
    let config = make_config(vec![
        with_active_cargo_publisher(CrateConfig {
            name: "main".to_string(),
            path: p(root, "crates/main"),
            tag_template: Some("v{{ .Version }}".to_string()),
            depends_on: Some(vec!["helper".to_string()]),
            ..Default::default()
        }),
        helper,
    ]);
    let all_names = flatten_crate_names(&config);
    let mut errors = vec![];
    check_workspace_membership(&config, root, &all_names, &mut errors);
    assert_eq!(
        errors.len(),
        1,
        "dependency with publish.cargo.skip=true should still fail the membership check: {errors:?}"
    );
    assert!(
        errors[0].contains("no active cargo publisher"),
        "error should explain the skipped publisher, got: {}",
        errors[0]
    );
}

// ---- multi-root: `workspaces:` spanning distinct physical Cargo workspaces ----

#[test]
fn check_workspace_membership_discriminates_distinct_cargo_workspace_roots() {
    let tmp = tempdir().unwrap();
    let root = tmp.path();
    // Two SEPARATE physical Cargo workspaces, each rooted below `root`
    // (no Cargo.toml at `root` itself) — proves `find_cargo_workspace_root`
    // climbs per-crate rather than coincidentally reaching `base_dir`,
    // and that `member_cache` keys on the resolved root without
    // cross-contaminating the two workspaces' member sets.
    write_disk_workspace(
        &root.join("ws-a"),
        &[
            ("crates/frontend", "frontend", &["util"]),
            ("crates/util", "util", &[]),
        ],
    );
    write_disk_workspace(
        &root.join("ws-b"),
        &[
            ("crates/backend", "backend", &["dbutil"]),
            ("crates/dbutil", "dbutil", &[]),
        ],
    );
    let config = make_config(vec![
        // ws-a: "frontend" omits depends_on for its genuine dep "util" — expect an error.
        with_active_cargo_publisher(CrateConfig {
            name: "frontend".to_string(),
            path: p(root, "ws-a/crates/frontend"),
            tag_template: Some("frontend-v{{ .Version }}".to_string()),
            ..Default::default()
        }),
        // ws-b: "backend" correctly declares depends_on for its genuine dep "dbutil" — expect none.
        with_active_cargo_publisher(CrateConfig {
            name: "backend".to_string(),
            path: p(root, "ws-b/crates/backend"),
            tag_template: Some("backend-v{{ .Version }}".to_string()),
            depends_on: Some(vec!["dbutil".to_string()]),
            ..Default::default()
        }),
        with_active_cargo_publisher(CrateConfig {
            name: "dbutil".to_string(),
            path: p(root, "ws-b/crates/dbutil"),
            tag_template: Some("dbutil-v{{ .Version }}".to_string()),
            ..Default::default()
        }),
    ]);
    let all_names = flatten_crate_names(&config);
    let mut errors = vec![];
    check_workspace_membership(&config, root, &all_names, &mut errors);
    assert_eq!(
        errors.len(),
        1,
        "only ws-a's frontend/util gap should error; ws-b's backend/dbutil is complete: {errors:?}"
    );
    assert!(
        errors[0].contains("util") && errors[0].contains("frontend"),
        "error should name ws-a's missing dep, got: {}",
        errors[0]
    );
}

/// `check config --workspace X` validates X's resolved config only: a
/// SIBLING workspace's error (here a `depends_on` cycle confined to ws-b)
/// must not fail ws-a's scoped validation. The overlay clears
/// `workspaces`, so the resolved universe is exactly ws-a's crates.
#[test]
fn workspace_scoped_checks_ignore_sibling_errors() {
    let config = Config {
        project_name: "test".to_string(),
        workspaces: Some(vec![
            WorkspaceConfig {
                name: "ws-a".to_string(),
                crates: vec![make_crate("a-one", "a-one-v{{ .Version }}", None)],
                ..Default::default()
            },
            WorkspaceConfig {
                name: "ws-b".to_string(),
                crates: vec![
                    make_crate("b-one", "b-one-v{{ .Version }}", Some(vec!["b-two"])),
                    make_crate("b-two", "b-two-v{{ .Version }}", Some(vec!["b-one"])),
                ],
                ..Default::default()
            },
        ]),
        ..Default::default()
    };
    // The raw (un-overlaid) config fails on ws-b's cycle.
    assert!(
        run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_err(),
        "raw config must fail on the sibling's cycle"
    );
    // The ws-a-resolved config must pass — the sibling is out of scope.
    let ws = config.workspaces.as_ref().unwrap()[0].clone();
    let mut resolved = config.clone();
    helpers::apply_workspace_overlay(&mut resolved, &ws);
    run_checks(
        &resolved,
        false,
        &test_logger(),
        Path::new(NO_WORKSPACE_BASE),
    )
    .expect("workspace-scoped validation must ignore sibling workspace errors");
}

/// The COMMAND path of the sibling-isolation rule: `check config
/// --workspace ws-a` must exit clean when the only error (a `depends_on`
/// cycle) is confined to sibling ws-b, while the no-flag form still fails
/// on it. The hand-overlaid `run_checks` pin above cannot catch a command
/// that validates the raw config before scoping — this one drives `run`.
#[test]
fn command_workspace_scoped_run_ignores_sibling_errors() {
    let tmp = tempfile::tempdir().unwrap();
    let root = tmp.path();
    let config_path = root.join(".anodizer.yaml");
    // `path: .` throughout — the crate-path existence check resolves
    // against the PROCESS cwd (which a unit test must not change), and
    // the sibling-isolation subject here is the cycle, not the paths.
    std::fs::write(
        &config_path,
        r#"project_name: fixture
workspaces:
  - name: ws-a
    crates:
      - name: a-one
        path: .
        tag_template: "a-one-v{{ .Version }}"
  - name: ws-b
    crates:
      - name: b-one
        path: .
        tag_template: "b-one-v{{ .Version }}"
        depends_on: [b-two]
      - name: b-two
        path: .
        tag_template: "b-two-v{{ .Version }}"
        depends_on: [b-one]
"#,
    )
    .unwrap();

    run(Some(&config_path), Some("ws-a"), &[], false, false, true)
        .expect("scoped run must not fail on the sibling workspace's cycle");
    let err = run(Some(&config_path), None, &[], false, false, true)
        .expect_err("the no-flag run still validates the whole file");
    assert!(err.to_string().contains("validation failed"), "got: {err}");
}

// ---- Cycle detection tests ----

#[test]
fn test_no_cycle_linear() {
    let crates = vec![
        make_crate("a", "a-v{{ .Version }}", None),
        make_crate("b", "b-v{{ .Version }}", Some(vec!["a"])),
        make_crate("c", "c-v{{ .Version }}", Some(vec!["b"])),
    ];
    assert!(find_cycle(&crates).is_none());
}

#[test]
fn test_cycle_two_nodes() {
    let crates = vec![
        make_crate("a", "a-v{{ .Version }}", Some(vec!["b"])),
        make_crate("b", "b-v{{ .Version }}", Some(vec!["a"])),
    ];
    let cycle = find_cycle(&crates);
    assert!(cycle.is_some(), "expected a cycle to be detected");
}

#[test]
fn test_cycle_three_nodes() {
    let crates = vec![
        make_crate("a", "a-v{{ .Version }}", Some(vec!["c"])),
        make_crate("b", "b-v{{ .Version }}", Some(vec!["a"])),
        make_crate("c", "c-v{{ .Version }}", Some(vec!["b"])),
    ];
    let cycle = find_cycle(&crates);
    assert!(cycle.is_some(), "expected a cycle to be detected");
}

#[test]
fn test_no_cycle_diamond() {
    let crates = vec![
        make_crate("base", "base-v{{ .Version }}", None),
        make_crate("left", "left-v{{ .Version }}", Some(vec!["base"])),
        make_crate("right", "right-v{{ .Version }}", Some(vec!["base"])),
        make_crate("top", "top-v{{ .Version }}", Some(vec!["left", "right"])),
    ];
    assert!(find_cycle(&crates).is_none());
}

// ---- tag_template validation tests ----

#[test]
fn test_tag_template_valid() {
    let config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_tag_template_missing_version() {
    let config = make_config(vec![make_crate("a", "release-tag", None)]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err());
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_tag_template_empty_skipped() {
    // Empty tag_template should not trigger the error (it's just unconfigured)
    let config = make_config(vec![make_crate("a", "", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

// ---- depends_on reference tests ----

#[test]
fn test_depends_on_missing_crate() {
    let config = make_config(vec![make_crate(
        "a",
        "a-v{{ .Version }}",
        Some(vec!["nonexistent"]),
    )]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err());
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_depends_on_cycle_fails() {
    let crates = vec![
        make_crate("a", "a-v{{ .Version }}", Some(vec!["b"])),
        make_crate("b", "b-v{{ .Version }}", Some(vec!["a"])),
    ];
    let config = make_config(crates);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err());
}

// ---- copy_from tests ----

#[test]
fn test_copy_from_valid() {
    use anodizer_core::config::BuildConfig;
    let mut c = make_crate("a", "a-v{{ .Version }}", None);
    c.builds = Some(vec![
        BuildConfig {
            binary: Some("a".to_string()),
            ..Default::default()
        },
        BuildConfig {
            binary: Some("b".to_string()),
            copy_from: Some("a".to_string()),
            ..Default::default()
        },
    ]);
    let config = make_config(vec![c]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_copy_from_invalid() {
    use anodizer_core::config::BuildConfig;
    let mut c = make_crate("a", "a-v{{ .Version }}", None);
    c.builds = Some(vec![BuildConfig {
        binary: Some("b".to_string()),
        copy_from: Some("nonexistent".to_string()),
        ..Default::default()
    }]);
    let config = make_config(vec![c]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err());
}

// ---- Contradictory config warning tests ----

#[test]
fn test_check_changelog_disabled_with_other_fields_passes() {
    use anodizer_core::config::{ChangelogConfig, ChangelogGroup};
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.changelog = Some(ChangelogConfig {
        skip: Some(anodizer_core::config::StringOrBool::Bool(true)),
        sort: Some("desc".to_string()),
        header: Some(anodizer_core::config::ContentSource::Inline(
            "header".to_string(),
        )),
        groups: Some(vec![ChangelogGroup {
            title: "Features".to_string(),
            regexp: Some("^feat".to_string()),
            order: Some(0),
            groups: None,
        }]),
        ..Default::default()
    });
    // Should pass (warnings only, not errors)
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_check_checksum_disabled_with_other_fields_passes() {
    use anodizer_core::config::{ChecksumConfig, Defaults, StringOrBool};
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.defaults = Some(Defaults {
        checksum: Some(ChecksumConfig {
            skip: Some(StringOrBool::Bool(true)),
            algorithm: Some("sha512".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    // Should pass (warnings only, not errors)
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

// ---- Empty crate name validation tests ----

#[test]
fn test_empty_crate_name_fails() {
    let config = make_config(vec![make_crate("", "v{{ .Version }}", None)]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "empty crate name should fail validation");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_whitespace_only_crate_name_fails() {
    let config = make_config(vec![make_crate("  ", "v{{ .Version }}", None)]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(
        result.is_err(),
        "whitespace-only crate name should fail validation"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("1 error(s)"),
        "error should report 1 validation error, got: {msg}"
    );
}

// ---- tag_template compact spacing variant tests ----

#[test]
fn test_tag_template_compact_version_accepted() {
    // {{.Version}} without spaces should also be accepted
    let config = make_config(vec![make_crate("a", "v{{.Version}}", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_tag_template_tera_native_version_accepted() {
    // {{ Version }} (Tera-native, no dot) should also be accepted
    let config = make_config(vec![make_crate("a", "v{{ Version }}", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_tag_template_tera_native_compact_version_accepted() {
    // {{Version}} (Tera-native, no dot, no spaces) should also be accepted
    let config = make_config(vec![make_crate("a", "v{{Version}}", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_tag_template_missing_version_with_other_placeholder() {
    // Has a placeholder but not {{ .Version }}
    let config = make_config(vec![make_crate("a", "{{ .Tag }}-release", None)]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(
        result.is_err(),
        "tag_template without Version placeholder should fail"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("1 error(s)"),
        "error should report 1 validation error, got: {msg}"
    );
}

// ---- Multiple validation errors test ----

#[test]
fn test_multiple_validation_errors_reported() {
    let crates = vec![
        make_crate("", "v{{ .Version }}", None), // empty name
        make_crate("b", "bad-tag", Some(vec!["nonexistent"])), // missing dep + bad template
    ];
    let config = make_config(crates);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err());
    let msg = result.unwrap_err().to_string();
    // Should report exactly 3 errors: empty name, missing dep, bad tag_template
    assert!(
        msg.contains("3 error(s)"),
        "should report 3 error(s), got: {}",
        msg
    );
}

#[test]
fn test_check_per_crate_checksum_disabled_with_other_fields_passes() {
    use anodizer_core::config::{ChecksumConfig, StringOrBool};
    let mut c = make_crate("a", "a-v{{ .Version }}", None);
    c.checksum = Some(ChecksumConfig {
        skip: Some(StringOrBool::Bool(true)),
        algorithm: Some("sha512".to_string()),
        name_template: Some("checksums.txt".to_string()),
        ..Default::default()
    });
    let config = make_config(vec![c]);
    // Should pass (warnings only, not errors)
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

// ---- Workspace validation tests ----

#[test]
fn workspace_only_crates_flag_tool_needs() {
    // A crate declared only under `workspaces[].crates` must arm the
    // same tool-requirement checks a top-level crate does; a
    // top-level-only walk would let its docker/release/nfpm needs pass
    // `check config` silently.
    use anodizer_core::config::{DockerV2Config, NfpmConfig, ReleaseConfig};
    let mut member = make_crate("svc", "svc-v{{ .Version }}", None);
    member.dockers_v2 = Some(vec![DockerV2Config::default()]);
    member.release = Some(ReleaseConfig::default());
    member.nfpms = Some(vec![NfpmConfig::default()]);
    let mut config = make_config(vec![]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "grp".to_string(),
        crates: vec![member],
        ..Default::default()
    }]);

    assert!(config_needs_docker(&config));
    assert!(config_needs_release(&config));
    assert!(config_needs_nfpm(&config));
}

#[test]
fn test_workspace_names_unique_passes() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![
        WorkspaceConfig {
            name: "frontend".to_string(),
            crates: vec![make_crate("fe", "fe-v{{ .Version }}", None)],
            ..Default::default()
        },
        WorkspaceConfig {
            name: "backend".to_string(),
            crates: vec![make_crate("be", "be-v{{ .Version }}", None)],
            ..Default::default()
        },
    ]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_workspace_duplicate_name_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![
        WorkspaceConfig {
            name: "dup".to_string(),
            crates: vec![make_crate("x", "x-v{{ .Version }}", None)],
            ..Default::default()
        },
        WorkspaceConfig {
            name: "dup".to_string(),
            crates: vec![make_crate("y", "y-v{{ .Version }}", None)],
            ..Default::default()
        },
    ]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "duplicate workspace names should fail");
}

#[test]
fn test_workspace_empty_name_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "".to_string(),
        crates: vec![make_crate("x", "x-v{{ .Version }}", None)],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "empty workspace name should fail");
}

#[test]
fn test_workspace_crate_empty_name_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "ws1".to_string(),
        crates: vec![make_crate("", "v{{ .Version }}", None)],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "empty crate name in workspace should fail");
}

#[test]
fn test_workspace_crate_bad_tag_template_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "ws1".to_string(),
        crates: vec![make_crate("x", "no-version-here", None)],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(
        result.is_err(),
        "bad tag_template in workspace crate should fail"
    );
}

#[test]
fn test_no_workspaces_passes() {
    let config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    assert!(run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok());
}

#[test]
fn test_workspace_duplicate_crate_name_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "ws1".to_string(),
        crates: vec![
            make_crate("dup", "dup-v{{ .Version }}", None),
            make_crate("dup", "dup-v{{ .Version }}", None),
        ],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(
        result.is_err(),
        "duplicate crate names within a workspace should fail"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("1 error(s)"),
        "should report 1 validation error for duplicate crate name: {}",
        msg
    );
}

#[test]
fn test_workspace_depends_on_missing_fails() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "ws1".to_string(),
        crates: vec![make_crate(
            "x",
            "x-v{{ .Version }}",
            Some(vec!["nonexistent"]),
        )],
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(
        result.is_err(),
        "workspace crate with missing depends_on should fail"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("1 error(s)"),
        "should report 1 validation error for missing depends_on: {}",
        msg
    );
}

#[test]
fn test_workspace_depends_on_cross_workspace_passes() {
    // A crate in one workspace can depend on a crate in another workspace.
    // The release engine topo-sorts across all workspaces, so the check
    // validator must not flag cross-workspace references as missing.
    let config = Config {
        project_name: "test".to_string(),
        workspaces: Some(vec![
            WorkspaceConfig {
                name: "core-ws".to_string(),
                crates: vec![make_crate("core", "core-v{{ .Version }}", None)],
                ..Default::default()
            },
            WorkspaceConfig {
                name: "app-ws".to_string(),
                crates: vec![make_crate("app", "app-v{{ .Version }}", Some(vec!["core"]))],
                ..Default::default()
            },
        ]),
        ..Default::default()
    };
    assert!(
        run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok(),
        "cross-workspace depends_on should be accepted"
    );
}

#[test]
fn test_workspace_depends_on_valid_passes() {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.workspaces = Some(vec![WorkspaceConfig {
        name: "ws1".to_string(),
        crates: vec![
            make_crate("lib", "lib-v{{ .Version }}", None),
            make_crate("app", "app-v{{ .Version }}", Some(vec!["lib"])),
        ],
        ..Default::default()
    }]);
    assert!(
        run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok(),
        "valid depends_on within workspace should pass"
    );
}

// ---- Source/SBOM format validation tests ----

#[test]
fn test_invalid_source_format_fails() {
    use anodizer_core::config::SourceConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.source = Some(SourceConfig {
        enabled: Some(true),
        format: Some("tar.bz2".to_string()),
        name_template: None,
        prefix_template: None,
        files: vec![],
    });
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "invalid source format should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_valid_source_formats_pass() {
    use anodizer_core::config::SourceConfig;
    for fmt in &["tar.gz", "tgz", "tar", "zip"] {
        let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
        config.source = Some(SourceConfig {
            enabled: Some(true),
            format: Some(fmt.to_string()),
            name_template: None,
            prefix_template: None,
            files: vec![],
        });
        assert!(
            run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok(),
            "source format '{}' should pass",
            fmt
        );
    }
}

#[test]
fn test_invalid_sbom_artifacts_fails() {
    use anodizer_core::config::SbomConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.sboms = vec![SbomConfig {
        artifacts: Some("invalid".to_string()),
        ..Default::default()
    }];
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "invalid sbom artifacts should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_valid_sbom_artifacts_pass() {
    use anodizer_core::config::SbomConfig;
    for art in &[
        "source",
        "archive",
        "binary",
        "package",
        "diskimage",
        "installer",
        "any",
    ] {
        let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
        config.sboms = vec![SbomConfig {
            artifacts: Some(art.to_string()),
            ..Default::default()
        }];
        assert!(
            run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok(),
            "sbom artifacts '{}' should pass",
            art
        );
    }
}

// -----------------------------------------------------------------------
// Blob config validation tests
// -----------------------------------------------------------------------

#[test]
fn test_blob_config_valid_provider() {
    use anodizer_core::config::BlobConfig;
    for provider in &["s3", "gcs", "gs", "azblob", "azure"] {
        let mut config = make_config(vec![make_crate("a", "v{{ .Version }}", None)]);
        config.crates[0].blobs = Some(vec![BlobConfig {
            provider: provider.to_string(),
            bucket: "my-bucket".to_string(),
            ..Default::default()
        }]);
        assert!(
            run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE)).is_ok(),
            "blob provider '{}' should pass",
            provider
        );
    }
}

#[test]
fn test_blob_config_invalid_provider() {
    use anodizer_core::config::BlobConfig;
    let mut config = make_config(vec![make_crate("a", "v{{ .Version }}", None)]);
    config.crates[0].blobs = Some(vec![BlobConfig {
        provider: "dropbox".to_string(),
        bucket: "b".to_string(),
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "invalid blob provider should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_blob_config_empty_provider() {
    use anodizer_core::config::BlobConfig;
    let mut config = make_config(vec![make_crate("a", "v{{ .Version }}", None)]);
    config.crates[0].blobs = Some(vec![BlobConfig {
        provider: String::new(),
        bucket: "b".to_string(),
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "empty blob provider should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_blob_config_empty_bucket() {
    use anodizer_core::config::BlobConfig;
    let mut config = make_config(vec![make_crate("a", "v{{ .Version }}", None)]);
    config.crates[0].blobs = Some(vec![BlobConfig {
        provider: "s3".to_string(),
        bucket: String::new(),
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "empty blob bucket should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

#[test]
fn test_blob_config_id_in_error_label() {
    use anodizer_core::config::BlobConfig;
    let mut config = make_config(vec![make_crate("a", "v{{ .Version }}", None)]);
    config.crates[0].blobs = Some(vec![BlobConfig {
        id: Some("my-upload".to_string()),
        provider: "invalid".to_string(),
        bucket: "b".to_string(),
        ..Default::default()
    }]);
    let result = run_checks(&config, false, &test_logger(), Path::new(NO_WORKSPACE_BASE));
    assert!(result.is_err(), "invalid provider with id should fail");
    let msg = result.unwrap_err().to_string();
    assert!(msg.contains("validation failed"), "got: {}", msg);
}

// -----------------------------------------------------------------------
// Announce secret-exposure lint tests
// -----------------------------------------------------------------------

use anodizer_core::config::{
    AnnounceConfig, BlueskyAnnounce, DiscourseAnnounce, EmailAnnounce, SlackAnnounce,
    SlackAttachment, SlackBlock, SlackTextObject, TwitterAnnounce,
};

fn collect_announce_warnings(announce: AnnounceConfig) -> Vec<String> {
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.announce = Some(announce);
    let mut warnings = Vec::new();
    check_announce_secret_exposure(&config, &mut warnings);
    warnings
}

#[test]
fn test_announce_secret_warns_on_token_in_message() {
    let warnings = collect_announce_warnings(AnnounceConfig {
        twitter: Some(TwitterAnnounce {
            message_template: Some("deploy {{ Env.GITHUB_TOKEN }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(
        warnings.len(),
        1,
        "expected one warning, got: {:?}",
        warnings
    );
    assert!(warnings[0].contains("announce.twitter.message_template"));
    assert!(warnings[0].contains("Env.GITHUB_TOKEN"));
    assert!(
        warnings[0].contains("$GITHUB_TOKEN"),
        "warning should state the masked form: {}",
        warnings[0]
    );
}

#[test]
fn test_announce_secret_warns_on_title_and_email_subject() {
    let title_warnings = collect_announce_warnings(AnnounceConfig {
        discourse: Some(DiscourseAnnounce {
            title_template: Some("release {{ Env.SIGNING_KEY }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(title_warnings.len(), 1, "got: {:?}", title_warnings);
    assert!(title_warnings[0].contains("announce.discourse.title_template"));
    assert!(title_warnings[0].contains("Env.SIGNING_KEY"));

    let email_warnings = collect_announce_warnings(AnnounceConfig {
        email: Some(EmailAnnounce {
            subject_template: Some("v{{ Env.NPM_PASSWORD }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(email_warnings.len(), 1, "got: {:?}", email_warnings);
    assert!(email_warnings[0].contains("announce.email.subject_template"));
    assert!(email_warnings[0].contains("Env.NPM_PASSWORD"));
}

#[test]
fn test_announce_secret_warns_on_go_style_dotted_env() {
    let warnings = collect_announce_warnings(AnnounceConfig {
        twitter: Some(TwitterAnnounce {
            message_template: Some("{{ .Env.CARGO_REGISTRY_TOKEN }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(warnings.len(), 1, "got: {:?}", warnings);
    assert!(warnings[0].contains("Env.CARGO_REGISTRY_TOKEN"));
}

#[test]
fn test_announce_secret_warns_in_slack_blocks_and_attachments() {
    let warnings = collect_announce_warnings(AnnounceConfig {
        slack: Some(SlackAnnounce {
            blocks: Some(vec![SlackBlock {
                block_type: "section".to_string(),
                text: Some(SlackTextObject {
                    text_type: "mrkdwn".to_string(),
                    text: "see {{ Env.SLACK_API_TOKEN }}".to_string(),
                    ..Default::default()
                }),
                ..Default::default()
            }]),
            attachments: Some(vec![SlackAttachment {
                footer: Some("built by {{ Env.BUILDER_SECRET }}".to_string()),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(warnings.len(), 2, "got: {:?}", warnings);
    assert!(
        warnings
            .iter()
            .any(|w| w.contains("announce.slack.blocks[0].text")
                && w.contains("Env.SLACK_API_TOKEN")),
        "block-nested secret not warned: {:?}",
        warnings
    );
    assert!(
        warnings
            .iter()
            .any(|w| w.contains("announce.slack.attachments[0].footer")
                && w.contains("Env.BUILDER_SECRET")),
        "attachment-nested secret not warned: {:?}",
        warnings
    );
}

#[test]
fn test_announce_secret_silent_on_non_secret_refs() {
    // Non-secret placeholders, a non-secret env var, a provider with no
    // template, and an absent announce block all stay silent.
    let warnings = collect_announce_warnings(AnnounceConfig {
        bluesky: Some(BlueskyAnnounce {
            message_template: Some("{{ ProjectName }} {{ Tag }} home={{ Env.HOME }}".to_string()),
            ..Default::default()
        }),
        twitter: Some(TwitterAnnounce {
            message_template: None,
            ..Default::default()
        }),
        ..Default::default()
    });
    assert!(
        warnings.is_empty(),
        "non-secret refs should not warn: {:?}",
        warnings
    );

    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.announce = None;
    let mut no_announce = Vec::new();
    check_announce_secret_exposure(&config, &mut no_announce);
    assert!(
        no_announce.is_empty(),
        "absent announce block should not warn: {:?}",
        no_announce
    );
}

#[test]
fn test_announce_secret_silent_on_bare_prose_no_braces() {
    // A secret-named ref in plain prose (outside any {{ }} / {% %} block)
    // never renders under Tera, so it cannot leak and must stay silent.
    let warnings = collect_announce_warnings(AnnounceConfig {
        twitter: Some(TwitterAnnounce {
            message_template: Some("contact Env.GITHUB_TOKEN admin".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert!(
        warnings.is_empty(),
        "bare-prose Env ref outside a render block should not warn: {:?}",
        warnings
    );
}

#[test]
fn test_announce_secret_warns_on_both_refs_in_one_block() {
    // Two Env refs inside ONE render block must both be flagged; only the
    // secret-named one(s) warn (PROJECT is not secret, B_TOKEN is).
    let warnings = collect_announce_warnings(AnnounceConfig {
        twitter: Some(TwitterAnnounce {
            message_template: Some("{{ Env.A_TOKEN | default(Env.B_TOKEN) }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(
        warnings.len(),
        2,
        "both secret refs should warn: {:?}",
        warnings
    );
    assert!(
        warnings.iter().any(|w| w.contains("Env.A_TOKEN")),
        "first ref missed: {:?}",
        warnings
    );
    assert!(
        warnings.iter().any(|w| w.contains("Env.B_TOKEN")),
        "second ref in same block missed: {:?}",
        warnings
    );
}

// ---- Sign artifact-filter validation tests ----

fn config_with_sign_artifacts(filter: &str) -> Config {
    Config {
        project_name: "test".to_string(),
        signs: vec![anodizer_core::config::SignConfig {
            artifacts: Some(filter.to_string()),
            ..Default::default()
        }],
        ..Default::default()
    }
}

#[test]
fn sign_filter_accepts_runtime_recognized_values_without_warning() {
    // Every value the runtime `should_sign_artifact` resolver accepts must
    // be accepted by the check validator too — otherwise a config that
    // signs correctly at release time emits a spurious "unrecognized
    // artifact filter" warning at check time. The previously-missing
    // values (`any`, `installer`, `diskimage`, `sbom`, `snap`,
    // `macos_package`) are the regression this guards.
    for filter in anodizer_stage_sign::VALID_SIGN_ARTIFACT_FILTERS {
        let config = config_with_sign_artifacts(filter);
        let mut warnings: Vec<String> = vec![];
        check_sign_artifact_filters(&config, &mut warnings);
        assert!(
            warnings.is_empty(),
            "filter '{filter}' must NOT warn (it is runtime-valid), got: {warnings:?}"
        );
    }
}

#[test]
fn sign_filter_warns_on_unrecognized_value() {
    let config = config_with_sign_artifacts("bogus");
    let mut warnings: Vec<String> = vec![];
    check_sign_artifact_filters(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "an unknown filter must still warn");
    assert!(
        warnings[0].contains("bogus"),
        "warning should name the offending filter: {:?}",
        warnings
    );
}

#[test]
fn sign_authenticode_filter_warns_on_unrecognized_value() {
    // The authenticode sub-block carries its own `artifacts` selector,
    // resolved through the same vocabulary; an unknown value must warn too.
    let config = Config {
        project_name: "test".to_string(),
        signs: vec![anodizer_core::config::SignConfig {
            authenticode: Some(anodizer_core::config::AuthenticodeConfig {
                artifacts: Some("nonsense".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_sign_artifact_filters(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "unknown authenticode filter must warn");
    assert!(
        warnings[0].contains("authenticode") && warnings[0].contains("nonsense"),
        "authenticode warning should name the block and value: {:?}",
        warnings
    );
}

/// `asset_name_template:` parses on every sign config but is read only on the
/// `binary_signs:` slice — a `signs:` entry that sets it gets the derived name
/// with no error, so check names the omission.
#[test]
fn asset_name_template_on_signs_warns_that_it_is_ignored() {
    let sign_with_template = || anodizer_core::config::SignConfig {
        asset_name_template: Some("{{ Binary }}-{{ Version }}".to_string()),
        ..Default::default()
    };
    let config = Config {
        project_name: "test".to_string(),
        signs: vec![sign_with_template()],
        binary_signs: vec![sign_with_template()],
        workspaces: Some(vec![anodizer_core::config::WorkspaceConfig {
            name: "ws".to_string(),
            signs: vec![sign_with_template()],
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_sign_asset_name_templates(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "signs[0].asset_name_template is set but only binary_signs honors it (it will be ignored)".to_string(),
            "workspaces.ws.signs[0].asset_name_template is set but only binary_signs honors it (it will be ignored)".to_string(),
        ],
        "binary_signs honors the field and must not warn"
    );
}

/// `defaults.sign:` fills an empty top-level `signs:`, so the warning must
/// name the block the user actually wrote — `signs[0]` points at nothing in
/// their file.
#[test]
fn asset_name_template_under_defaults_sign_names_the_defaults_block() {
    let mut config = Config {
        project_name: "test".to_string(),
        defaults: Some(anodizer_core::config::Defaults {
            sign: Some(anodizer_core::config::SignConfig {
                asset_name_template: Some("{{ Binary }}-{{ Version }}".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        }),
        ..Default::default()
    };
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    let mut warnings: Vec<String> = vec![];
    check_sign_asset_name_templates(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "defaults.sign.asset_name_template is set but only binary_signs honors it (it will be ignored)".to_string(),
        ]
    );
}

/// A `signs:` entry the operator wrote is named as `signs[0]` even when it
/// repeats the `defaults.sign:` value verbatim — the fold filled nothing, so
/// naming `defaults.sign` would point at a block that changed no behaviour.
#[test]
fn an_entry_repeating_the_defaults_value_is_still_named_as_the_entry() {
    let mut config = Config {
        project_name: "test".to_string(),
        defaults: Some(anodizer_core::config::Defaults {
            sign: Some(anodizer_core::config::SignConfig {
                asset_name_template: Some("{{ Binary }}-{{ Version }}".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        }),
        signs: vec![anodizer_core::config::SignConfig {
            asset_name_template: Some("{{ Binary }}-{{ Version }}".to_string()),
            cmd: Some("cosign".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    let mut warnings: Vec<String> = vec![];
    check_sign_asset_name_templates(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "signs[0].asset_name_template is set but only binary_signs honors it (it will be ignored)".to_string(),
        ]
    );
}

/// `check config --workspace <name>` runs the checks on the OVERLAID config.
/// A workspace that declares its own `signs:` replaces the slice the
/// `defaults:` fold filled, so the warning must name the workspace entry — the
/// block the operator actually wrote — not `defaults.sign`.
#[test]
fn a_workspace_signs_entry_is_named_as_the_entry_after_the_overlay() {
    let workspace = WorkspaceConfig {
        name: "tools".to_string(),
        signs: vec![anodizer_core::config::SignConfig {
            cmd: Some("cosign".to_string()),
            asset_name_template: Some("{{ Binary }}-{{ Version }}".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut config = Config {
        project_name: "test".to_string(),
        defaults: Some(anodizer_core::config::Defaults {
            sign: Some(anodizer_core::config::SignConfig {
                cmd: Some("cosign".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        }),
        workspaces: Some(vec![workspace.clone()]),
        ..Default::default()
    };
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    assert!(
        config.filled_from_defaults.contains("signs"),
        "the fold must have filled the top-level slice for this to be a test"
    );

    let mut resolved = config.clone();
    helpers::apply_workspace_overlay(&mut resolved, &workspace);
    let mut warnings: Vec<String> = vec![];
    check_sign_asset_name_templates(&resolved, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "signs[0].asset_name_template is set but only binary_signs honors it (it will be ignored)".to_string(),
        ]
    );
}

/// A config that sets the field nowhere warns nowhere.
#[test]
fn no_asset_name_template_warns_nothing() {
    let config = Config {
        project_name: "test".to_string(),
        signs: vec![anodizer_core::config::SignConfig::default()],
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_sign_asset_name_templates(&config, &mut warnings);
    assert!(warnings.is_empty(), "{warnings:?}");
}

/// The duplicate-output warning as `check_sign_duplicate_outputs` prints it,
/// spelled out here so a broken continuation in the production format string
/// fails a test instead of an operator's terminal.
fn one_file_warning(first: &str, second: &str, field: &str) -> String {
    format!(
        "{first} and {second} resolve one {field} file for the artifacts both \
         select — the second {field} overwrites the first, so one file ships \
         where two were configured"
    )
}

/// Two `binary_signs:` entries with one `signature:` template sign one file,
/// and the second `cmd:` overwrites the first's bytes. The asset-name claim
/// accepts the pair (one name over one file is one release asset), so check
/// is the only place that says so.
#[test]
fn two_binary_signs_entries_over_one_file_warn() {
    use anodizer_core::config::SignConfig;
    let config = Config {
        binary_signs: vec![
            SignConfig {
                cmd: Some("cosign".to_string()),
                ..Default::default()
            },
            SignConfig {
                cmd: Some("gpg".to_string()),
                ..Default::default()
            },
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );
}

/// The `workspaces.<name>.binary_signs:` slice is the other half of the
/// population, and its label names the workspace.
#[test]
fn two_workspace_binary_signs_entries_over_one_file_warn() {
    use anodizer_core::config::SignConfig;
    let entry = |cmd: &str| SignConfig {
        cmd: Some(cmd.to_string()),
        ..Default::default()
    };
    let config = Config {
        workspaces: Some(vec![anodizer_core::config::WorkspaceConfig {
            name: "ws".to_string(),
            binary_signs: vec![entry("cosign"), entry("gpg")],
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "workspaces.ws.binary_signs[0]",
            "workspaces.ws.binary_signs[1]",
            "signature"
        )]
    );
}

/// `signature:` has a default, so leaving it unset and spelling it out name
/// one file; the certificate has none, so two absent ones name nothing.
#[test]
fn an_unset_signature_and_its_default_spelling_are_one_file() {
    use anodizer_core::config::SignConfig;
    let config = Config {
        binary_signs: vec![
            SignConfig {
                cmd: Some("cosign".to_string()),
                ..Default::default()
            },
            SignConfig {
                cmd: Some("gpg".to_string()),
                signature: Some(SignConfig::DEFAULT_BINARY_SIGNATURE_TEMPLATE.to_string()),
                ..Default::default()
            },
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );
}

/// Two entries sharing a `certificate:` template overwrite that file too, and
/// the message names the certificate on both sides.
#[test]
fn two_binary_signs_entries_over_one_certificate_warn() {
    use anodizer_core::config::SignConfig;
    let entry = |cmd: &str| SignConfig {
        cmd: Some(cmd.to_string()),
        signature: Some(format!("{{{{ .Artifact }}}}.{cmd}.sig")),
        certificate: Some("{{ .Artifact }}.pem".to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![entry("cosign"), entry("gpg")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "certificate"
        )]
    );
}

/// An Authenticode entry signs the PE in place and `artifacts: none` signs
/// nothing, so neither can overwrite a sibling's detached output.
#[test]
fn entries_that_write_no_detached_output_warn_nothing() {
    use anodizer_core::config::SignConfig;
    let cosign = || SignConfig {
        cmd: Some("cosign".to_string()),
        ..Default::default()
    };
    for quiet in [
        SignConfig {
            authenticode: Some(anodizer_core::config::AuthenticodeConfig::default()),
            ..Default::default()
        },
        SignConfig {
            artifacts: Some("none".to_string()),
            ..Default::default()
        },
    ] {
        let config = Config {
            binary_signs: vec![cosign(), quiet],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert!(warnings.is_empty(), "{warnings:?}");
    }
}

/// An entry the filter drops keeps the entries after it on the index the
/// operator wrote.
#[test]
fn a_filtered_entry_does_not_renumber_the_labels_after_it() {
    use anodizer_core::config::SignConfig;
    let cosign = |cmd: &str| SignConfig {
        cmd: Some(cmd.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![
            SignConfig {
                artifacts: Some("none".to_string()),
                ..Default::default()
            },
            cosign("cosign"),
            cosign("gpg"),
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[1]",
            "binary_signs[2]",
            "signature"
        )]
    );
}

/// Two entries under different gates cannot be proven to both fire; two under
/// the same gate still overwrite each other, and so does an ungated entry
/// paired with a gated one — the ungated one runs every time.
#[test]
fn entries_under_different_gates_warn_nothing() {
    use anodizer_core::config::SignConfig;
    let entry = |gate: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        if_condition: Some(gate.to_string()),
        ..Default::default()
    };
    let ungated = SignConfig {
        cmd: Some("cosign".to_string()),
        ..Default::default()
    };
    let warnings_for = |pair: Vec<SignConfig>| {
        let config = Config {
            binary_signs: pair,
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        warnings
    };
    assert!(
        warnings_for(vec![
            entry("{{ IsSnapshot }}"),
            entry("{{ not IsSnapshot }}")
        ])
        .is_empty()
    );
    assert_eq!(
        warnings_for(vec![entry("{{ IsSnapshot }}"), entry("{{ IsSnapshot }}")]).len(),
        1
    );
    assert_eq!(
        warnings_for(vec![ungated.clone(), entry("{{ IsSnapshot }}")]).len(),
        1
    );
    assert_eq!(
        warnings_for(vec![entry("{{ IsSnapshot }}"), ungated]).len(),
        1
    );
    // An empty `if:` always runs, exactly like an absent one, so it pairs
    // with a real gate rather than reading as a second gate.
    assert_eq!(
        warnings_for(vec![entry(""), entry("{{ IsSnapshot }}")]).len(),
        1
    );
    assert_eq!(
        warnings_for(vec![entry("{{ IsSnapshot }}"), entry("")]).len(),
        1
    );
}

/// Two spellings of one literal path are one file, the same answer the sign
/// stage reaches by folding `.` and `..` before it compares two outputs.
#[test]
fn two_spellings_of_one_signature_path_warn() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![entry("dist/sigs/app.sig"), entry("./dist/sigs/app.sig")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    // `{{ .Artifact }}` expands to the artifact's whole path, which already
    // carries `dist`, so the two spellings really do write two files
    // (`dist/app.sig` and `dist/dist/app.sig`) and neither is joined onto
    // the other.
    let templated = Config {
        binary_signs: vec![
            entry("{{ .Artifact }}.sig"),
            entry("dist/{{ .Artifact }}.sig"),
        ],
        ..Default::default()
    };
    let mut none = Vec::new();
    check_sign_duplicate_outputs(&templated, &mut none);
    assert!(none.is_empty(), "{none:?}");
}

/// A rendering that is not under `dist` is placed under it by the sign
/// stage, so `app.sig` and `dist/app.sig` are one file and the second `cmd:`
/// overwrites the first.
#[test]
fn a_signature_outside_dist_names_the_same_file_as_its_dist_spelling() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![entry("app.sig"), entry("dist/app.sig")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    // A `dist:` the config moved is the one the join uses, so a spelling
    // under the OLD default is a different file.
    let moved = Config {
        dist: std::path::PathBuf::from("out"),
        binary_signs: vec![entry("app.sig"), entry("dist/app.sig")],
        ..Default::default()
    };
    let mut none = Vec::new();
    check_sign_duplicate_outputs(&moved, &mut none);
    assert!(none.is_empty(), "{none:?}");
}

/// Two templates that differ only in a `./` around the SAME placeholder name
/// one file: the literal segments fold as path components while the
/// placeholder stays opaque.
#[test]
fn two_spellings_of_one_templated_signature_path_warn() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![
            entry("dist/sigs/{{ .Artifact }}.sig"),
            entry("dist/./sigs/../sigs/{{ .Artifact }}.sig"),
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    // Two DIFFERENT placeholders render two names, so the fold must keep
    // them apart.
    let distinct = Config {
        binary_signs: vec![
            entry("dist/{{ .Artifact }}.sig"),
            entry("./dist/{{ .Binary }}.sig"),
        ],
        ..Default::default()
    };
    let mut none = Vec::new();
    check_sign_duplicate_outputs(&distinct, &mut none);
    assert!(none.is_empty(), "{none:?}");
}

/// A template that renders outside `dist` is placed under it by the sign
/// stage, exactly as a literal path is, so `{{ ProjectName }}.sig` and
/// `dist/{{ ProjectName }}.sig` name one file.
#[test]
fn a_templated_signature_outside_dist_names_its_dist_spelling() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![
            entry("{{ ProjectName }}-{{ Version }}.sig"),
            entry("dist/{{ ProjectName }}-{{ Version }}.sig"),
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    // Two different placeholders render two names, so the join must not
    // fold them together.
    let distinct = Config {
        binary_signs: vec![
            entry("{{ ProjectName }}.sig"),
            entry("dist/{{ Binary }}.sig"),
        ],
        ..Default::default()
    };
    let mut none = Vec::new();
    check_sign_duplicate_outputs(&distinct, &mut none);
    assert!(none.is_empty(), "{none:?}");
}

/// The padding inside `{{ … }}` is not part of what a placeholder renders,
/// so `{{ Target }}` and `{{Target}}` are one placeholder.
#[test]
fn placeholder_spacing_does_not_split_one_template_in_two() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    for pair in [
        ["dist/{{ Target }}.sig", "./dist/{{Target}}.sig"],
        ["{{ Version }}.sig", "dist/{{Version}}.sig"],
    ] {
        let config = Config {
            binary_signs: vec![entry(pair[0]), entry(pair[1])],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert_eq!(
            warnings,
            vec![one_file_warning(
                "binary_signs[0]",
                "binary_signs[1]",
                "signature"
            )],
            "{pair:?}"
        );
    }
}

/// An unterminated `{{` is answered, not parsed: the run is opaque to the
/// end of the string, so the pair still compares and a `..` inside it cannot
/// climb out of the placeholder.
#[test]
fn an_unterminated_placeholder_is_opaque_to_the_end() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![entry("dist/{{ Version.sig"), entry("./dist/{{ Version.sig")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    let climbing = Config {
        binary_signs: vec![entry("dist/{{ Version/../app.sig"), entry("dist/app.sig")],
        ..Default::default()
    };
    let mut none = Vec::new();
    check_sign_duplicate_outputs(&climbing, &mut none);
    assert!(none.is_empty(), "{none:?}");
}

/// A spelling holding a placeholder that renders a whole PATH is compared
/// without the `dist` join, whatever the placeholder is called: the run
/// resolves it to a path that already carries `dist`, so joining `dist` a
/// second time would call two different files one.
#[test]
fn a_spelling_that_renders_a_path_is_compared_without_the_dist_join() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    for pair in [
        // The shell-style siblings of `{{ .Artifact }}`, expanded after the
        // render — `${artifact}.sig` is also the imported GoReleaser default.
        ["${artifact}.sig", "dist/${artifact}.sig"],
        ["$artifact.sig", "dist/$artifact.sig"],
        ["${signature}.asc", "dist/${signature}.asc"],
        ["$signature.asc", "dist/$signature.asc"],
        ["${certificate}.pem", "dist/${certificate}.pem"],
        ["$certificate.pem", "dist/$certificate.pem"],
        // A variable the operator points wherever they like.
        [
            "{{ .Env.SIG_DIR }}/app.sig",
            "dist/{{ .Env.SIG_DIR }}/app.sig",
        ],
        [
            "{{ Var.sig_dir }}/app.sig",
            "dist/{{ Var.sig_dir }}/app.sig",
        ],
        // One unbounded placeholder is enough, however many bounded ones
        // stand beside it.
        [
            "{{ .Artifact }}-{{ Version }}.sig",
            "dist/{{ .Artifact }}-{{ Version }}.sig",
        ],
    ] {
        let config = Config {
            binary_signs: vec![entry(pair[0]), entry(pair[1])],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert!(warnings.is_empty(), "{pair:?}: {warnings:?}");
    }

    // `$artifactName` and `$artifactID` are variables of those names, each
    // expanding to a NAME, so a prefix match on `$artifact` must not read
    // them as paths and skip the join.
    for pair in [
        ["$artifactName.sig", "dist/$artifactName.sig"],
        ["$artifactID.sig", "dist/$artifactID.sig"],
    ] {
        let config = Config {
            binary_signs: vec![entry(pair[0]), entry(pair[1])],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert_eq!(
            warnings,
            vec![one_file_warning(
                "binary_signs[0]",
                "binary_signs[1]",
                "signature"
            )],
            "{pair:?}"
        );
    }

    // Only the bounded name-only variables keep the join, so the pair the
    // check really is about still warns.
    let bounded = Config {
        binary_signs: vec![
            entry("{{ ProjectName }}-{{ Version }}.sig"),
            entry("dist/{{ ProjectName }}-{{ Version }}.sig"),
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&bounded, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );
}

/// A `}}` inside a quoted literal closes the run early, so the tail it
/// leaves behind is read as real path components rather than as part of the
/// placeholder.
#[test]
fn a_placeholder_closed_by_a_quoted_brace_leaves_its_tail_unmasked() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![
            entry(r#"dist/{{ printf "}}" }}/sigs/app.sig"#),
            entry(r#"./dist/{{ printf "}}" }}/sigs/../sigs/app.sig"#),
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );
}

/// `signs:` entries overwrite each other exactly as `binary_signs:` entries
/// do — the same struct, the same resolver, the same `dist`.
#[test]
fn two_signs_entries_resolving_one_file_warn() {
    use anodizer_core::config::SignConfig;
    let entry = |signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        artifacts: Some("all".to_string()),
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    let config = Config {
        signs: vec![entry("app.sig"), entry("dist/app.sig")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning("signs[0]", "signs[1]", "signature")]
    );
}

/// The repo's own documented multi-signer config signs two disjoint kinds,
/// so neither entry can overwrite the other's output however they name it.
/// `signs:` resolves an absent `artifacts:` to `none`, which selects nothing
/// at all, so a pair that sets no filter is quiet for the same reason.
#[test]
fn sign_entries_selecting_disjoint_artifact_kinds_warn_nothing() {
    use anodizer_core::config::SignConfig;
    let entry = |artifacts: Option<&str>, cmd: &str| SignConfig {
        artifacts: artifacts.map(str::to_string),
        cmd: Some(cmd.to_string()),
        args: Some(vec!["${signature}".to_string(), "${artifact}".to_string()]),
        ..Default::default()
    };
    for pair in [
        // docs/site/content/docs/sign/binaries-archives.md, "Multiple
        // signing configs".
        vec![
            entry(Some("archive"), "gpg"),
            entry(Some("checksum"), "cosign"),
        ],
        vec![entry(None, "gpg"), entry(None, "cosign")],
    ] {
        let config = Config {
            signs: pair,
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert!(warnings.is_empty(), "{warnings:?}");
    }

    // The same two entries under a filter that takes every kind really do
    // overwrite each other.
    let both = Config {
        signs: vec![entry(Some("all"), "gpg"), entry(Some("all"), "cosign")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&both, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning("signs[0]", "signs[1]", "signature")]
    );
}

/// `binary_signs:` resolves an absent `artifacts:` to `binary`, so two
/// entries that set no filter still meet — the default of that slice is not
/// the default of `signs:`.
#[test]
fn the_artifacts_term_reads_each_slices_own_default() {
    use anodizer_core::config::SignConfig;
    let entry = |cmd: &str| SignConfig {
        cmd: Some(cmd.to_string()),
        ..Default::default()
    };
    let config = Config {
        binary_signs: vec![entry("cosign"), entry("gpg")],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning(
            "binary_signs[0]",
            "binary_signs[1]",
            "signature"
        )]
    );

    // `windows` and `binary` both take a `Binary`, so the two meet. Written
    // on `signs:`, the slice whose loader accepts both values — a
    // `binary_signs:` entry can only ever say `binary` or `none`.
    let windows = Config {
        signs: vec![
            SignConfig {
                artifacts: Some("windows".to_string()),
                ..entry("osslsigncode")
            },
            SignConfig {
                artifacts: Some("binary".to_string()),
                ..entry("gpg")
            },
        ],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_sign_duplicate_outputs(&windows, &mut warnings);
    assert_eq!(
        warnings,
        vec![one_file_warning("signs[0]", "signs[1]", "signature")]
    );
}

/// An unpadded `{{.Artifact}}` is substituted by nothing and reaches the
/// template engine as an undefined variable, so it can only fail the run.
/// Every other padding of the same name fails identically, because the
/// substitution is by exact literal.
#[test]
fn a_mis_padded_literal_placeholder_warns() {
    use anodizer_core::config::SignConfig;
    for spelling in [
        "{{.Artifact}}",
        "{{Artifact}}",
        "{{ .Artifact}}",
        "{{.Artifact }}",
        "{{  .Artifact  }}",
        "{{ Artifact}}",
    ] {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(format!("{spelling}.sig")),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert_eq!(
            warnings,
            vec![format!(
                "binary_signs[0].signature names `{spelling}`, which anodizer \
                 substitutes only as the literal `{{{{ .Artifact }}}}` or \
                 `{{{{ Artifact }}}}` — every other spelling reaches the \
                 template engine as an undefined variable and fails the sign \
                 stage"
            )]
        );
    }

    // The two spellings the stage really does substitute warn nothing.
    for spelling in ["{{ .Artifact }}", "{{ Artifact }}"] {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(format!("{spelling}.sig")),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert!(warnings.is_empty(), "{spelling}: {warnings:?}");
    }
}

/// `signature:` and `certificate:` are what the signature and certificate
/// paths are derived FROM, so those two names have no value there in any
/// padding. The remedy has to be something that works: the sibling output's
/// shell-style name resolves after the render, but the field's OWN name
/// resolves to this template's unexpanded text, so there the only answer is
/// to drop the reference.
#[test]
fn a_placeholder_the_field_never_substitutes_warns_in_every_padding() {
    use anodizer_core::config::SignConfig;
    let derived = |field: &str, shell: &str| {
        format!(
            "; the {field} path is what this template renders, so \
             `${{{shell}}}` has no value here either — remove the reference"
        )
    };
    let sibling = |shell: &str| {
        format!("; write `${{{shell}}}`, which the sign stage expands after the render")
    };
    for (field, spelling, remedy) in [
        (
            "signature",
            "{{ .Signature }}",
            derived("signature", "signature"),
        ),
        (
            "signature",
            "{{.Signature}}",
            derived("signature", "signature"),
        ),
        (
            "certificate",
            "{{ Certificate }}",
            derived("certificate", "certificate"),
        ),
        ("signature", "{{ Certificate }}", sibling("certificate")),
        ("certificate", "{{ .Signature }}", sibling("signature")),
    ] {
        let mut cfg = SignConfig::default();
        match field {
            "signature" => cfg.signature = Some(format!("{spelling}.x")),
            _ => cfg.certificate = Some(format!("{spelling}.x")),
        }
        let config = Config {
            binary_signs: vec![cfg],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert_eq!(
            warnings,
            vec![format!(
                "binary_signs[0].{field} names `{spelling}`, which anodizer \
                 does not substitute in {field}: — it reaches the template \
                 engine as an undefined variable and fails the sign \
                 stage{remedy}"
            )],
            "{spelling} in {field}"
        );
    }
}

/// A placeholder written inside an expression is missed by the literal
/// replacement exactly as a mis-padded one is, and the name is seeded in no
/// template context, so the render fails either way.
#[test]
fn a_placeholder_inside_an_expression_warns() {
    use anodizer_core::config::SignConfig;
    for spelling in [
        "{{ Artifact | upper }}",
        "{{ Artifact.path }}",
        "{{ .Artifact | default(value=\"x\") }}",
    ] {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(format!("{spelling}.sig")),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert_eq!(
            warnings,
            vec![format!(
                "binary_signs[0].signature names `{spelling}`, which anodizer \
                 substitutes only as the literal `{{{{ .Artifact }}}}` or \
                 `{{{{ Artifact }}}}` — every other spelling reaches the \
                 template engine as an undefined variable and fails the sign \
                 stage"
            )]
        );
    }

    // A name that merely starts or ends the same is a different variable,
    // and a name inside a quoted literal is text Tera never looks up.
    for spelling in [
        "{{ ArtifactName }}",
        "{{ my_Artifact }}",
        "{{ my_artifact }}",
        "{{ \"Artifact\" }}",
        "{{ Version | replace(from=\"Artifact\", to=\"x\") }}",
        "{{ ['Artifact'] | join(sep=\"-\") }}",
    ] {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(format!("{spelling}.sig")),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert!(warnings.is_empty(), "{spelling}: {warnings:?}");
    }
}

/// A statement block reads its names out of the same template context an
/// expression does, so `{% set x = Artifact %}` fails the render exactly as
/// `{{ Artifact | upper }}` does and is warned about the same way.
#[test]
fn a_placeholder_inside_a_statement_block_warns() {
    use anodizer_core::config::SignConfig;
    let spelling = "{% set x = Artifact %}";
    let config = Config {
        binary_signs: vec![SignConfig {
            signature: Some(format!("{spelling}out.sig")),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![format!(
            "binary_signs[0].signature names `{spelling}`, which anodizer \
             substitutes only as the literal `{{{{ .Artifact }}}}` or \
             `{{{{ Artifact }}}}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
        )]
    );
}

/// The three openers close on three different delimiters, so an opener
/// whose own closer is missing is stepped over rather than ending the scan:
/// a `{{` with no `}}` can still be followed by a complete `{% … %}`, and
/// breaking there would leave that statement unread. A run that closes
/// AFTER another opener is still one run, and still warned about.
#[test]
fn an_unclosed_run_does_not_hide_the_runs_after_it() {
    use anodizer_core::config::SignConfig;
    let warnings_for = |template: &str| {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(template.to_string()),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        warnings
    };
    // Nothing complete follows the unterminated opener.
    assert!(warnings_for("{{ Artifact | upper").is_empty());
    assert!(warnings_for("out.sig {{ .Artifact").is_empty());
    assert_eq!(warnings_for("{{ oops {{ Artifact }}.sig").len(), 1);
    assert!(warnings_for("{{ .Artifact }}{{ Artifact }}.sig").is_empty());

    // A complete run of the OTHER kind after an unterminated one is found.
    assert_eq!(
        warnings_for("{{ oops {% set x = Artifact %}"),
        vec![
            "binary_signs[0].signature names `{% set x = Artifact %}`, which \
             anodizer substitutes only as the literal `{{ .Artifact }}` or \
             `{{ Artifact }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string()
        ]
    );
    assert_eq!(
        warnings_for("{% oops {{ Artifact | upper }}"),
        vec![
            "binary_signs[0].signature names `{{ Artifact | upper }}`, which \
             anodizer substitutes only as the literal `{{ .Artifact }}` or \
             `{{ Artifact }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string()
        ]
    );
    // The same fall-through reaches a name written after an unterminated
    // comment, whose own `{#` is what really fails the parse.
    assert_eq!(warnings_for("{# oops {{ Artifact | upper }}").len(), 1);
}

/// Tera opens a string literal on a single quote, a double quote or a
/// backtick, and a backslash inside one escapes the next character. So all
/// three spellings are text it never looks a name up in, and an escaped
/// quote does not end the literal it sits in.
#[test]
fn a_name_inside_any_tera_string_literal_warns_nothing() {
    use anodizer_core::config::SignConfig;
    for spelling in [
        "{{ `Artifact` }}",
        "{{ \"he said \\\"Artifact\\\"\" }}",
        "{{ Version | replace(from=`Artifact`, to=\"x\") }}",
    ] {
        let config = Config {
            binary_signs: vec![SignConfig {
                signature: Some(format!("{spelling}.sig")),
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_unpadded_sign_placeholders(&config, &mut warnings);
        assert!(warnings.is_empty(), "{spelling}: {warnings:?}");
    }

    // A name OUTSIDE the literal is still found.
    let config = Config {
        binary_signs: vec![SignConfig {
            signature: Some("{{ `x` }}{{ Artifact | upper }}.sig".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "{warnings:?}");
}

/// Tera strips a `{# … #}` comment before evaluating the template, so a
/// placeholder written inside one cannot fail the render and is not warned
/// about — while one written after the comment still is.
#[test]
fn a_placeholder_inside_a_tera_comment_warns_nothing() {
    use anodizer_core::config::SignConfig;
    let config = Config {
        binary_signs: vec![SignConfig {
            signature: Some("{# {{.Artifact}} #}out.sig".to_string()),
            certificate: Some("{# note #}{{.Artifact}}.pem".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "binary_signs[0].certificate names `{{.Artifact}}`, which anodizer \
             substitutes only as the literal `{{ .Artifact }}` or \
             `{{ Artifact }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string(),
        ]
    );
}

/// `args:` substitutes all three names, so only the padding is wrong there.
#[test]
fn an_args_template_substitutes_every_placeholder_name() {
    use anodizer_core::config::SignConfig;
    let config = Config {
        binary_signs: vec![SignConfig {
            args: Some(vec![
                "{{ .Signature }}".to_string(),
                "{{ Certificate }}".to_string(),
                "{{.Signature}}".to_string(),
            ]),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "binary_signs[0].args names `{{.Signature}}`, which anodizer \
             substitutes only as the literal `{{ .Signature }}` or \
             `{{ Signature }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string(),
        ]
    );
}

/// `stdin:` is handed to the template engine raw, so every one of the three
/// names fails there in either padding. A `signs:` entry can still reach the
/// value through the shell-style spelling; a `docker_signs:` entry's stdin
/// is not shell-expanded, so the warning offers no remedy it cannot keep.
#[test]
fn a_stdin_template_substitutes_no_placeholder() {
    use anodizer_core::config::{DockerSignConfig, SignConfig};
    let config = Config {
        binary_signs: vec![SignConfig {
            stdin: Some("{{ .Artifact }}".to_string()),
            ..Default::default()
        }],
        docker_signs: Some(vec![DockerSignConfig {
            stdin: Some("{{ Signature }}".to_string()),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "binary_signs[0].stdin names `{{ .Artifact }}`, which anodizer does \
             not substitute in stdin: — it reaches the template engine as an \
             undefined variable and fails the sign stage; write `${artifact}`, \
             which the sign stage expands after the render"
                .to_string(),
            "docker_signs[0].stdin names `{{ Signature }}`, which anodizer does \
             not substitute in stdin: — it reaches the template engine as an \
             undefined variable and fails the sign stage"
                .to_string(),
        ]
    );
}

/// The `docker_signs:` argv is substituted the same three ways as a sign
/// entry's, so a mis-padded name warns there too.
#[test]
fn a_docker_args_placeholder_warns_on_its_padding() {
    use anodizer_core::config::DockerSignConfig;
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            args: Some(vec!["{{.Certificate}}".to_string()]),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "docker_signs[0].args names `{{.Certificate}}`, which anodizer \
             substitutes only as the literal `{{ .Certificate }}` or \
             `{{ Certificate }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string(),
        ]
    );
}

/// A slice the `defaults:` fold filled holds an entry the operator never
/// wrote, so every check that names a block names the `defaults.` one.
#[test]
fn a_defaults_filled_sign_slice_is_named_as_the_defaults_block() {
    use anodizer_core::config::{Defaults, DockerSignConfig, SignConfig};
    let mut config = Config {
        project_name: "test".to_string(),
        defaults: Some(Defaults {
            sign: Some(SignConfig {
                args: Some(vec!["{{.Artifact}}".to_string()]),
                artifacts: Some("bogus".to_string()),
                ..Default::default()
            }),
            binary_signs: Some(SignConfig {
                stdin: Some("{{ Signature }}".to_string()),
                ..Default::default()
            }),
            docker_signs: Some(DockerSignConfig {
                args: Some(vec!["{{Artifact}}".to_string()]),
                ..Default::default()
            }),
            ..Default::default()
        }),
        ..Default::default()
    };
    anodizer_core::defaults_merge::apply_defaults(&mut config);

    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "defaults.sign.args names `{{.Artifact}}`, which anodizer \
             substitutes only as the literal `{{ .Artifact }}` or \
             `{{ Artifact }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string(),
            "defaults.binary_signs.stdin names `{{ Signature }}`, which \
             anodizer does not substitute in stdin: — it reaches the template \
             engine as an undefined variable and fails the sign stage; write \
             `${signature}`, which the sign stage expands after the render"
                .to_string(),
            "defaults.docker_signs.args names `{{Artifact}}`, which anodizer \
             substitutes only as the literal `{{ .Artifact }}` or \
             `{{ Artifact }}` — every other spelling reaches the template \
             engine as an undefined variable and fails the sign stage"
                .to_string(),
        ]
    );

    let mut warnings = Vec::new();
    check_sign_artifact_filters(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![format!(
            "unrecognized defaults.sign artifacts filter 'bogus' (valid: {})",
            anodizer_stage_sign::VALID_SIGN_ARTIFACT_FILTERS.join(", ")
        )]
    );
}

/// Every double-quoted string literal in `src`, with `\`-newline
/// continuations resolved the way rustc resolves them: the escape eats the
/// newline and the indentation after it, so what is left is the text a
/// message really carries.
fn message_literals(src: &str) -> Vec<String> {
    let chars: Vec<char> = src.chars().collect();
    let mut out = Vec::new();
    let mut i = 0;
    while i < chars.len() {
        // A `//` comment can hold an unbalanced quote.
        if chars[i] == '/' && chars.get(i + 1) == Some(&'/') {
            while i < chars.len() && chars[i] != '\n' {
                i += 1;
            }
            continue;
        }
        // A raw string processes no escape, so it is read to its own
        // terminator rather than through the escape rules below.
        if chars[i] == 'r' {
            let mut j = i + 1;
            while chars.get(j) == Some(&'#') {
                j += 1;
            }
            if chars.get(j) == Some(&'"') {
                let hashes = j - i - 1;
                let mut k = j + 1;
                loop {
                    match chars.get(k) {
                        None => break,
                        Some('"') if chars[k + 1..k + 1 + hashes].iter().all(|c| *c == '#') => {
                            break;
                        }
                        Some(_) => k += 1,
                    }
                }
                out.push(chars[j + 1..k.min(chars.len())].iter().collect());
                i = (k + 1 + hashes).min(chars.len());
                continue;
            }
        }
        if chars[i] != '"' {
            i += 1;
            continue;
        }
        i += 1;
        let mut literal = String::new();
        while i < chars.len() && chars[i] != '"' {
            if chars[i] == '\\' {
                i += 1;
                match chars.get(i) {
                    Some('\n') => {
                        i += 1;
                        while matches!(chars.get(i), Some(' ') | Some('\t')) {
                            i += 1;
                        }
                    }
                    Some(_) => i += 1,
                    None => break,
                }
                continue;
            }
            literal.push(chars[i]);
            i += 1;
        }
        i += 1;
        out.push(literal);
    }
    out
}

/// A format string broken across source lines needs a `\` continuation: the
/// escape eats the newline AND the indentation after it. Written without
/// one, that indentation goes into the message, and `check config` prints a
/// single 300-column line carrying 26-space runs — which every assertion
/// shaped like `starts_with(…)` reads straight past.
///
/// So no message this module builds may carry a run of three spaces —
/// asked of every production source under `check/config/`, not just the one
/// that happened to hold the defect.
/// How many function bodies under `check/config/` build a message. Pinned
/// so a rename or a move that empties the walk fails instead of passing
/// with nothing to ask.
const MESSAGE_BUILDING_BODIES: usize = 31;

#[test]
fn no_check_config_message_carries_a_run_of_spaces() {
    use anodizer_core::test_helpers::test_sources::{
        function_bodies, production_half, rust_sources,
    };

    let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/commands/check/config");
    let sources = rust_sources(std::path::Path::new(dir));
    assert_eq!(
        sources.len(),
        5,
        "the production sources under {dir} the walk found: {sources:?}"
    );
    let building: Vec<String> = sources
        .iter()
        .flat_map(|path| {
            let src =
                std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {path:?}: {e}"));
            function_bodies(production_half(&src))
        })
        .filter(|body| body.contains("format!("))
        .collect();
    assert_eq!(
        building.len(),
        MESSAGE_BUILDING_BODIES,
        "the message-building bodies the walk found under {dir}"
    );
    let offenders: Vec<String> = building
        .iter()
        .flat_map(|body| message_literals(body))
        .filter(|literal| literal.contains("   "))
        .collect();
    assert!(
        offenders.is_empty(),
        "a message literal carries a run of three or more spaces, so its line \
         continuation is missing and the warning prints this file's own \
         indentation: {offenders:?}"
    );
}

/// The filter check walks every sign slice, so an unrecognized value on a
/// per-crate slice is caught exactly as one on the top-level `signs:` is.
///
/// Both arms are `signs:`, which is the only slice a YAML file can write an
/// unrecognized filter on: `binary_signs:` is loaded through a deserializer
/// that refuses everything but `binary` and `none`, so its own vocabulary is
/// asked on the one route past that deserializer —
/// `a_wide_filter_under_defaults_binary_signs_warns`.
#[test]
fn an_unrecognized_filter_warns_on_every_sign_slice() {
    let yaml = r#"
project_name: test
signs:
  - artifacts: bogus
workspaces:
  - name: ws
    crates:
      - name: app
    signs:
      - artifacts: bogus
"#;
    let mut config: Config = serde_yaml_ng::from_str(yaml).expect("the loader accepts it");
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    let mut warnings = Vec::new();
    check_sign_artifact_filters(&config, &mut warnings);
    let valid = anodizer_stage_sign::VALID_SIGN_ARTIFACT_FILTERS.join(", ");
    assert_eq!(
        warnings,
        vec![
            format!("unrecognized signs[0] artifacts filter 'bogus' (valid: {valid})"),
            format!(
                "unrecognized workspaces.ws.signs[0] artifacts filter 'bogus' (valid: {valid})"
            ),
        ]
    );
}

/// `defaults.binary_signs:` is a plain `SignConfig` the defaults fold copies
/// into the slice, so it is the one route by which a filter the
/// `binary_signs:` loader refuses reaches the run — where it is ignored and
/// every binary is signed anyway. Driven through YAML, which is the only way
/// the config could be written.
#[test]
fn a_wide_filter_under_defaults_binary_signs_warns() {
    let yaml = r#"
project_name: test
defaults:
  binary_signs:
    artifacts: archive
    cmd: cosign
"#;
    let mut config: Config = serde_yaml_ng::from_str(yaml).expect("the loader accepts it");
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    let mut warnings = Vec::new();
    check_sign_artifact_filters(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "defaults.binary_signs artifacts filter 'archive' is not allowed \
             on binary_signs (valid: binary, none) — the sign stage signs \
             binaries whatever it says"
                .to_string(),
        ]
    );

    // The two values the field really does take warn nothing.
    for filter in ["binary", "none"] {
        let mut config: Config = serde_yaml_ng::from_str(&format!(
            "project_name: test\ndefaults:\n  binary_signs:\n    artifacts: {filter}\n"
        ))
        .expect("the loader accepts it");
        anodizer_core::defaults_merge::apply_defaults(&mut config);
        let mut warnings = Vec::new();
        check_sign_artifact_filters(&config, &mut warnings);
        assert!(warnings.is_empty(), "{filter}: {warnings:?}");
    }
}

/// The docker sign path renders its templates and substitutes
/// `{{ .Artifact }}` / `{{ .Signature }}` by literal; it never expands the
/// `${…}` variables the detached sign path does, so a shell-style reference
/// reaches cosign as text. `stdin:` substitutes nothing at all, so it is
/// offered no remedy.
#[test]
fn a_docker_shell_variable_warns_that_it_is_never_expanded() {
    use anodizer_core::config::DockerSignConfig;
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            args: Some(vec![
                "sign".to_string(),
                "${artifact}".to_string(),
                "--certificate=$certificate".to_string(),
            ]),
            stdin: Some("${signature}".to_string()),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "docker_signs[0].args names `${artifact}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text; write `{{ .Artifact }}`, which anodizer substitutes \
             before the render"
                .to_string(),
            "docker_signs[0].args names `${certificate}`, which the docker \
             sign path never expands — it reaches the signing command as that \
             literal text; a docker certificate path is read nowhere, so \
             remove the reference"
                .to_string(),
            "docker_signs[0].stdin names `${signature}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text"
                .to_string(),
        ]
    );

    // The spellings the docker path really does substitute warn nothing.
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            args: Some(vec![
                "{{ .Artifact }}@{{ .Digest }}".to_string(),
                "{{ Signature }}".to_string(),
            ]),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert!(warnings.is_empty(), "{warnings:?}");
}

/// `${digest}` and `${artifactID}` expand nowhere either — the docker path
/// seeds those two as TEMPLATE variables — so each is warned about with the
/// spelling that renders instead of the one that is substituted, on `stdin:`
/// as well as on `args:` because `stdin:` is rendered too.
#[test]
fn a_docker_digest_shell_variable_warns_with_the_template_spelling() {
    use anodizer_core::config::DockerSignConfig;
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            args: Some(vec![
                "sign".to_string(),
                "${artifact}@${digest}".to_string(),
                "--annotation=id=$artifactID".to_string(),
            ]),
            stdin: Some("${digest}".to_string()),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "docker_signs[0].args names `${artifact}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text; write `{{ .Artifact }}`, which anodizer substitutes \
             before the render"
                .to_string(),
            "docker_signs[0].args names `${digest}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text; write `{{ .Digest }}`, which the docker sign path \
             renders from the image"
                .to_string(),
            "docker_signs[0].args names `${artifactID}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text; write `{{ .ArtifactID }}`, which the docker sign \
             path renders from the image"
                .to_string(),
            "docker_signs[0].stdin names `${digest}`, which the docker sign \
             path never expands — it reaches the signing command as that \
             literal text; write `{{ .Digest }}`, which the docker sign path \
             renders from the image"
                .to_string(),
        ]
    );

    // The template spellings themselves warn nothing.
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            args: Some(vec!["{{ .Artifact }}@{{ .Digest }}".to_string()]),
            stdin: Some("{{ ArtifactID }}".to_string()),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert!(warnings.is_empty(), "{warnings:?}");
}

/// A docker certificate path is read nowhere — only its presence is, to pick
/// cosign's bundle verify mode — so the placeholder the argv substitutes
/// resolves to the empty string and the argument ships with no value.
#[test]
fn a_docker_certificate_placeholder_warns_that_it_renders_empty() {
    use anodizer_core::config::DockerSignConfig;
    let config = Config {
        docker_signs: Some(vec![DockerSignConfig {
            certificate: Some("cert.pem".to_string()),
            args: Some(vec!["--certificate={{ .Certificate }}".to_string()]),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_unpadded_sign_placeholders(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "docker_signs[0].args names `{{ .Certificate }}`, which anodizer \
             substitutes with the empty string on the docker path — a docker \
             certificate path is read nowhere, so the argument reaches the \
             signing command with no value"
                .to_string(),
        ]
    );
}

/// A `docker_signs:` entry's `signature:` names no file — the signature is
/// stored in the registry — so setting it does nothing and check says so.
#[test]
fn a_docker_sign_signature_template_warns_that_it_is_ignored() {
    use anodizer_core::config::DockerSignConfig;
    let config = Config {
        docker_signs: Some(vec![
            DockerSignConfig {
                signature: Some("{{ .Artifact }}.sig".to_string()),
                ..Default::default()
            },
            DockerSignConfig::default(),
        ]),
        ..Default::default()
    };
    let mut warnings = Vec::new();
    check_docker_sign_signature_templates(&config, &mut warnings);
    assert_eq!(
        warnings,
        vec![
            "docker_signs[0].signature is set but a docker signature is stored \
             in the registry rather than written to a file (it will be ignored)"
                .to_string(),
        ]
    );
}

/// Two entries whose `signature:` templates differ write two files, and two
/// entries whose `ids:` cannot both take one binary never meet — neither is
/// the overwrite this warns about.
#[test]
fn binary_signs_entries_that_write_two_files_warn_nothing() {
    use anodizer_core::config::SignConfig;
    let entry = |ids: Option<Vec<String>>, signature: &str| SignConfig {
        cmd: Some("cosign".to_string()),
        ids,
        signature: Some(signature.to_string()),
        ..Default::default()
    };
    for pair in [
        vec![
            entry(None, "{{ .Artifact }}.sig"),
            entry(None, "{{ .Artifact }}.bundle.sig"),
        ],
        vec![
            entry(Some(vec!["app".to_string()]), "{{ .Artifact }}.sig"),
            entry(Some(vec!["helper".to_string()]), "{{ .Artifact }}.sig"),
        ],
    ] {
        let config = Config {
            binary_signs: pair,
            ..Default::default()
        };
        let mut warnings = Vec::new();
        check_sign_duplicate_outputs(&config, &mut warnings);
        assert!(warnings.is_empty(), "{warnings:?}");
    }
}

// ---- Target-triple validation tests ----

#[test]
fn target_triple_warns_on_unrecognized_in_defaults() {
    use anodizer_core::config::Defaults;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.defaults = Some(Defaults {
        targets: Some(vec![
            "x86_64-unknown-linux-gnu".to_string(), // valid
            "sparc-sun-solaris".to_string(),        // unknown arch AND os
        ]),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_target_triples(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "only the bad triple warns: {warnings:?}");
    assert!(
        warnings[0].contains("sparc-sun-solaris") && warnings[0].contains("defaults.targets"),
        "warning should name the triple and its context: {:?}",
        warnings
    );
}

#[test]
fn target_triple_warns_on_unrecognized_in_crate_build() {
    use anodizer_core::config::BuildConfig;
    let mut crate_cfg = make_crate("mycrate", "v{{ .Version }}", None);
    crate_cfg.builds = Some(vec![BuildConfig {
        binary: Some("mybin".to_string()),
        targets: Some(vec!["not-a-real-triple".to_string()]),
        ..Default::default()
    }]);
    let config = make_config(vec![crate_cfg]);
    let mut warnings: Vec<String> = vec![];
    check_target_triples(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("not-a-real-triple")
            && warnings[0].contains("crate 'mycrate'")
            && warnings[0].contains("build 'mybin'"),
        "warning should name the triple, crate, and build binary: {:?}",
        warnings
    );
}

#[test]
fn target_triple_silent_on_known_triples() {
    use anodizer_core::config::Defaults;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.defaults = Some(Defaults {
        targets: Some(vec![
            "aarch64-apple-darwin".to_string(),
            "x86_64-pc-windows-msvc".to_string(),
        ]),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_target_triples(&config, &mut warnings);
    assert!(
        warnings.is_empty(),
        "known triples must not warn: {warnings:?}"
    );
}

// ---- Changelog `use` validation tests ----

#[test]
fn changelog_use_warns_on_unrecognized_value() {
    use anodizer_core::config::ChangelogConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.changelog = Some(ChangelogConfig {
        use_source: Some("mercurial".to_string()),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_changelog(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("mercurial") && warnings[0].contains("git, github-native"),
        "warning should name the bad value and valid set: {:?}",
        warnings
    );
}

#[test]
fn changelog_use_silent_on_github_native() {
    use anodizer_core::config::ChangelogConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.changelog = Some(ChangelogConfig {
        use_source: Some("github-native".to_string()),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_changelog(&config, &mut warnings);
    assert!(warnings.is_empty(), "github-native is valid: {warnings:?}");
}

// ---- Checksum-algorithm validation tests ----

#[test]
fn checksum_algorithm_warns_on_unrecognized_in_defaults() {
    use anodizer_core::config::{ChecksumConfig, Defaults};
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.defaults = Some(Defaults {
        checksum: Some(ChecksumConfig {
            algorithm: Some("crc32".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_checksum_algorithms(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("crc32") && warnings[0].contains("defaults.checksum"),
        "warning should name the algorithm and context: {:?}",
        warnings
    );
}

#[test]
fn checksum_algorithm_warns_on_unrecognized_per_crate() {
    use anodizer_core::config::ChecksumConfig;
    let mut crate_cfg = make_crate("mycrate", "v{{ .Version }}", None);
    crate_cfg.checksum = Some(ChecksumConfig {
        algorithm: Some("md5".to_string()),
        ..Default::default()
    });
    let config = make_config(vec![crate_cfg]);
    let mut warnings: Vec<String> = vec![];
    check_checksum_algorithms(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("md5") && warnings[0].contains("mycrate"),
        "warning should name the algorithm and crate: {:?}",
        warnings
    );
}

#[test]
fn checksum_algorithm_silent_on_known_algorithm() {
    use anodizer_core::config::{ChecksumConfig, Defaults};
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.defaults = Some(Defaults {
        checksum: Some(ChecksumConfig {
            algorithm: Some("blake2b".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    let mut warnings: Vec<String> = vec![];
    check_checksum_algorithms(&config, &mut warnings);
    assert!(warnings.is_empty(), "blake2b is valid: {warnings:?}");
}

// ---- SBOM artifacts validation tests ----

#[test]
fn sbom_artifacts_errors_on_unrecognized_value() {
    use anodizer_core::config::SbomConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.sboms = vec![SbomConfig {
        id: Some("main".to_string()),
        artifacts: Some("everything".to_string()),
        ..Default::default()
    }];
    let mut errors: Vec<String> = vec![];
    check_sbom_configs(&config, &mut errors);
    assert_eq!(errors.len(), 1, "got: {errors:?}");
    assert!(
        errors[0].contains("everything") && errors[0].contains("main"),
        "error should name the value and the sbom label: {:?}",
        errors
    );
}

#[test]
fn sbom_artifacts_silent_on_known_value() {
    use anodizer_core::config::SbomConfig;
    let mut config = make_config(vec![make_crate("a", "a-v{{ .Version }}", None)]);
    config.sboms = vec![SbomConfig {
        artifacts: Some("binary".to_string()),
        ..Default::default()
    }];
    let mut errors: Vec<String> = vec![];
    check_sbom_configs(&config, &mut errors);
    assert!(
        errors.is_empty(),
        "'binary' is a valid artifacts type: {errors:?}"
    );
}

// ---- Announce secret-exposure: remaining channels ----

#[test]
fn announce_secret_warns_across_all_remaining_channels() {
    use anodizer_core::config::{
        DiscordAnnounce, LinkedInAnnounce, MastodonAnnounce, MattermostAnnounce,
        OpenCollectiveAnnounce, RedditAnnounce, TeamsAnnounce, TelegramAnnounce, WebhookConfig,
    };
    // Each channel content field carries a distinct secret-named ref so the
    // per-field warning routing (field label in the message) is exercised
    // once per channel branch.
    let warnings = collect_announce_warnings(AnnounceConfig {
        linkedin: Some(LinkedInAnnounce {
            message_template: Some("{{ Env.LINKEDIN_TOKEN }}".to_string()),
            ..Default::default()
        }),
        opencollective: Some(OpenCollectiveAnnounce {
            title_template: Some("{{ Env.OC_API_KEY }}".to_string()),
            message_template: Some("{{ Env.OC_SECRET }}".to_string()),
            ..Default::default()
        }),
        mastodon: Some(MastodonAnnounce {
            message_template: Some("{{ Env.MASTODON_TOKEN }}".to_string()),
            ..Default::default()
        }),
        discord: Some(DiscordAnnounce {
            message_template: Some("{{ Env.DISCORD_TOKEN }}".to_string()),
            author: Some("{{ Env.DISCORD_SECRET }}".to_string()),
            ..Default::default()
        }),
        webhook: Some(WebhookConfig {
            message_template: Some("{{ Env.WEBHOOK_TOKEN }}".to_string()),
            ..Default::default()
        }),
        telegram: Some(TelegramAnnounce {
            message_template: Some("{{ Env.TELEGRAM_TOKEN }}".to_string()),
            ..Default::default()
        }),
        teams: Some(TeamsAnnounce {
            message_template: Some("{{ Env.TEAMS_TOKEN }}".to_string()),
            title_template: Some("{{ Env.TEAMS_SECRET }}".to_string()),
            ..Default::default()
        }),
        mattermost: Some(MattermostAnnounce {
            message_template: Some("{{ Env.MM_TOKEN }}".to_string()),
            title_template: Some("{{ Env.MM_SECRET }}".to_string()),
            ..Default::default()
        }),
        reddit: Some(RedditAnnounce {
            title_template: Some("{{ Env.REDDIT_TOKEN }}".to_string()),
            url_template: Some("https://x/{{ Env.REDDIT_SECRET }}".to_string()),
            ..Default::default()
        }),
        ..Default::default()
    });
    // Two each for opencollective/discord/teams/mattermost/reddit + one each
    // for linkedin/mastodon/webhook/telegram = 5*2 + 4 = 14.
    assert_eq!(
        warnings.len(),
        14,
        "one warning per secret-named field: {warnings:?}"
    );
    for needle in [
        "announce.linkedin.message_template",
        "announce.opencollective.title_template",
        "announce.opencollective.message_template",
        "announce.mastodon.message_template",
        "announce.discord.message_template",
        "announce.discord.author",
        "announce.webhook.message_template",
        "announce.telegram.message_template",
        "announce.teams.message_template",
        "announce.teams.title_template",
        "announce.mattermost.message_template",
        "announce.mattermost.title_template",
        "announce.reddit.title_template",
        "announce.reddit.url_template",
    ] {
        assert!(
            warnings.iter().any(|w| w.contains(needle)),
            "missing warning for {needle}: {warnings:?}"
        );
    }
}

#[test]
fn announce_secret_warns_in_slack_attachment_text_fields() {
    use anodizer_core::config::{SlackAnnounce, SlackAttachment};
    // The attachment scan covers text/title/fallback/pretext/footer; drive
    // the first four (footer already has a dedicated test above).
    let warnings = collect_announce_warnings(AnnounceConfig {
        slack: Some(SlackAnnounce {
            attachments: Some(vec![SlackAttachment {
                text: Some("{{ Env.SLACK_A_TOKEN }}".to_string()),
                title: Some("{{ Env.SLACK_B_TOKEN }}".to_string()),
                fallback: Some("{{ Env.SLACK_C_TOKEN }}".to_string()),
                pretext: Some("{{ Env.SLACK_D_TOKEN }}".to_string()),
                ..Default::default()
            }]),
            ..Default::default()
        }),
        ..Default::default()
    });
    assert_eq!(
        warnings.len(),
        4,
        "one per attachment content field: {warnings:?}"
    );
    for suffix in [".text", ".title", ".fallback", ".pretext"] {
        assert!(
            warnings
                .iter()
                .any(|w| w.contains(&format!("announce.slack.attachments[0]{suffix}"))),
            "missing attachment{suffix} warning: {warnings:?}"
        );
    }
}

// ---- Signing-tool availability warnings ----

#[test]
fn signing_tools_warns_on_missing_sign_cmd() {
    // A `signs.cmd` naming a binary not on PATH must warn — the release
    // would otherwise fail at sign time with a less-actionable spawn error.
    let config = Config {
        project_name: "test".to_string(),
        signs: vec![anodizer_core::config::SignConfig {
            cmd: Some("anodizer-nonexistent-signer".to_string()),
            ..Default::default()
        }],
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_signing_tools(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("anodizer-nonexistent-signer")
            && warnings[0].contains("signs section"),
        "warning should name the missing tool and section: {:?}",
        warnings
    );
}

#[test]
fn signing_tools_warns_on_missing_docker_sign_cmd() {
    let config = Config {
        project_name: "test".to_string(),
        docker_signs: Some(vec![anodizer_core::config::DockerSignConfig {
            cmd: Some("anodizer-nonexistent-cosign".to_string()),
            ..Default::default()
        }]),
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_signing_tools(&config, &mut warnings);
    assert_eq!(warnings.len(), 1, "got: {warnings:?}");
    assert!(
        warnings[0].contains("anodizer-nonexistent-cosign")
            && warnings[0].contains("docker_signs section"),
        "warning should name the missing tool and section: {:?}",
        warnings
    );
}

#[test]
fn signing_tools_silent_when_no_signing_configured() {
    let config = Config {
        project_name: "test".to_string(),
        ..Default::default()
    };
    let mut warnings: Vec<String> = vec![];
    check_signing_tools(&config, &mut warnings);
    assert!(
        warnings.is_empty(),
        "no signing config → no warnings: {warnings:?}"
    );
}

/// The sign docs page quotes `check config` output as the operator sees it,
/// and a reworded message leaves those blocks quoting a line the binary no
/// longer prints. So the page's own ```yaml blocks ARE the fixtures: each
/// one is parsed, the five sign checks are run over it, and what they
/// produce must be exactly what the ```text block after it quotes — every
/// quoted line produced, and every produced line quoted, in that order.
///
/// Every yaml block has to load, and the count of `Warning ` lines is taken
/// over the WHOLE page rather than over the fixtures: a line quoted in a
/// block no fixture reaches would otherwise be counted by neither side.
///
/// What this covers is `check config`'s own sign warnings. The command also
/// runs the announce, structure and tooling checks, so a page block that
/// ever quotes one of THEIR warnings needs that check driven here too. The
/// page's `Error sign:` blocks come from the sign stage rather than from a
/// check function and are pinned in `crates/stage-sign/src/tests.rs`.
#[test]
fn every_warning_quoted_in_the_sign_docs_is_a_message_the_checks_produce() {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../docs/site/content/docs/sign/binaries-archives.md"
    );
    let page = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {path}: {e}"));
    let blocks = fenced_blocks(&page);

    let mut fixtures = 0usize;
    let mut refused = 0usize;
    for (at, (language, body)) in blocks.iter().enumerate() {
        if *language != "yaml" {
            continue;
        }
        // A fragment the loader refuses is not a config the page claims to
        // show output for. The count is pinned below, so one arriving is a
        // failure rather than a silent skip.
        let Ok(mut config) = serde_yaml_ng::from_str::<Config>(body) else {
            refused += 1;
            continue;
        };
        anodizer_core::defaults_merge::apply_defaults(&mut config);
        fixtures += 1;
        let mut produced: Vec<String> = vec![];
        check_sign_artifact_filters(&config, &mut produced);
        check_sign_asset_name_templates(&config, &mut produced);
        check_sign_duplicate_outputs(&config, &mut produced);
        check_unpadded_sign_placeholders(&config, &mut produced);
        check_docker_sign_signature_templates(&config, &mut produced);

        let quoted: Vec<String> = blocks[at + 1..]
            .iter()
            .take_while(|(language, _)| *language != "yaml")
            .flat_map(|(_, body)| body.lines())
            .filter_map(|line| line.trim_start().strip_prefix("Warning "))
            .map(str::to_string)
            .collect();
        assert_eq!(
            produced, quoted,
            "the config in block {at} and the output quoted under it disagree"
        );
    }
    assert_eq!(fixtures, 12, "the page's parseable config blocks");
    assert_eq!(refused, 0, "every config block on the page has to load");
    assert_eq!(
        quoted_warning_lines("sign/binaries-archives.md").len(),
        9,
        "the warnings the page quotes"
    );
}

/// Every fenced block on a docs page as `(language, body)`, in page order.
fn fenced_blocks(page: &str) -> Vec<(&str, &str)> {
    let mut blocks = Vec::new();
    let mut open: Option<(&str, usize)> = None;
    for line in page.lines() {
        let at = line.as_ptr() as usize - page.as_ptr() as usize;
        match (line.strip_prefix("```"), open) {
            (Some(_), Some((language, from))) => {
                blocks.push((language, &page[from..at]));
                open = None;
            }
            (Some(language), None) => open = Some((language.trim(), at + line.len() + 1)),
            (None, _) => {}
        }
    }
    blocks
}

/// The release-resilience page quotes the announce secret-exposure warning
/// the same way the sign page quotes its own, and the same rewording breaks
/// it. So that page's lint section is driven as a fixture too: its `yaml`
/// block is the config, and the `text` block under it is what the check has
/// to produce for it.
///
/// The count is taken over the whole page, not over that section, so a
/// `Warning ` quoted anywhere else on it fails until somebody pins it too.
#[test]
fn the_warning_quoted_in_the_resilience_docs_is_a_message_the_check_produces() {
    let path = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/../../docs/site/content/docs/advanced/release-resilience.md"
    );
    let page = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("read {path}: {e}"));
    let section = page
        .split_once("### Static lint — `anodizer check config`")
        .expect("the lint section is on the page")
        .1;
    let blocks = fenced_blocks(section);
    let yaml = blocks
        .iter()
        .find(|(language, _)| *language == "yaml")
        .expect("the section shows a config");
    let quoted: Vec<String> = blocks
        .iter()
        .find(|(language, _)| *language == "text")
        .expect("the section shows the output")
        .1
        .lines()
        .filter_map(|line| line.trim_start().strip_prefix("Warning "))
        .map(str::to_string)
        .collect();

    let mut config: Config = serde_yaml_ng::from_str(yaml.1).expect("the loader accepts it");
    anodizer_core::defaults_merge::apply_defaults(&mut config);
    let mut produced: Vec<String> = vec![];
    check_announce_secret_exposure(&config, &mut produced);
    assert_eq!(produced, quoted);
    assert_eq!(
        quoted_warning_lines("advanced/release-resilience.md").len(),
        1,
        "the warnings the page quotes"
    );
}

/// Read every line a docs page quotes under one gutter label, in page
/// order, with the label and the renderer's indentation stripped. A line
/// carrying the elision character is an abbreviation of real output rather
/// than a claim about it, so it is left out.
fn quoted_label_lines(relative: &str, label: &str) -> Vec<String> {
    let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../docs/site/content/docs")
        .join(relative);
    let page =
        std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
    page.lines()
        .filter_map(|line| line.trim_start().strip_prefix(label))
        .filter(|line| !line.contains('\u{2026}'))
        .map(str::to_string)
        .collect()
}

/// Every `Error ` line a docs page quotes.
fn quoted_error_lines(relative: &str) -> Vec<String> {
    quoted_label_lines(relative, "Error ")
}

/// Every `Warning ` line a docs page quotes.
fn quoted_warning_lines(relative: &str) -> Vec<String> {
    quoted_label_lines(relative, "Warning ")
}

/// The monorepo page and the release-resilience page both quote the workspace
/// membership guard's errors as the operator sees them, so a reword leaves
/// them showing a line the binary no longer prints. Each documented situation
/// is reproduced on its own temporary workspace and the pages' lines have to
/// be exactly what the guard produced.
///
/// The release-resilience page's other errors come from four more producers
/// and are pinned where each of them lives; this test asserts that page's
/// total error count too, so a newly quoted line fails here until it is
/// pinned somewhere.
#[test]
fn the_membership_errors_quoted_in_the_docs_are_what_the_guard_produces() {
    // A dependency on disk that the config never lists.
    let absent = tempdir().unwrap();
    write_disk_workspace(
        absent.path(),
        &[
            ("crates/cli", "anodizer", &["anodizer-stage-install-script"]),
            (
                "crates/stage-install-script",
                "anodizer-stage-install-script",
                &[],
            ),
        ],
    );
    let config = make_config(vec![with_active_cargo_publisher(CrateConfig {
        name: "anodizer".to_string(),
        path: p(absent.path(), "crates/cli"),
        tag_template: Some("v{{ .Version }}".to_string()),
        ..Default::default()
    })]);
    let mut produced = vec![];
    check_workspace_membership(
        &config,
        absent.path(),
        &flatten_crate_names(&config),
        &mut produced,
    );

    // A dependency the config lists but never uploads.
    let unpublished = tempdir().unwrap();
    write_disk_workspace(
        unpublished.path(),
        &[
            ("crates/cli", "anodizer", &["anodizer-core"]),
            ("crates/core", "anodizer-core", &[]),
        ],
    );
    let config = make_config(vec![
        with_active_cargo_publisher(CrateConfig {
            name: "anodizer".to_string(),
            path: p(unpublished.path(), "crates/cli"),
            tag_template: Some("v{{ .Version }}".to_string()),
            ..Default::default()
        }),
        CrateConfig {
            name: "anodizer-core".to_string(),
            path: p(unpublished.path(), "crates/core"),
            tag_template: Some("v{{ .Version }}".to_string()),
            ..Default::default()
        },
    ]);
    check_workspace_membership(
        &config,
        unpublished.path(),
        &flatten_crate_names(&config),
        &mut produced,
    );

    let monorepo = quoted_error_lines("advanced/monorepo.md");
    assert_eq!(monorepo, produced[..1], "the monorepo page's Error lines");
    assert_eq!(monorepo.len(), 1, "the errors the monorepo page quotes");

    let resilience = quoted_error_lines("advanced/release-resilience.md");
    assert_eq!(
        resilience[3..],
        produced[..],
        "the release-resilience page's last two Error lines"
    );
    assert_eq!(
        resilience.len(),
        5,
        "the errors the release-resilience page quotes"
    );
}