ostrya 0.19.1

Pure-Rust async reimplementation of the ostree repository library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
//! The typed view of the repository `config` file.
//!
//! This module re-exports each documented item of `ostrya_core::config`.
//! These items are the traits, [`Value`], [`ValueError`], the codec, the
//! groups `[core]` and `[ex-integrity]`, and the value types. The other items
//! are [`Lookup`], [`ConfigView`], [`Section`], [`RemoteSource`],
//! [`ConfigEdit`], [`SectionMut`], and [`ConfigError`]. The module adds
//! [`RepoConfig`], the other groups of the port, their value types, and the
//! extension traits of a section. A program that links `ostrya-core` and not
//! this crate takes the items from `ostrya_core::config`.
//!
//! - [`RepoConfig`] reads the keys of the repository groups.
//!   [`get`](RepoConfig::get), [`file_value`](RepoConfig::file_value), and
//!   [`lookup`](RepoConfig::lookup) read one key through its key type.
//!   [`section`](RepoConfig::section), [`sections`](RepoConfig::sections),
//!   and [`resolve`](RepoConfig::resolve) give the sections of a named group.
//!   [`check`](RepoConfig::check) checks the value of each key of the port
//!   that the file sets, and refuses an unknown key of a closed group of the
//!   port. [`refuse_unknown_keys`](RepoConfig::refuse_unknown_keys) refuses
//!   an unknown key of one closed group.
//! - The modules [`repo`], [`archive`], [`ex_integrity`], and [`ex_ostrya`]
//!   hold one key type for each key that the port reads in `[core]`,
//!   `[archive]`, `[ex-integrity]`, and `[ex-ostrya]`. The module [`remote`]
//!   holds the key types of `[remote "NAME"]`, the module [`server`] holds
//!   the key types of `[ex-ostrya server]`, and the module [`client`] holds
//!   the key types of `[ex-ostrya client "NAME"]`. The module [`trust`]
//!   holds the key types of `[ex-ostrya trust "NAME"]`, which are key types
//!   of [`remote`], and the module [`key`] holds the key types of
//!   `[ex-ostrya key "NAME"]`.
//! - [`Key`], [`Group`], [`SingleKey`], [`Overridable`], and [`Settable`]
//!   are the traits of the keys and the groups. [`UserGroup`] is the trait of
//!   a group of a library user.
//! - [`config_group!`](crate::config_group) defines a group and its keys.
//! - [`Value`] is the text form of a value, and [`ValueError`] is its parse
//!   error. The value types [`Tristate`], [`SizeSpec`], [`SizeUnit`],
//!   [`LockTimeout`], [`FreeSpacePercent`], [`CollectionIdValue`],
//!   [`RemotesConfigPath`], [`ConfigPath`], [`KeyringPaths`], and
//!   [`CollectionIdList`] hold a checked value. The value types
//!   [`ListenAddrs`], [`TrustedNets`], [`HeaderName`],
//!   [`PemPath`], [`PositiveInt`], [`UploadStreams`], and [`KeyGroupNames`]
//!   hold a checked value of [`server`]. The value types [`AuthItems`],
//!   [`AllowItems`], [`DenyItems`], and [`TrustRef`] hold a checked value of
//!   [`client`], and so does [`KeyGroupNames`]. The value type
//!   [`TrustGroupName`] holds a checked value of [`remote`], and
//!   [`SigningKeyType`] holds a checked value of [`key`]. The value types
//!   [`SignVerify`], [`DottedOid`], and [`X509Identities`] hold a checked
//!   value of [`remote`] and of [`trust`].
//! - [`decode_string`], [`encode_string`], [`decode_bool`], [`encode_bool`],
//!   [`decode_integer`], [`encode_integer`], [`decode_string_list`], and
//!   [`encode_string_list`] read and write the text of the key file.
//! - [`Section`] reads one section of a named group, and [`GroupRef`] names
//!   a section. [`Lookup`] gives a value and its source. A section of
//!   [`remote::Group`] comes from `config` or from a `.conf` file of the
//!   remotes directory. [`RemoteSource`] names the file that holds a
//!   section.
//! - [`RemoteSectionExt`] and [`ClientSectionExt`] give the reads of a
//!   remote section and of a client section that the key types do not give
//!   alone. A caller imports the trait to call its method.
//! - [`ConfigView`] reads the keys of a [`KeyFile`] through the key types,
//!   with no override and no remotes directory.
//! - [`ConfigEdit`] and [`SectionMut`] edit the document of `config` through
//!   the key types.
//!   [`UpdateGuard::edit_config`](crate::UpdateGuard::edit_config) edits the
//!   `config` of a repository.
//! - [`ConfigError`] is the error of the reads of [`ConfigView`] and
//!   [`Section`], and of the writes of [`ConfigEdit`] and [`SectionMut`].
//! - [`Repo::write_config`] writes an edited config back to the repository.
//! - [`valid_remote_name`] checks a remote name.
//!
//! # Typed keys
//!
//! Each key is a zero-sized type that implements [`Key`]. The type states
//! the group, the key name, the value type, and the built-in default. A read
//! parses the value of the file each time that it is called.
//!
//! ```
//! use ostrya::config::{Lookup, RepoConfig, repo};
//!
//! let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=false\n")?;
//!
//! // The value in effect, the value of the file, and the value with its
//! // source.
//! assert!(!cfg.get::<repo::Fsync>()?);
//! assert_eq!(cfg.file_value::<repo::Fsync>()?, Some(false));
//! assert_eq!(cfg.lookup::<repo::Fsync>()?, Some(Lookup::File(false)));
//!
//! // An absent key gives its default.
//! assert!(cfg.get::<repo::Locking>()?);
//! assert_eq!(cfg.file_value::<repo::Locking>()?, None);
//! assert_eq!(cfg.lookup::<repo::Locking>()?, Some(Lookup::Default(true)));
//! # Ok::<(), ostrya::Error>(())
//! ```
//!
//! # Overrides
//!
//! A repository handle can hold overrides of the keys of the single groups,
//! in memory. [`OpenOptions::force`](crate::OpenOptions::force) sets a value
//! that is in effect whether `config` sets the key or not.
//! [`OpenOptions::fallback`](crate::OpenOptions::fallback) and
//! [`CreateOptions::fallback`](crate::CreateOptions::fallback) set a value
//! that is in effect when `config` does not set the key. A key takes an
//! override if it implements [`Overridable`].
//!
//! [`RepoConfig::get`] and [`RepoConfig::lookup`] of the config of the handle
//! apply the overrides, and [`Lookup`] names the source of the value.
//! [`RepoConfig::file_value`], [`RepoConfig::keyfile`], a [`Section`], and
//! each write of `config` give the file alone, so no override goes to disk.
//! A `RepoConfig` with no handle, such as the result of
//! [`RepoConfig::parse`], has no override.
//!
//! [`CreateOptions::set`](crate::CreateOptions::set) writes a key that
//! implements [`Settable`] into the `config` of a new repository.
//!
//! ```no_run
//! # async fn run() -> ostrya::Result<()> {
//! use ostrya::config::{Lookup, repo};
//! use ostrya::{CreateOptions, OpenOptions, RepoMode};
//!
//! CreateOptions::new(RepoMode::Archive)
//!     .set::<repo::Locking>(false)
//!     .create("/srv/repo".as_ref())
//!     .await?;
//! let repo = OpenOptions::new()
//!     .force::<repo::Fsync>(false)
//!     .fallback::<repo::AutoUpdateSummary>(true)
//!     .open("/srv/repo".as_ref())
//!     .await?;
//! let cfg = repo.config();
//! assert_eq!(cfg.lookup::<repo::Fsync>()?, Some(Lookup::Forced(false)));
//! assert_eq!(cfg.lookup::<repo::Locking>()?, Some(Lookup::File(false)));
//! assert_eq!(cfg.lookup::<repo::AutoUpdateSummary>()?, Some(Lookup::Fallback(true)));
//! assert_eq!(cfg.file_value::<repo::Fsync>()?, None);
//! # Ok(()) }
//! ```
//!
//! # Groups of a library user
//!
//! A library user defines its own groups with
//! [`config_group!`](crate::config_group). The name of such a group starts
//! with `ex-`, and it is not `ex-integrity`, `ex-ostrya`, or a name that
//! starts with `ex-ostrya` and a space. [`UserGroup`] states each rule. A
//! name that breaks a rule fails the build.
//!
//! ```
//! use ostrya::config::RepoConfig;
//!
//! ostrya::config_group! {
//!     /// The keys of the `debles` tool.
//!     pub group debles = "ex-debles" {
//!         /// The number of parallel jobs.
//!         Parallel: u32 = "parallel", default 4, overridable;
//!     }
//! }
//!
//! let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n[ex-debles]\nparallel=8\n")?;
//! assert_eq!(cfg.get::<debles::Parallel>()?, 8);
//! # Ok::<(), ostrya::Error>(())
//! ```
//!
//! # Reads with no repository handle
//!
//! [`ConfigView`] reads a [`KeyFile`] through the key types. It has no
//! override and no remotes directory, so a lookup gives [`Lookup::File`] or
//! [`Lookup::Default`].
//!
//! ```
//! use ostrya::KeyFile;
//! use ostrya::config::{ConfigView, Lookup, repo};
//!
//! let text = "[core]\nrepo_version=1\nmode=bare\nfsync=false\n";
//! let kf = KeyFile::parse(text)?;
//! let view = ConfigView::new(&kf);
//! assert_eq!(view.lookup::<repo::Fsync>()?, Some(Lookup::File(false)));
//! # Ok::<(), ostrya::Error>(())
//! ```
//!
//! # Edits
//!
//! [`UpdateGuard::edit_config`](crate::UpdateGuard::edit_config) gives a
//! [`ConfigEdit`] of the `config` of a repository to a closure, and writes
//! the edited document. It writes the file also when the closure changes
//! nothing. The closure returns [`Result`], and `?` converts the
//! [`ConfigError`] of each write. [`ConfigEdit::new`] gives an edit of a
//! [`KeyFile`] in memory.
//!
//! ```no_run
//! # async fn run(handle: &ostrya::Repo) -> ostrya::Result<()> {
//! use ostrya::config::{Tristate, ex_integrity, repo};
//!
//! let guard = handle.begin_update().await?;
//! guard
//!     .edit_config(|edit| {
//!         edit.set::<repo::Fsync>(false)?;
//!         edit.set::<ex_integrity::Fsverity>(Tristate::No)?;
//!         Ok(())
//!     })
//!     .await?;
//! guard.finish().await?;
//! # Ok(()) }
//! ```
//!
//! # Errors
//!
//! The reads of [`RepoConfig`] and the methods of the extension traits
//! return [`Error`]. The reads of [`ConfigView`] and [`Section`], and the
//! writes of [`ConfigEdit`] and [`SectionMut`], return [`ConfigError`].
//! [`Error`] converts each variant of [`ConfigError`] to its variant with the
//! same name and the same text. Thus `?` in a function that returns
//! [`Result`] gives the same error as the same read through [`RepoConfig`].

use std::collections::HashMap;
use std::os::fd::{AsFd, BorrowedFd};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use ostrya_core::{KeyFile, RepoMode};
use rustix::io::Errno;

use crate::error::{Error, Result};
use crate::pattern::ReceiveSelector;
use crate::remotes_dir;
use crate::repo::{Repo, check_config_size};
use crate::repo_fs::{FsError, Publish, Reason, RootFile};

#[cfg(doctest)]
mod doctests;
mod section;
mod value;

#[doc(no_inline)]
pub use crate::config_group;
#[doc(no_inline)]
pub use ostrya_core::config::{
    CollectionIdList, CollectionIdValue, ConfigEdit, ConfigPath, ConfigView, DottedOid,
    FreeSpacePercent, GroupRef, KeyGroupNames, KeyringPaths, ListenAddrs, LockTimeout, PemPath,
    PositiveInt, RemoteSource, RemotesConfigPath, Section, SectionMut, SignVerify, SigningKeyType,
    SizeSpec, SizeUnit, Tristate, UploadStreams, X509Identities, ex_integrity, repo,
};
pub use ostrya_core::config::{
    ConfigError, Group, Key, Lookup, Overridable, Settable, SingleKey, UserGroup, Value,
    ValueError, decode_bool, decode_integer, decode_string, decode_string_list, encode_bool,
    encode_integer, encode_string, encode_string_list,
};
pub(crate) use ostrya_core::config::{
    Entry, OutputOf, Overrides, ValueOf, find_entry, lists, put_entry, put_settable,
    refuse_unknown_keys, section_name, str_eq,
};
pub use section::{ClientSectionExt, RemoteSectionExt};
pub(crate) use section::{
    SPKI_X509_KEYS, SectionCheck, SectionExt, TRUST_ENGINES, refuse_foreign_keys,
    refuse_removed_keys, verification_engine,
};
pub use value::{
    AllowItems, AuthItems, DenyItems, HeaderName, TrustGroupName, TrustRef, TrustedNets,
};

const CORE: &str = "core";
pub(crate) const EX_OSTRYA: &str = "ex-ostrya";
/// The key of the `[ex-ostrya]` group that names the remotes directory of the
/// repository.
pub(crate) const REMOTES_CONFIG_DIR: &str = "remotes-config-dir";
/// The name of the `config` file at the repository root.
const CONFIG_FILE: &str = "config";

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[archive]` group.
    pub group archive = "archive" {
        /// The zlib compression level of an `archive` repository.
        ///
        /// The default is `6`. The read takes each integer. The write path
        /// takes the level into the range that zlib accepts. A read gives
        /// [`Error::Core`] if the value is not an integer.
        ZlibLevel: i64 = "zlib-level", default 6, overridable;
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[ex-ostrya]` group. Each key of the group is an
    /// ostrya extension.
    pub group ex_ostrya = "ex-ostrya" {
        /// `true` if a transfer into this repository stores
        /// `ostrya.related`.
        ///
        /// The default is `true`. If the value is `false`, each transfer that
        /// writes into this repository drops `ostrya.related` from each
        /// detached metadata dict that it stores: [`Repo::pull`], also through
        /// a static delta, [`Repo::pull_with_session`],
        /// [`Repo::pull_collection`], and [`Repo::pull_local`]. Under the
        /// `receive` feature, the receive path also applies it: the push
        /// session and the one-way stream. A push to a bucket repository reads
        /// the key from the `config` of the bucket.
        ///
        /// A local write does not read the key: a commit write,
        /// [`Repo::write_commit_detached_metadata`], and
        /// [`Repo::add_supplement`] store `ostrya.related`. The key controls
        /// what a transfer stores. A pull, also a local pull and a pull
        /// through a static delta, and a push to a bucket replace the whole
        /// stored `.commitmeta` with the dict that the key leaves. So a stored
        /// `ostrya.related` stays only if that dict is empty: the transfer
        /// then writes nothing, and the destination keeps the copy that it
        /// holds. A receive merges the incoming dict into the stored dict, so
        /// a stored value stays.
        ///
        /// A read gives [`Error::Core`] if the value is not a boolean.
        KeepDetachedRelated: bool = "keep-detached-related", default true, overridable;
        /// The selector of the refs that a prune marks weak.
        ///
        /// The value is a `;` list of ref patterns, the entries of a
        /// [`ReceiveSelector`]. [`RepoConfig::gc_weak_references`] states the
        /// forms of an entry, and it also refuses a list with no positive
        /// entry. The key has no default. A read gives
        /// [`Error::InvalidFormat`] if an entry is not a valid ref pattern,
        /// and [`Error::Core`] if the value holds a malformed escape sequence.
        GcWeakReferences: Option<ReceiveSelector> = "gc-weak-references", overridable;
        /// The remotes directory of the repository.
        ///
        /// An absolute value names a directory, and a relative value names a
        /// directory relative to the repository. The key has no default. A
        /// read gives [`Error::InvalidFormat`] if the value is empty, holds a
        /// NUL byte, or is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        RemotesConfigDir: Option<RemotesConfigPath> = "remotes-config-dir";
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[ex-ostrya server]` group. Each key of the group is
    /// an ostrya extension.
    ///
    /// The group is closed: [`RepoConfig::check`] and
    /// [`ClientAccess::from_config`] refuse a key that the group does not
    /// list. No key has a default. A server takes its own default for an
    /// absent key, and [`ServerSettings`] states the use of each key.
    /// [`ClientAccess::from_config`] also checks that each name of
    /// [`SignSummary`](server::SignSummary) names a key group, and
    /// [`ClientAccess::check_server`] checks the rules between the keys.
    ///
    /// [`ClientAccess::from_config`]: crate::access::ClientAccess::from_config
    /// [`ClientAccess::check_server`]: crate::access::ClientAccess::check_server
    /// [`ServerSettings`]: crate::access::ServerSettings
    pub group server = "ex-ostrya server", closed {
        /// The addresses to listen on, each `ADDR:PORT`.
        ///
        /// A read gives [`Error::InvalidFormat`] if the list is empty or if an
        /// item is not an IP address and a port, and [`Error::Core`] if the
        /// value holds a malformed escape sequence.
        Listen: Option<ListenAddrs> = "listen";
        /// The PEM certificate chain of the server.
        ///
        /// A relative path is relative to the repository root. A read gives
        /// [`Error::InvalidFormat`] if the value is empty or is a relative
        /// path with a `..` component, and [`Error::Core`] if the value holds
        /// a malformed escape sequence.
        TlsCert: Option<PemPath> = "tls-cert";
        /// The PEM private key of [`TlsCert`].
        ///
        /// A read gives the errors of [`TlsCert`].
        TlsKey: Option<PemPath> = "tls-key";
        /// The PEM CA certificates that verify a client certificate.
        ///
        /// A read gives the errors of [`TlsCert`].
        TlsClientCa: Option<PemPath> = "tls-client-ca";
        /// The networks of the peers whose forwarding data the server reads.
        ///
        /// A read gives [`Error::InvalidFormat`] if the list is empty or if an
        /// item is not a network in the form of
        /// [`IpNet`](crate::access::IpNet), and [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        TrustedProxy: Option<TrustedNets> = "trusted-proxy";
        /// The request header from which the server reads the client address
        /// of a request from a trusted proxy.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is not
        /// `forwarded`, `x-forwarded-for`, or `x-real-ip`, and [`Error::Core`]
        /// if the value holds a malformed escape sequence.
        TrustedProxyHeader: Option<crate::access::ForwardedHeader> = "trusted-proxy-header";
        /// The name of the request header that carries the client
        /// certificate from a trusted proxy.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is not a header
        /// name, and [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        TrustedProxyClientCert: Option<HeaderName> = "trusted-proxy-client-cert";
        /// `true` if each connection starts with a PROXY protocol header.
        ///
        /// A read gives [`Error::Core`] if the value is not a boolean.
        ProxyProtocol: Option<bool> = "proxy-protocol";
        /// `true` if the server takes a credential on a connection with no
        /// TLS.
        ///
        /// A read gives [`Error::Core`] if the value is not a boolean.
        AllowCleartextCredentials: Option<bool> = "allow-cleartext-credentials";
        /// The idle time of a push session, in seconds.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is less than
        /// `1`, and [`Error::Core`] if the value is not an integer.
        SessionTimeout: Option<PositiveInt> = "session-timeout";
        /// The number of push sessions at the same time.
        ///
        /// A read gives the errors of [`SessionTimeout`].
        MaxSessions: Option<PositiveInt> = "max-sessions";
        /// The number of object streams of a push session, `1` to `31`.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is outside the
        /// range, and [`Error::Core`] if the value is not an integer.
        ParallelUploads: Option<UploadStreams> = "parallel-uploads";
        /// The time in seconds that a response waits for the client.
        ///
        /// A read gives the errors of [`SessionTimeout`].
        BodyTimeout: Option<PositiveInt> = "body-timeout";
        /// The key groups that sign a summary that a push or a command
        /// writes again.
        ///
        /// Each name names a section of [`key::Group`]. A read gives
        /// [`Error::InvalidFormat`] if the list is empty, and [`Error::Core`]
        /// if the value holds a malformed escape sequence. The read does not
        /// check that a key group of a name exists.
        SignSummary: Option<KeyGroupNames> = "sign-summary";
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[ex-ostrya client "NAME"]` group. Each key of the
    /// group is an ostrya extension.
    ///
    /// A client group states how a client of a server authenticates, the
    /// rights of the client on the refs, how the server verifies the commits
    /// of the client, and the keys that sign them.
    /// [`ClientGroup`](crate::access::ClientGroup) states the use of each key.
    ///
    /// The group is closed: [`RepoConfig::check`] and
    /// [`ClientAccess::from_config`] refuse a key that the group does not
    /// list. They also refuse the key `collection` with a message that names
    /// the form `@ID:PATTERN` of an allow item and a deny item.
    /// [`ClientAccess::from_config`] also applies the rules that need more
    /// than the value of one key: the references of
    /// [`Verify`](client::Verify) and [`Sign`](client::Sign) to other groups,
    /// a group with no auth item, an auth item that two groups carry, and the
    /// rules between the keys of a group.
    ///
    /// [`ClientAccess::from_config`]: crate::access::ClientAccess::from_config
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{ClientSectionExt, RepoConfig, client};
    ///
    /// let cfg = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\n\
    ///      [ex-ostrya client \"ci\"]\nauth=ssh:ci\nallow=rw:os/**\nverify=trust:ci\n\
    ///      [ex-ostrya trust \"ci\"]\n",
    /// )?;
    /// let ci = cfg.section::<client::Group>("ci").unwrap();
    /// assert_eq!(ci.get::<client::Auth>()?.items().len(), 1);
    /// let trust = ci.get::<client::Verify>()?.unwrap();
    /// assert_eq!(cfg.resolve(trust.group())?.name(), "ci");
    /// assert!(!ci.allow_unsigned()?);
    /// assert!(!ci.get::<client::Summary>()?);
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub group client = named "ex-ostrya client", closed {
        /// The authentication items of the group.
        ///
        /// The key is required. A read gives [`Error::InvalidFormat`] if an
        /// item is not an authentication item or if the key is absent, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        /// The value type accepts an empty list, and
        /// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
        /// refuses it.
        Auth: AuthItems = "auth", required;
        /// The allow items of the group.
        ///
        /// The default is the empty list. A read gives
        /// [`Error::InvalidFormat`] if an item is malformed, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        Allow: AllowItems = "allow", default AllowItems::default();
        /// The deny items of the group.
        ///
        /// The default is the empty list. A read gives the errors of
        /// [`Allow`].
        Deny: DenyItems = "deny", default DenyItems::default();
        /// `true` if the server reads the claims of the client certificate.
        ///
        /// The default is `false`. A read gives [`Error::Core`] if the value
        /// is not a boolean.
        TlsAcceptClaim: bool = "tls-accept-claim", default false;
        /// The trust group that verifies the new commits of a push.
        ///
        /// The key has no default. Without the key, the group verifies no
        /// signature. A read gives [`Error::InvalidFormat`] if the value is
        /// not `trust:NAME`, and [`Error::Core`] if the value holds a
        /// malformed escape sequence. The read does not check that the
        /// trust group exists.
        Verify: Option<TrustRef> = "verify";
        /// `true` if the server accepts a new commit with no signature.
        ///
        /// The key has no default value of its own.
        /// [`ClientSectionExt::allow_unsigned`] gives the value in effect:
        /// `true` without [`Verify`], and `false` with it. A read gives
        /// [`Error::Core`] if the value is not a boolean.
        AllowUnsigned: Option<bool> = "allow-unsigned";
        /// The key groups that sign the new commits of a push and the server
        /// commits of the group.
        ///
        /// Each name names a section of [`key::Group`]. The key has no
        /// default. A read gives [`Error::InvalidFormat`] if the list is
        /// empty, and [`Error::Core`] if the value holds a malformed escape
        /// sequence. The read does not check that a key group of a name
        /// exists.
        Sign: Option<KeyGroupNames> = "sign";
        /// `true` if a session on a `bare` repository accepts the setuid and
        /// setgid bits and the privileged extended attributes.
        ///
        /// The default is `false`. A read gives [`Error::Core`] if the value
        /// is not a boolean.
        AllowPrivileged: bool = "allow-privileged", default false;
        /// `true` if a push of the group skips the check of
        /// `ostree.ref-binding`.
        ///
        /// The default is `false`. A read gives [`Error::Core`] if the value
        /// is not a boolean.
        DisableVerifyBindings: bool = "disable-verify-bindings", default false;
        /// `true` if each authentication item of the group has a summary.
        ///
        /// The default is `false`. A read gives [`Error::Core`] if the value
        /// is not a boolean.
        Summary: bool = "summary", default false;
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[ex-ostrya trust "NAME"]` group. Each key of the
    /// group is a key of [`remote`], and the group is an ostrya extension.
    ///
    /// A trust group holds the trusted keys that verify the commits of a
    /// client group, of a pull from a remote with the key
    /// [`remote::Trust`], and of a caller of
    /// [`TrustedKeys::from_trust_group`]. The value of [`client::Verify`]
    /// is a [`GroupRef`] of this group, and [`RepoConfig::resolve`] gives
    /// its section.
    ///
    /// The key types of the module are the key types of [`remote`]. Each key
    /// type has its own default in each group: [`GpgVerify`](trust::GpgVerify)
    /// is `false` in a trust group and `true` in a remote group.
    ///
    /// The group takes the keys of the X.509 trust of the spki engine, such
    /// as [`VerificationSpkiCaFile`](trust::VerificationSpkiCaFile), with the
    /// rules of a remote group. A trust group reads no anchor, no CRL, and no
    /// revoked key of the system key store. So the X.509 trust of a group
    /// needs [`VerificationSpkiCaFile`](trust::VerificationSpkiCaFile), and
    /// its anchors are the certificates of that file alone.
    ///
    /// The key type [`SignVerify`](trust::SignVerify) has the name of its
    /// value type [`config::SignVerify`](SignVerify). A glob import of
    /// `ostrya::config` and of this module makes the name ambiguous, so name
    /// one of them by its path.
    ///
    /// The group is closed: [`RepoConfig::check`] and the readers of the
    /// group refuse a key that the group does not list. For the keys
    /// `gpg-verify-summary`, `sign-verify-summary`, and
    /// `verification-ENGINE-key` and `verification-ENGINE-file` of an engine
    /// other than `ed25519` and `spki`, they give a text that states the
    /// reason. The readers also apply the rules that need more than the value
    /// of one key, as [`TrustedKeys::from_trust_group`] states.
    ///
    /// [`TrustedKeys::from_trust_group`]: crate::verify::TrustedKeys::from_trust_group
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{RepoConfig, trust};
    ///
    /// let cfg = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\n\
    ///      [ex-ostrya trust \"ci\"]\nsign-verify=ed25519\n\
    ///      verification-ed25519-file=keys/ci.ed25519\n",
    /// )?;
    /// let ci = cfg.section::<trust::Group>("ci").unwrap();
    /// assert!(!ci.get::<trust::GpgVerify>()?);
    /// assert_eq!(
    ///     ci.get::<trust::VerificationEd25519File>()?.unwrap().as_str(),
    ///     "keys/ci.ed25519"
    /// );
    /// assert!(ci.get::<trust::GpgKeyPath>()?.entries().is_empty());
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub group trust = named "ex-ostrya trust", closed {
        use remote::GpgVerify: bool = "gpg-verify", default false;
        use remote::GpgKeyPath: KeyringPaths = "gpgkeypath", default KeyringPaths::default();
        use remote::SignVerify: super::SignVerify = "sign-verify", default super::SignVerify::Off;
        use remote::VerificationEd25519Key: Option<String> = "verification-ed25519-key";
        use remote::VerificationEd25519File: Option<ConfigPath> = "verification-ed25519-file";
        use remote::VerificationSpkiKey: Option<String> = "verification-spki-key";
        use remote::VerificationSpkiFile: Option<ConfigPath> = "verification-spki-file";
        use remote::VerificationSpkiCaFile: Option<ConfigPath> = "verification-spki-ca-file";
        use remote::VerificationSpkiIntermediatesFile: Option<ConfigPath> =
            "verification-spki-intermediates-file";
        use remote::VerificationSpkiEku: Option<DottedOid> = "verification-spki-eku";
        use remote::VerificationSpkiIdentity: Option<X509Identities> = "verification-spki-identity";
        use remote::VerificationSpkiCrlFile: Option<ConfigPath> = "verification-spki-crl-file";
        use remote::VerificationSpkiRevocation: crate::sign::X509Revocation =
            "verification-spki-revocation", default crate::sign::X509Revocation::BestEffort;
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[ex-ostrya key "NAME"]` group. Each key of the group
    /// is an ostrya extension.
    ///
    /// A key group holds one signing key: an `ed25519` key, the `spki` keys
    /// of a file, or a GnuPG key. [`SigningKey::from_key_group`] builds its
    /// signing keys. [`server::SignSummary`] and [`client::Sign`] name key
    /// groups.
    ///
    /// The group is closed: [`RepoConfig::check`] and the readers of the
    /// group refuse a key that the group does not list. The readers also
    /// apply the rules that need more than the value of one key: the keys
    /// that a type needs and the keys that it does not take, as
    /// [`SigningKey::from_key_group`] states.
    ///
    /// [`SigningKey::from_key_group`]: crate::sign::SigningKey::from_key_group
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{RepoConfig, SigningKeyType, key};
    ///
    /// let cfg = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=archive-z2\n\
    ///      [ex-ostrya key \"release\"]\ntype=ed25519\nsecret-key-file=keys/release\n",
    /// )?;
    /// let release = cfg.section::<key::Group>("release").unwrap();
    /// assert_eq!(release.get::<key::Type>()?, SigningKeyType::Ed25519);
    /// assert_eq!(
    ///     release.get::<key::SecretKeyFile>()?.unwrap().as_str(),
    ///     "keys/release"
    /// );
    /// assert_eq!(release.get::<key::GpgKey>()?, None);
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub group key = named "ex-ostrya key", closed {
        /// The type of the key: `ed25519`, `spki`, or `gpg`.
        ///
        /// The key is required. A read gives [`Error::InvalidFormat`] if the
        /// value is not a type or if the key is absent, and [`Error::Core`]
        /// if the value holds a malformed escape sequence.
        Type: SigningKeyType = "type", required;
        /// The file of the secret key of an `ed25519` or `spki` key.
        ///
        /// A relative path is relative to the repository root. The key has
        /// no default. A read gives [`Error::InvalidFormat`] if the value is
        /// a relative path with a `..` component, and [`Error::Core`] if the
        /// value holds a malformed escape sequence. The read accepts an empty
        /// value, and [`SigningKey::from_key_group`] refuses it.
        ///
        /// [`SigningKey::from_key_group`]: crate::sign::SigningKey::from_key_group
        SecretKeyFile: Option<ConfigPath> = "secret-key-file";
        /// The file of the X.509 certificate chain of an `spki` key.
        ///
        /// The file holds PEM `CERTIFICATE` blocks of one chain, the leaf
        /// certificate first. The key of the leaf certificate is the key of
        /// one `PRIVATE KEY` block of `secret-key-file`. Each signature of
        /// that key carries the chain in `ostrya.x509.chains`. A relative
        /// path is relative to the repository root. The key has no default.
        /// A read gives [`Error::InvalidFormat`] if the value is a relative
        /// path with a `..` component, and [`Error::Core`] if the value holds
        /// a malformed escape sequence. The read accepts an empty value, and
        /// [`SigningKey::from_key_group`] refuses it.
        ///
        /// [`SigningKey::from_key_group`]: crate::sign::SigningKey::from_key_group
        CertificateChainFile: Option<ConfigPath> = "certificate-chain-file";
        /// The file of the X.509 CRLs of an `spki` key.
        ///
        /// The file holds PEM `X509 CRL` blocks. Each signature of the keys
        /// of the group carries the CRLs in `ostrya.x509.crls`. A relative
        /// path is relative to the repository root. The key has no default.
        /// A read gives [`Error::InvalidFormat`] if the value is a relative
        /// path with a `..` component, and [`Error::Core`] if the value holds
        /// a malformed escape sequence. The read accepts an empty value, and
        /// [`SigningKey::from_key_group`] refuses it.
        ///
        /// [`SigningKey::from_key_group`]: crate::sign::SigningKey::from_key_group
        CrlFile: Option<ConfigPath> = "crl-file";
        /// The GnuPG selector of the secret key of a `gpg` key.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence. The read accepts an empty
        /// value, and [`SigningKey::from_key_group`] refuses it.
        ///
        /// [`SigningKey::from_key_group`]: crate::sign::SigningKey::from_key_group
        GpgKey: Option<String> = "gpg-key";
        /// The GnuPG home directory of a `gpg` key.
        ///
        /// The value goes to GnuPG unchanged, so a relative value is
        /// relative to the current directory of the process. The key has no
        /// default. A read gives [`Error::Core`] if the value holds a
        /// malformed escape sequence.
        GpgHomedir: Option<String> = "gpg-homedir";
    }
}

ostrya_core::__config_group! {
    @builtin [pub(crate)]
    /// The keys of the `[remote "NAME"]` group.
    ///
    /// A remote section comes from `config` or from a `.conf` file of the
    /// remotes directory of the handle. [`RepoConfig::section`] and
    /// [`RepoConfig::sections`] give the sections of both sources, and
    /// [`Section::source`] names the file of a section. The group is open: a
    /// key that the group does not list is valid, and the port does not read
    /// it.
    ///
    /// A trust group, `[ex-ostrya trust "NAME"]`, takes the key names of a
    /// remote section, and the module [`trust`] re-exports the key types
    /// that it takes. The key types [`GpgVerify`](remote::GpgVerify),
    /// [`GpgKeyPath`](remote::GpgKeyPath),
    /// [`SignVerify`](remote::SignVerify),
    /// [`VerificationEd25519Key`](remote::VerificationEd25519Key),
    /// [`VerificationEd25519File`](remote::VerificationEd25519File),
    /// [`VerificationSpkiKey`](remote::VerificationSpkiKey),
    /// [`VerificationSpkiFile`](remote::VerificationSpkiFile),
    /// [`VerificationSpkiCaFile`](remote::VerificationSpkiCaFile),
    /// [`VerificationSpkiIntermediatesFile`](remote::VerificationSpkiIntermediatesFile),
    /// [`VerificationSpkiEku`](remote::VerificationSpkiEku),
    /// [`VerificationSpkiIdentity`](remote::VerificationSpkiIdentity),
    /// [`VerificationSpkiCrlFile`](remote::VerificationSpkiCrlFile), and
    /// [`VerificationSpkiRevocation`](remote::VerificationSpkiRevocation) are
    /// the keys that the two groups share.
    ///
    /// The key type [`SignVerify`](remote::SignVerify) has the name of its
    /// value type [`config::SignVerify`](SignVerify). A glob import of
    /// `ostrya::config` and of this module makes the name ambiguous, so name
    /// one of them by its path.
    ///
    /// # Paths
    ///
    /// The keys `gpgkeypath`, `verification-ENGINE-file`,
    /// `verification-spki-ca-file`, `verification-spki-intermediates-file`,
    /// `tls-ca-path`, `tls-client-cert-path`, `tls-client-key-path`, and
    /// `push-token-file` name files. A path is absolute, or relative to a base:
    ///
    /// - A relative path in `config` is relative to the repository root. This
    ///   applies to a remote and to a trust group.
    /// - A relative path in a `.conf` file of the remotes directory is relative
    ///   to that directory.
    ///
    /// A read of each of these keys refuses a relative path with a `..`
    /// component. An absolute path with a `..` component is not refused. The
    /// readers do not expand `~`. A read of the file follows a symlink at
    /// each component of the path, also to a path outside the repository. It
    /// opens the file with `O_NONBLOCK`, and then refuses each file that is
    /// not a regular file, so a FIFO, a device, or a socket at the path fails
    /// the read. A directory entry of `gpgkeypath` is the exception, as
    /// [`GpgKeyPath`](remote::GpgKeyPath) states.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{RemoteSource, RepoConfig, remote};
    ///
    /// let cfg = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=bare\n\
    ///      [remote \"origin\"]\nurl=https://example.com/repo\ngpg-verify=false\n",
    /// )?;
    /// let origin = cfg.section::<remote::Group>("origin").unwrap();
    /// assert_eq!(origin.name(), "origin");
    /// assert_eq!(origin.source(), RemoteSource::Config);
    /// assert_eq!(
    ///     origin.get::<remote::Url>()?.as_deref(),
    ///     Some("https://example.com/repo")
    /// );
    /// assert!(!origin.get::<remote::GpgVerify>()?);
    /// assert!(!origin.get::<remote::TlsPermissive>()?);
    ///
    /// let names: Vec<&str> = cfg.sections::<remote::Group>().map(|s| s.name()).collect();
    /// assert_eq!(names, ["origin"]);
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub group remote = named "remote" {
        /// The base URL of the objects and the refs.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        Url: Option<String> = "url";
        /// The URL of the content objects.
        ///
        /// A remote sets this key if the URL differs from `url`. The key has
        /// no default. A read gives [`Error::Core`] if the value holds a
        /// malformed escape sequence.
        ContentUrl: Option<String> = "contenturl";
        /// The URL of a metalink for this remote.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        Metalink: Option<String> = "metalink";
        /// The refs of a pull that names no ref.
        ///
        /// A pull with no ref also takes the refs of the summary that
        /// [`PullBranches`] selects. [`PullBranches`] states the rules of the
        /// two keys together. The key has no default. A read gives
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        Branches: Option<Vec<String>> = "branches";
        /// The collection id of this remote.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        CollectionId: Option<String> = "collection-id";
        /// The collections that the remote serves from `refs/mirrors/ID/`, in
        /// the order of the key.
        ///
        /// The summary of such a remote lists the refs of each of these
        /// collections in `ostree.summary.collection-map`. The key does not
        /// need `collection-id`. An id that occurs again counts one time. The
        /// key is an ostrya extension.
        ///
        /// The key has no default.
        /// [`RemoteSectionExt::mirrored_collection_ids`] gives an empty list for
        /// an absent key, and also refuses an id that is the [`CollectionId`]
        /// of the section. A read gives [`Error::InvalidFormat`] if the list
        /// holds no id or holds an id that fails the collection-id rule, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        MirroredCollectionIds: Option<CollectionIdList> = "mirrored-collection-ids";
        /// `true` if a pull verifies the GPG signatures of commits.
        ///
        /// The default is `true` in a remote group and `false` in a trust
        /// group. A read gives [`Error::Core`] if the value is not a boolean.
        GpgVerify: bool = "gpg-verify", default true;
        /// `true` if a pull verifies the GPG signature of the summary.
        ///
        /// The default is `false`. A read gives [`Error::Core`] if the value
        /// is not a boolean.
        GpgVerifySummary: bool = "gpg-verify-summary", default false;
        /// More trusted GPG keyrings.
        ///
        /// The remote also trusts the keyring `REMOTE.trustedkeys.gpg` of the
        /// repository, or of the remotes directory when the repository holds
        /// no such file, and the system trusted set. The read takes the raw
        /// value of the key and does not decode the escape sequences of the
        /// key file, so `\s` is two characters of a path. A `;` separates the
        /// entries. The read removes one empty entry at the end of the list
        /// and keeps each other empty entry, so an empty value gives one empty
        /// entry. The default is the empty list.
        ///
        /// Each entry is a keyring file or a directory of keyring files, by
        /// the rules of the [paths](self#paths) of a remote. The GPG verifier
        /// refuses an empty entry, because it cannot read it. It opens an
        /// entry as a file first, and lists the entry if it is a directory.
        /// In a directory, it reads each member that the listing gives as a
        /// regular file. It skips a symlink, a subdirectory, a FIFO, a
        /// socket, and a device, and opens no such member. It also skips a
        /// member that is absent or is not a regular file at its open. It
        /// skips a file that does not hold the bytes `-----BEGIN PGP` and
        /// that is a GnuPG keybox or is not a whole OpenPGP packet stream. It
        /// refuses each other file that it cannot read whole as a keyring.
        ///
        /// A read gives [`Error::InvalidFormat`] if an entry is a relative
        /// path with a `..` component.
        GpgKeyPath: KeyringPaths = "gpgkeypath", default KeyringPaths::default();
        /// The sign-api engines that verify the commits of this remote.
        ///
        /// The value type is [`config::SignVerify`](super::SignVerify), and
        /// the default is `Off`. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        SignVerify: super::SignVerify = "sign-verify", default super::SignVerify::Off;
        /// The sign-api engines that verify the summary of this remote.
        ///
        /// The value type is [`config::SignVerify`](super::SignVerify), and
        /// the default is `Off`. A pull reads this key alone for the summary.
        /// `sign-verify=false` does not turn off a summary verification that
        /// this key asks for. A read gives [`Error::Core`] if the value holds
        /// a malformed escape sequence.
        SignVerifySummary: super::SignVerify = "sign-verify-summary",
            default super::SignVerify::Off;
        /// The inline trusted key of the `ed25519` engine.
        ///
        /// The value holds exactly one base64 key. The key has no default. A
        /// read gives [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        VerificationEd25519Key: Option<String> = "verification-ed25519-key";
        /// The path of a file of trusted keys of the `ed25519` engine.
        ///
        /// The file holds one base64 key on each line. A pull and the receive
        /// side read the path by the rules of the [paths](self#paths) of a
        /// remote. The key has no default. A read gives
        /// [`Error::InvalidFormat`] if the value is a relative path with a
        /// `..` component, and [`Error::Core`] if the value holds a malformed
        /// escape sequence.
        VerificationEd25519File: Option<ConfigPath> = "verification-ed25519-file";
        /// The inline trusted key of the `spki` engine.
        ///
        /// The value holds exactly one key. The key has no default. A read
        /// gives [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        VerificationSpkiKey: Option<String> = "verification-spki-key";
        /// The path of a file of trusted keys of the `spki` engine.
        ///
        /// The file holds PEM `PUBLIC KEY` blocks. A pull and the receive
        /// side read the path by the rules of the [paths](self#paths) of a
        /// remote. The key has no default. A read gives
        /// [`Error::InvalidFormat`] if the value is a relative path with a
        /// `..` component, and [`Error::Core`] if the value holds a malformed
        /// escape sequence.
        VerificationSpkiFile: Option<ConfigPath> = "verification-spki-file";
        /// The path of a file of X.509 trust anchors of the `spki` engine.
        ///
        /// The file holds PEM `CERTIFICATE` blocks. The key of each
        /// certificate is of a key type of the engine. A pull and the receive
        /// side read the path by the rules of the [paths](self#paths) of a
        /// remote. A signature whose X.509 certificate chain reaches an
        /// anchor is from a trusted key, as `SpkiVerifier::with_x509` states.
        /// The key needs [`VerificationSpkiIdentity`]. The key is an ostrya
        /// extension.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        VerificationSpkiCaFile: Option<ConfigPath> = "verification-spki-ca-file";
        /// The path of a file of X.509 intermediate certificates of the
        /// `spki` engine.
        ///
        /// The file holds PEM `CERTIFICATE` blocks. The path check builds a
        /// path through them and through the intermediate certificates of
        /// each chain. The key needs an anchor source:
        /// [`VerificationSpkiCaFile`] or [`VerificationSpkiIdentity`]. The
        /// key is an ostrya extension.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        VerificationSpkiIntermediatesFile: Option<ConfigPath> =
            "verification-spki-intermediates-file";
        /// The EKU that the leaf certificate of an X.509 chain holds, an OID
        /// in dotted form.
        ///
        /// The default is codeSigning, `1.3.6.1.5.5.7.3.3`. The key needs an
        /// anchor source: [`VerificationSpkiCaFile`] or
        /// [`VerificationSpkiIdentity`]. The key is an ostrya extension.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is not an OID
        /// in dotted form, and [`Error::Core`] if the value holds a malformed
        /// escape sequence.
        VerificationSpkiEku: Option<DottedOid> = "verification-spki-eku";
        /// The identities that the leaf certificate of an X.509 chain
        /// matches, as [`X509Identities`] states.
        ///
        /// The key is necessary with [`VerificationSpkiCaFile`]. With the
        /// key, a pull also trusts the anchors of the system key store,
        /// `trusted.x509` and the files of `trusted.x509.d/` in
        /// `/etc/ostree` and `/usr/share/ostree`. A trust group reads no
        /// anchor of the system key store, so in a trust group the key also
        /// needs [`VerificationSpkiCaFile`]. The key is an ostrya extension.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is not a list of identities, and [`Error::Core`] if the
        /// value holds a malformed escape sequence.
        VerificationSpkiIdentity: Option<X509Identities> = "verification-spki-identity";
        /// The path of a file of X.509 CRLs of the `spki` engine.
        ///
        /// The file holds PEM `X509 CRL` blocks. A pull and the receive side
        /// read the path by the rules of the [paths](self#paths) of a remote.
        /// Each CRL is one that the path check uses, as
        /// `X509Trust::with_crls` states, else the file is refused. The CRLs
        /// of the file come first in the sources of the CRLs of the path
        /// check. The key needs an anchor source: [`VerificationSpkiCaFile`]
        /// or [`VerificationSpkiIdentity`]. The key is an ostrya extension.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        VerificationSpkiCrlFile: Option<ConfigPath> = "verification-spki-crl-file";
        /// The use of the X.509 CRLs at the admission of an object:
        /// `best-effort` or `required`, as
        /// [`X509Revocation`](crate::sign::X509Revocation) states.
        ///
        /// The default is `best-effort`. A media import, an offline delta
        /// apply, and each verify of an object in a repository read the CRLs
        /// as `best-effort` with each value. A pull, a push to the receive
        /// endpoint, and a one-way receive follow the value. The key needs an
        /// anchor source: [`VerificationSpkiCaFile`] or
        /// [`VerificationSpkiIdentity`]. The key is an ostrya extension.
        ///
        /// A read gives [`Error::InvalidFormat`] if the value is not
        /// `best-effort` or `required`, and [`Error::Core`] if the value holds
        /// a malformed escape sequence.
        VerificationSpkiRevocation: crate::sign::X509Revocation =
            "verification-spki-revocation", default crate::sign::X509Revocation::BestEffort;
        /// The name of the trust group `[ex-ostrya trust "NAME"]` whose keys
        /// check the commits of each pull from this remote.
        ///
        /// With the key, the group sets the commit checks of the pull, and
        /// the summary keys of this section set the summary check.
        /// [`PullTrust::from_remote`](crate::verify::PullTrust::from_remote)
        /// states the rules and the refusals.
        /// [`PullOptions::trust_group`](crate::PullOptions::trust_group) wins
        /// over the key, and a pull with that field does not read the key.
        /// The key is an ostrya extension. The `ostree` command keeps it and
        /// ignores it.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is empty or holds a `"` or a control character, and
        /// [`Error::Core`] if the value holds a malformed escape sequence. The
        /// read does not check that the trust group exists.
        Trust: Option<TrustGroupName> = "trust";
        /// A PEM file of trust anchors for TLS.
        ///
        /// The anchors replace the trust store of the host. A pull and a push
        /// read the path by the rules of the [paths](self#paths) of a remote.
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        TlsCaPath: Option<ConfigPath> = "tls-ca-path";
        /// The PEM client certificate chain.
        ///
        /// The client presents this chain to the remote. A pull and a push
        /// read the path by the rules of the [paths](self#paths) of a remote.
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// the value is a relative path with a `..` component, and
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        TlsClientCertPath: Option<ConfigPath> = "tls-client-cert-path";
        /// The PEM private key of the client.
        ///
        /// The key belongs to the chain of [`TlsClientCertPath`]. A pull and a
        /// push read the path by the rules of the [paths](self#paths) of a
        /// remote. The key has no default. A read gives
        /// [`Error::InvalidFormat`] if the value is a relative path with a
        /// `..` component, and [`Error::Core`] if the value holds a malformed
        /// escape sequence.
        TlsClientKeyPath: Option<ConfigPath> = "tls-client-key-path";
        /// `true` if the TLS chain verification is off.
        ///
        /// The default is `false`. A pull from a remote that sets the key
        /// accepts the certificate chain as presented and keeps the host name
        /// check.
        ///
        /// `ostrya::endpoint::resolve_push` refuses an `https://` address of
        /// a remote that sets the key. A push to an
        /// `http://` address uses no TLS and ignores the key. The transport of
        /// a push accepts each trust setting that its caller gives, so this
        /// refusal is the policy of the remote key alone.
        ///
        /// A read gives [`Error::Core`] if the value is not a boolean.
        TlsPermissive: bool = "tls-permissive", default false;
        /// The `http://`, `socks5://`, or `socks5h://` proxy URL of an HTTP
        /// pull and of an HTTP push.
        ///
        /// An HTTP pull from this remote and an HTTP push to it connect
        /// through this proxy. If the value is empty, the key counts as
        /// absent, and the pull or the push reads the proxy environment
        /// variables. A pull or a push that uses the key connects through the
        /// proxy for every origin and ignores `no_proxy`.
        ///
        /// The read keeps white space at the end of the value. An HTTP pull
        /// and an HTTP push refuse a non-empty value with white space at its
        /// start or end. A push and a pull over ssh do not read the key.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        Proxy: Option<String> = "proxy";
        /// The push address of this remote.
        ///
        /// If the key is absent and `url` is an `http://` or an `https://`
        /// URL, a push uses `url`. The key has no default. A read gives
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        PushUrl: Option<String> = "push-url";
        /// The pull address of this remote.
        ///
        /// The value is an ssh address, an `http://` or `https://` URL, or the
        /// `s3://BUCKET[/PREFIX]` address of a bucket repository. If the key
        /// is set, a pull from this remote uses it and ignores `url`. The key
        /// is an ostrya extension, and the `ostree` command does not read it.
        ///
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        PullUrl: Option<String> = "pull-url";
        /// The selector of the refs that a push with no refspec sends.
        ///
        /// The key is an ostrya extension. The value is a `;` list of ref
        /// patterns, the entries of a [`ReceiveSelector`]. An entry has one
        /// of these forms, with `*` and `**` in the name part:
        ///
        /// - `NAME` -- the local refs that `NAME` matches.
        /// - `REMOTE:NAME` -- the refs of the remote `REMOTE` that `NAME`
        ///   matches.
        /// - `@ID:NAME` -- the refs of the collection `ID` that `NAME`
        ///   matches.
        ///
        /// An entry that starts with `!` is an exclusion. The selector
        /// selects a ref when a positive entry matches it, and no exclusion
        /// matches it. If the list has no positive entry, each ref that no
        /// exclusion matches is selected. Thus an empty value selects each
        /// ref. The order of the entries has no effect. Pass the `[core]
        /// collection-id` of the repository as `own` to
        /// [`ReceiveSelector::matches`]: `@OWN:NAME` then matches the local
        /// ref `NAME`.
        ///
        /// `Repo::push` reads no config key for its refs. The `ostrya push`
        /// command reads this key when it gets no refspec.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// an entry is not a valid ref pattern, and [`Error::Core`] if the
        /// value holds a malformed escape sequence.
        PushBranches: Option<ReceiveSelector> = "push-branches";
        /// The selector of the summary refs that a pull with no ref takes.
        ///
        /// The key is an ostrya extension. The value is a `;` list of ref
        /// patterns, the entries of a [`ReceiveSelector`]. An entry has one
        /// of these forms, with `*` and `**` in the name part:
        ///
        /// - `NAME` -- the local refs that `NAME` matches.
        /// - `REMOTE:NAME` -- the refs of the remote `REMOTE` that `NAME`
        ///   matches.
        /// - `@ID:NAME` -- the refs of the collection `ID` that `NAME`
        ///   matches.
        ///
        /// An entry that starts with `!` is an exclusion. The selector
        /// selects a ref when a positive entry matches it, and no exclusion
        /// matches it. If the list has no positive entry, each ref that no
        /// exclusion matches is selected. Thus an empty value selects each
        /// ref. The order of the entries has no effect.
        ///
        /// The selector matches the refs of the summary of the remote. A ref
        /// of the ref list of the summary is the ref `NAME`, and a ref of the
        /// entry of `ID` in `ostree.summary.collection-map` is the ref
        /// `@ID:NAME`. The own id of the match is the
        /// `ostree.summary.collection-id` of the summary, so `@ID:NAME` of
        /// that id matches the ref `NAME` of the ref list. A pattern
        /// `REMOTE:NAME` matches no ref of the summary.
        ///
        /// [`Repo::pull`](crate::Repo::pull) reads this key when
        /// [`refs`](crate::PullOptions::refs) is empty and
        /// [`MIRROR`](crate::PullFlags::MIRROR) is not set. The pull takes
        /// each ref of [`Branches`] and each ref of the summary that this key
        /// selects. The refs of `branches` come first, in the order of the
        /// key, and then the selected refs, in the order of the summary. A
        /// name `NAME` of `branches` and a selected ref `NAME` of the ref list
        /// of the summary are one target, and the pull takes it one time.
        ///
        /// If the remote has no summary, the pull fails, also when `branches`
        /// holds refs. If no ref of the summary matches, the pull takes the
        /// refs of `branches`, and it fails if `branches` holds no ref.
        ///
        /// The key has no default. A read gives [`Error::InvalidFormat`] if
        /// an entry is not a valid ref pattern, and [`Error::Core`] if the
        /// value holds a malformed escape sequence.
        PullBranches: Option<ReceiveSelector> = "pull-branches";
        /// The ssh command line of this remote.
        ///
        /// A push to this remote and a pull over ssh from it run this command.
        /// The ssh transport splits it at ASCII white space, with no quoting
        /// rule. The key has no default. A read gives [`Error::Core`] if the
        /// value holds a malformed escape sequence.
        SshCommand: Option<String> = "ssh-command";
        /// The remote command of a push.
        ///
        /// The remote side of a push to this remote runs this command. The
        /// remote shell parses it. The key has no default. A read gives
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        ReceiveCommand: Option<String> = "receive-command";
        /// The remote command of a pull over ssh.
        ///
        /// The remote side of a pull over ssh from this remote runs this
        /// command. The remote shell parses it. The key has no default. A read
        /// gives [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        SendCommand: Option<String> = "send-command";
        /// The token file of an HTTP push.
        ///
        /// The first line of the file is the token of an HTTP push to this
        /// remote. The push reads the path by the rules of the
        /// [paths](self#paths) of a remote. The key has no default. A read
        /// gives [`Error::InvalidFormat`] if the value is a relative path
        /// with a `..` component, and [`Error::Core`] if the value holds a
        /// malformed escape sequence.
        PushTokenFile: Option<ConfigPath> = "push-token-file";
        /// The Basic credential name of an HTTP push.
        ///
        /// The token of [`PushTokenFile`] is the password. If the key is
        /// absent, the push sends the token as a bearer token. The key has no
        /// default. A read gives [`Error::Core`] if the value holds a
        /// malformed escape sequence.
        PushUser: Option<String> = "push-user";
        /// The region of the signature of each request to the `s3://` address
        /// of this remote.
        ///
        /// The key is an ostrya extension.
        /// [`resolve_pull`](crate::endpoint::resolve_pull) states the order of
        /// the sources of the region. The key has no default. A read gives
        /// [`Error::Core`] if the value holds a malformed escape sequence.
        S3Region: Option<String> = "s3-region";
        /// The `http://` or `https://` URL of the S3 server of the `s3://`
        /// address of this remote.
        ///
        /// The key is an ostrya extension. The key has no default. A read
        /// gives [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        S3Endpoint: Option<String> = "s3-endpoint";
        /// The addressing style of the bucket of the `s3://` address of this
        /// remote, `path` or `virtual`.
        ///
        /// The key is an ostrya extension. The read gives the value as
        /// written. A pull refuses each other value. The key has no default.
        /// A read gives [`Error::Core`] if the value holds a malformed escape
        /// sequence.
        S3Addressing: Option<String> = "s3-addressing";
        /// The profile of the shared AWS files for the `s3://` address of this
        /// remote.
        ///
        /// The key is an ostrya extension. A profile that this key names turns
        /// off the key pair, the region, and the endpoint of the environment.
        /// The key has no default. A read gives [`Error::Core`] if the value
        /// holds a malformed escape sequence.
        S3Profile: Option<String> = "s3-profile";
    }
}

/// A parsed repository configuration.
///
/// The type holds the [`KeyFile`] parsed from `<repo>/config`. It reads the
/// values with the conventions of the `ostree` command.
///
/// The type also holds the `[remote "<name>"]` groups of the `.conf` files of
/// the remotes directory of the handle, [`Repo::remotes_dir`]. The open reads
/// these files with `config`. [`section`](RepoConfig::section) and
/// [`sections`](RepoConfig::sections) of [`remote::Group`] give the remotes of
/// both sources. [`keyfile`](RepoConfig::keyfile) gives `config` alone.
///
/// [`get`](RepoConfig::get), [`file_value`](RepoConfig::file_value), and
/// [`lookup`](RepoConfig::lookup) read one key of a single group through its
/// key type.
///
/// # Groups
///
/// - `[core]`: the keys of [`repo`]. [`mode`](RepoConfig::mode),
///   [`repo_version`](RepoConfig::repo_version), and
///   [`collection_id`](RepoConfig::collection_id) give the values that the
///   open checks. [`min_free_space`](RepoConfig::min_free_space) reads
///   `min-free-space-size` and `min-free-space-percent` together.
/// - `[archive]`: the keys of [`archive`].
/// - `[ex-integrity]`: the keys of [`ex_integrity`].
///   [`fsverity`](RepoConfig::fsverity) gives the value in effect of
///   `fsverity`, with its default from `composefs`.
/// - `[remote "<name>"]`: the keys of [`remote`], one section for each
///   remote. [`RemoteSectionExt::mirrored_collection_ids`] also refuses an
///   id that is the `collection-id` of the remote.
/// - `[ex-ostrya]`: the keys of [`ex_ostrya`], which are ostrya extensions.
///   [`gc_weak_references`](RepoConfig::gc_weak_references) also refuses a
///   list with no positive entry.
/// - The groups whose names start with `ex-ostrya` and a space, for example
///   `[ex-ostrya client "NAME"]`: the access of the clients of a server, and
///   the keys that verify and sign the commits that it receives.
///   [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
///   reads `[ex-ostrya server]` through the keys of [`server`], and the
///   `[ex-ostrya client "NAME"]` groups through the keys of [`client`].
///   [`TrustedKeys::from_trust_group`](crate::verify::TrustedKeys::from_trust_group)
///   reads an `[ex-ostrya trust "NAME"]` group through the keys of
///   [`trust`], and
///   [`SigningKey::from_key_group`](crate::sign::SigningKey::from_key_group)
///   reads an `[ex-ostrya key "NAME"]` group through the keys of [`key`].
///   Under the `receive` feature, `ReceivePolicies::from_config` reads each
///   trust group and each key group.
///
/// # Checks
///
/// [`from_keyfile`](RepoConfig::from_keyfile) checks `repo_version` and `mode`
/// when it loads the config. The `ostree` command also refuses to open a
/// repository whose version is not `1`.
///
/// Each other read parses its key when it is called. If the key is absent,
/// the read returns the default of the key. If the value is malformed, the
/// read returns an error, as the `ostree` command reports a value that it
/// cannot read.
///
/// [`check`](RepoConfig::check) parses the value of each key of the port
/// that the file sets, in one call. It also applies the rules of
/// [`gc_weak_references`](RepoConfig::gc_weak_references) and of
/// [`RemoteSectionExt::mirrored_collection_ids`], and refuses an unknown key
/// of `[ex-ostrya server]` and of each `[ex-ostrya client "NAME"]`,
/// `[ex-ostrya trust "NAME"]`, and `[ex-ostrya key "NAME"]` group.
#[derive(Debug, Clone)]
pub struct RepoConfig {
    keyfile: KeyFile,
    mode: RepoMode,
    repo_version: i64,
    collection_id: Option<String>,
    remote_files: Vec<RemoteFile>,
    /// The overrides of the handle that read the config. A config with no
    /// handle has none.
    overrides: Arc<Overrides>,
}

/// A `.conf` file of the remotes directory: its name in the directory and its
/// parsed text.
#[derive(Debug, Clone)]
pub(crate) struct RemoteFile {
    pub(crate) name: String,
    pub(crate) keyfile: KeyFile,
}

/// The source of a path that a key or a caller names. The source sets the
/// base of a relative path.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum KeyOrigin {
    /// A path of a caller. A relative path resolves against the working
    /// directory.
    Caller,
    /// A value of `<repo>/config`. A relative path resolves against the
    /// repository root.
    Config,
    /// A value of a `.conf` file of the remotes directory. A relative path
    /// resolves against that directory.
    RemotesFile,
}

/// A path that a key or a caller names, with its source.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct KeyPath {
    /// The path as the key or the caller gives it.
    pub(crate) value: PathBuf,
    /// The source of the path.
    pub(crate) origin: KeyOrigin,
}

impl KeyPath {
    /// Returns the path `value` of a caller.
    pub(crate) fn caller(value: impl Into<PathBuf>) -> KeyPath {
        KeyPath {
            value: value.into(),
            origin: KeyOrigin::Caller,
        }
    }

    /// Returns the descriptor that the path resolves against, the path to
    /// open from that descriptor, and the path that names the file in a
    /// message.
    ///
    /// A path of a caller resolves against the working directory. A value of
    /// `config` resolves against the root of `repo`, and the message shows
    /// the value. A value of a `.conf` file resolves against the remotes
    /// directory of `repo`, and the message shows the path of that directory
    /// joined with the value, as [`remotes_dir::entry`] gives it. An empty
    /// value of a `.conf` file names no file, as an empty value of `config`
    /// does. An absolute path ignores the descriptor.
    ///
    /// A value of a key comes from the config of `repo`, so it always has a
    /// repository handle. A value with no handle resolves against the
    /// working directory.
    pub(crate) fn locate<'a>(
        &'a self,
        repo: Option<&'a Repo>,
    ) -> (BorrowedFd<'a>, PathBuf, PathBuf) {
        match (self.origin, repo) {
            (KeyOrigin::Config, Some(repo)) => (
                repo.root_dir().as_fd(),
                self.value.clone(),
                self.value.clone(),
            ),
            (KeyOrigin::RemotesFile, Some(repo)) => match repo.remotes_dir() {
                Some(dir) => remotes_dir::entry(repo.root_dir().as_fd(), dir, &self.value),
                None => (rustix::fs::CWD, self.value.clone(), self.value.clone()),
            },
            _ => (rustix::fs::CWD, self.value.clone(), self.value.clone()),
        }
    }
}

/// Returns the I/O error of `err`, an error of the open of a [`KeyPath`]
/// file, with the text of its errno.
///
/// [`FsError::Absent`] gives `ENOENT`, and [`Reason::NotDirectory`] gives
/// `ENOTDIR`. Each other [`FsError::Invalid`] gives an error with its text.
pub(crate) fn io_of(err: FsError) -> std::io::Error {
    match err {
        FsError::Io(e) => e,
        FsError::Absent { .. } => Errno::NOENT.into(),
        FsError::Invalid {
            reason: Reason::NotDirectory,
            ..
        } => Errno::NOTDIR.into(),
        other => std::io::Error::other(Error::from(other).to_string()),
    }
}

/// The minimum free space that a write must leave.
///
/// If the config sets a size, the size applies and the percentage does not.
/// The write path applies the byte value of a [`Size`](MinFreeSpace::Size).
/// This type holds the parsed magnitude and unit as written.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MinFreeSpace {
    /// `min-free-space-percent`, from `0` to `100`.
    ///
    /// The default is `3`.
    Percent(u32),
    /// `min-free-space-size`, a magnitude with a binary unit suffix.
    Size(SizeSpec),
}

impl RepoConfig {
    /// Creates a typed view of a parsed [`KeyFile`].
    ///
    /// The call checks the `[core]` keys `repo_version` and `mode`. It also
    /// reads `[core] collection-id` and the names of the remote sections.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the config has no `[core]` group, no
    ///   `repo_version` key, or no `mode` key.
    /// - [`Error::InvalidFormat`] if `repo_version` is not `1`, or if `mode`
    ///   names no repository mode.
    /// - [`Error::Core`] if `repo_version` is not an integer, or if `mode` or
    ///   `collection-id` holds a malformed escape sequence.
    pub fn from_keyfile(keyfile: KeyFile) -> Result<RepoConfig> {
        if !keyfile.has_group(CORE) {
            return Err(Error::InvalidFormat("config has no [core] group".into()));
        }

        let repo_version = keyfile
            .get_integer(CORE, "repo_version")?
            .ok_or_else(|| Error::InvalidFormat("config [core] has no repo_version".into()))?;
        if repo_version != 1 {
            return Err(Error::InvalidFormat(format!(
                "unsupported repository version {repo_version}"
            )));
        }

        let mode_str = keyfile
            .get_string(CORE, "mode")?
            .ok_or_else(|| Error::InvalidFormat("config [core] has no mode".into()))?;
        let mode = RepoMode::from_mode_str(&mode_str)
            .ok_or_else(|| Error::InvalidFormat(format!("unknown repository mode '{mode_str}'")))?;

        let collection_id = keyfile.get_string(CORE, "collection-id")?;

        Ok(RepoConfig {
            keyfile,
            mode,
            repo_version,
            collection_id,
            remote_files: Vec::new(),
            overrides: Arc::default(),
        })
    }

    /// Adds the remotes of the `.conf` files of the remotes directory, in the
    /// order of `files`. The read gives the files in the byte order of their
    /// names. The call takes the `[remote "<name>"]` groups of each file and
    /// ignores each other group.
    ///
    /// `base` is the path that names the directory in an error message. A
    /// file is `base` joined with its name.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if two sources define one remote name.
    pub(crate) fn with_remote_files(
        mut self,
        base: &Path,
        files: Vec<RemoteFile>,
    ) -> Result<RepoConfig> {
        // A repeated group header merges into one group during parsing, so
        // each source gives each name once.
        let mut seen: HashMap<&str, Option<usize>> = self
            .keyfile
            .groups()
            .filter_map(remote_group_name)
            .map(|name| (name, None))
            .collect();
        for (index, file) in files.iter().enumerate() {
            for name in file.keyfile.groups().filter_map(remote_group_name) {
                if let Some(other) = seen.insert(name, Some(index)) {
                    let other = match other {
                        None => CONFIG_FILE.to_owned(),
                        Some(other) => base.join(&files[other].name).display().to_string(),
                    };
                    return Err(Error::InvalidFormat(format!(
                        "remote \"{name}\" is defined in {other} and in {}",
                        base.join(&file.name).display()
                    )));
                }
            }
        }
        self.remote_files = files;
        Ok(self)
    }

    /// Parses a config from its text.
    ///
    /// # Errors
    ///
    /// - [`Error::Core`] if the text is not a valid key file.
    /// - The errors of [`from_keyfile`](RepoConfig::from_keyfile).
    pub fn parse(text: &str) -> Result<RepoConfig> {
        RepoConfig::from_keyfile(KeyFile::parse(text)?)
    }

    /// Returns the storage mode of the repository.
    pub fn mode(&self) -> RepoMode {
        self.mode
    }

    /// Returns the `[core] repo_version` value.
    ///
    /// The value is always `1` for a config that this type accepts.
    pub fn repo_version(&self) -> i64 {
        self.repo_version
    }

    /// Returns the `[core] collection-id` of the repository, if it is set.
    pub fn collection_id(&self) -> Option<&str> {
        self.collection_id.as_deref()
    }

    /// Returns the parsed text of the `.conf` file `file` of the remotes
    /// directory by value, or `None` if the config holds no file of that
    /// name.
    pub(crate) fn into_remote_file(self, file: &str) -> Option<KeyFile> {
        self.remote_files
            .into_iter()
            .find(|held| held.name == file)
            .map(|held| held.keyfile)
    }

    /// Returns the minimum free space that a write must leave.
    ///
    /// If [`repo::MinFreeSpaceSize`] is set, it applies, and the call does not
    /// read [`repo::MinFreeSpacePercent`]. If it is not set,
    /// [`repo::MinFreeSpacePercent`] applies, with the default `3`.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if `min-free-space-size` does not match
    ///   `^([0-9]+)(G|M|T)B$`, or if its magnitude does not fit in a `u64`.
    /// - [`Error::InvalidFormat`] if `min-free-space-percent` is outside the
    ///   range `0` to `100`.
    /// - [`Error::Core`] if `min-free-space-percent` is not an integer.
    pub fn min_free_space(&self) -> Result<MinFreeSpace> {
        if let Some(spec) = self.get::<repo::MinFreeSpaceSize>()? {
            return Ok(MinFreeSpace::Size(spec));
        }
        Ok(MinFreeSpace::Percent(
            self.get::<repo::MinFreeSpacePercent>()?.get(),
        ))
    }

    /// Returns the selector of the refs that a prune marks weak, or `None` if
    /// the key is absent.
    ///
    /// The key is `[ex-ostrya] gc-weak-references`, and it is an ostrya
    /// extension. The value is a `;` list of ref patterns, the entries of a
    /// [`ReceiveSelector`]. An entry has one of these forms, with `*` and `**`
    /// in the name part:
    ///
    /// - `NAME` -- the local refs that `NAME` matches.
    /// - `REMOTE:NAME` -- the refs of the remote `REMOTE` that `NAME`
    ///   matches.
    /// - `*:NAME` -- the remote refs of each remote that `NAME` matches.
    /// - `@ID:NAME` -- the refs of the collection `ID` that `NAME` matches.
    ///
    /// An entry that starts with `!` is an exclusion. The selector selects a
    /// ref when a positive entry matches it, and no exclusion matches it. The
    /// list must hold at least one positive entry. An empty value and a list
    /// of exclusions alone are not valid. The order of the entries has no
    /// effect. Pass the `[core] collection-id` of the repository as `own` to
    /// [`ReceiveSelector::matches`]: `@OWN:NAME` then matches the local ref
    /// `NAME`.
    ///
    /// [`Repo::prune`] reads no config key for its ref classifier. The
    /// `ostrya prune` command reads this key and marks each selected ref weak
    /// through [`PruneOptions::weak_ref_filter`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if an entry is not a valid ref pattern. The
    ///   text names the key and the entry.
    /// - [`Error::InvalidFormat`] if the list holds no positive entry, for
    ///   example an empty value or a list of exclusions alone. The text names
    ///   the key.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    ///
    /// [`PruneOptions::weak_ref_filter`]: crate::PruneOptions::weak_ref_filter
    pub fn gc_weak_references(&self) -> Result<Option<ReceiveSelector>> {
        refuse_no_positive(self.get::<ex_ostrya::GcWeakReferences>()?)
    }

    /// Checks the keys of the groups of the port that the file sets.
    ///
    /// The call parses the values of the file alone. The overrides of the
    /// handle and the defaults of the keys do not apply, so a forced value
    /// does not hide a bad value of the file. The call checks these groups
    /// and keys, in this order:
    ///
    /// 1. Each key of [`repo`], [`archive`], [`ex_integrity`], and
    ///    [`ex_ostrya`] that the file sets, in the order of the definition of
    ///    the keys. For example, the call checks `min-free-space-percent` also
    ///    when `min-free-space-size` is set, and `fsverity` also when
    ///    `composefs` is set.
    /// 2. The rule of [`gc_weak_references`](RepoConfig::gc_weak_references):
    ///    the list holds a positive entry.
    /// 3. Each section of [`sections`](RepoConfig::sections) of
    ///    [`remote::Group`], in that order: each key of [`remote`] that the
    ///    section sets, then the rule of
    ///    [`RemoteSectionExt::mirrored_collection_ids`]. The sections include
    ///    the remotes of the `.conf` files of the remotes directory that the
    ///    config holds. A config of [`from_keyfile`](RepoConfig::from_keyfile)
    ///    or [`parse`](RepoConfig::parse) holds no `.conf` file, so the call
    ///    then checks the remote groups of the document alone.
    /// 4. `[ex-ostrya server]`: first a key that [`server`] does not list,
    ///    then each key of [`server`] that the file sets, in the order of the
    ///    definition of the keys.
    /// 5. Each section of [`sections`](RepoConfig::sections) of
    ///    [`client::Group`], in the order of the file: first the removed key
    ///    `collection`, then a key that [`client`] does not list, then each
    ///    key of [`client`] that the section sets, in the order of the
    ///    definition of the keys.
    /// 6. Each section of [`sections`](RepoConfig::sections) of
    ///    [`trust::Group`], in the order of the file: first a key that
    ///    [`trust`] does not list, then each key of [`trust`] that the
    ///    section sets, in the order of the definition of the keys, then the
    ///    rules of the X.509 keys of the spki engine, with the texts of a
    ///    remote section.
    /// 7. Each section of [`sections`](RepoConfig::sections) of
    ///    [`key::Group`], in the order of the file: first a key that [`key`]
    ///    does not list, then each key of [`key`] that the section sets, in
    ///    the order of the definition of the keys.
    ///
    /// The call gives the first error that it finds. An unknown key gives the
    /// text `[GROUP] holds the unknown key 'KEY'`, where `GROUP` is the group
    /// header, and a bad value gives the text of the typed read of the key.
    /// The texts of the server group and of the client groups are the texts
    /// of [`ClientAccess::from_config`]. The texts of an unknown key of a
    /// trust group and of a key group are the texts of the readers of these
    /// groups, also the texts of the trust keys that [`trust`] names. The
    /// call does not apply these rules of [`ClientAccess::from_config`]:
    ///
    /// - The refusal of a group name that starts with `ex-ostrya` and a space
    ///   and has no known form, and of a quoted name with a control
    ///   character.
    /// - The references to other groups: a name of [`server::SignSummary`] or
    ///   of [`client::Sign`] names a key group, and [`client::Verify`] names
    ///   a trust group.
    /// - The rules of a client group: [`client::Auth`] holds one or more
    ///   items, an auth item is in one group alone,
    ///   [`client::TlsAcceptClaim`] needs a TLS item, `tls-accept-claim=true`
    ///   refuses `summary=true`, and `allow-unsigned=false` needs `verify`.
    /// - The rules between the server keys of [`ClientAccess::check_server`].
    ///
    /// The call does not apply these rules of the readers of the trust groups
    /// and the key groups,
    /// [`TrustedKeys::from_trust_group`](crate::verify::TrustedKeys::from_trust_group)
    /// and [`SigningKey::from_key_group`](crate::sign::SigningKey::from_key_group):
    ///
    /// - A trust group: an engine of [`trust::SignVerify`] other than
    ///   `ed25519` and `spki`, a group that turns on no check,
    ///   [`trust::GpgKeyPath`] without `gpg-verify=true`, `gpg-verify=true`
    ///   with no keyring or with an empty entry of `gpgkeypath`, a
    ///   verification key of an engine that the group does not select, and
    ///   [`trust::VerificationSpkiIdentity`] with no
    ///   [`trust::VerificationSpkiCaFile`].
    /// - A key group: a group with no [`key::Type`], a key of another type,
    ///   an absent or empty [`key::SecretKeyFile`] or [`key::GpgKey`] that
    ///   the type needs, and an empty [`key::CertificateChainFile`] or
    ///   [`key::CrlFile`].
    /// - The refusals of a type or an engine that the build does not have.
    ///
    /// The call does not check a key that an open group does not list, for
    /// example `[core] parent`. It does not check a group that the port does
    /// not define, such as `[ex-debles]`. It does not check a header of a
    /// remote, a client, a trust, or a key group that
    /// [`sections`](RepoConfig::sections) skips.
    ///
    /// [`Repo::write_config`], [`UpdateGuard::write_config`], and
    /// [`UpdateGuard::edit_config`] do not call this check. The `ostrya
    /// config set` and `ostrya config unset` commands call it on a config of
    /// the edited document before they write it. So these commands check the
    /// `config` document alone. They do not check the remote groups of the
    /// `.conf` files of the remotes directory.
    ///
    /// [`UpdateGuard::write_config`]: crate::UpdateGuard::write_config
    /// [`UpdateGuard::edit_config`]: crate::UpdateGuard::edit_config
    /// [`ClientAccess::from_config`]: crate::access::ClientAccess::from_config
    /// [`ClientAccess::check_server`]: crate::access::ClientAccess::check_server
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if `[ex-ostrya server]` holds a key that
    ///   [`server`] does not list, if a client group holds the key
    ///   `collection` or a key that [`client`] does not list, if a trust
    ///   group holds a key that [`trust`] does not list, or if a key group
    ///   holds a key that [`key`] does not list.
    /// - The error of the typed read of the first key whose value does not
    ///   parse: [`Error::Core`] for a value that is not a boolean or not an
    ///   integer, or that holds a malformed escape sequence, and
    ///   [`Error::InvalidFormat`] for each other value.
    /// - The errors of [`gc_weak_references`](RepoConfig::gc_weak_references)
    ///   and of [`RemoteSectionExt::mirrored_collection_ids`] for a list that
    ///   breaks the rule of the key.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=true\n")?;
    /// cfg.check()?;
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=maybe\n")?;
    /// assert_eq!(
    ///     cfg.check().unwrap_err().to_string(),
    ///     "keyfile: value 'maybe' for core.fsync is not a boolean"
    /// );
    ///
    /// // The check does not read a key that the port does not define.
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nparent=/srv/p\n")?;
    /// cfg.check()?;
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn check(&self) -> Result<()> {
        let keyfile = &self.keyfile;
        repo::check_file(keyfile, <repo::Group as Group>::NAME)?;
        archive::check_file(keyfile, <archive::Group as Group>::NAME)?;
        ex_integrity::check_file(keyfile, <ex_integrity::Group as Group>::NAME)?;
        ex_ostrya::check_file(keyfile, <ex_ostrya::Group as Group>::NAME)?;
        refuse_no_positive(self.file_value::<ex_ostrya::GcWeakReferences>()?)?;
        for section in self.sections::<remote::Group>() {
            section.check()?;
        }
        server::check_file(keyfile, <server::Group as Group>::NAME)?;
        for section in self.sections::<client::Group>() {
            section.check()?;
        }
        for section in self.sections::<trust::Group>() {
            section.check()?;
        }
        for section in self.sections::<key::Group>() {
            section.check()?;
        }
        Ok(())
    }

    /// Returns the value in effect of the key `key` of the group `group`, as
    /// the raw text of a key file.
    ///
    /// The `ostrya config get --effective` command reads a value with this
    /// call. The method is not a stable API.
    ///
    /// - A key of [`repo`], [`archive`], [`ex_integrity`], [`ex_ostrya`],
    ///   [`remote`], [`server`], [`client`], [`trust`], or [`key`] gives the
    ///   value of its typed
    ///   read as the text of [`Value::format`]: a forced value of the handle,
    ///   the value of the file, a fallback value of the handle, or the default
    ///   of the key. A key with no value gives [`TextInEffect::NoKey`], also
    ///   when the file does not hold a single group.
    /// - `[ex-integrity] fsverity` gives the value of
    ///   [`fsverity`](RepoConfig::fsverity), and `[ex-ostrya]
    ///   gc-weak-references` gives the value of
    ///   [`gc_weak_references`](RepoConfig::gc_weak_references).
    /// - `[ex-ostrya] remotes-config-dir` gives the value of the key.
    ///   [`Repo::remotes_dir`] gives the remotes directory of a handle.
    /// - A group `remote "NAME"` reads the section that
    ///   [`section`](RepoConfig::section) gives, so it also reads the `.conf`
    ///   files of the remotes directory that the config holds. A name with no
    ///   section gives [`TextInEffect::NoGroup`]. `mirrored-collection-ids`
    ///   gives the value of [`RemoteSectionExt::mirrored_collection_ids`], and
    ///   [`TextInEffect::NoKey`] if the section does not set it.
    /// - A group `ex-ostrya client "NAME"` reads the section that
    ///   [`section`](RepoConfig::section) gives. A name with no section gives
    ///   [`TextInEffect::NoGroup`]: an empty name, a name that holds `"`, and
    ///   the name of the implicit client group of
    ///   [`ClientAccess::from_config`]. `allow-unsigned` gives the
    ///   value of [`ClientSectionExt::allow_unsigned`].
    /// - A group `ex-ostrya trust "NAME"` or `ex-ostrya key "NAME"` reads the
    ///   section that [`section`](RepoConfig::section) gives. A name with no
    ///   section gives [`TextInEffect::NoGroup`], also an empty name and a
    ///   name that holds `"`.
    /// - Each other key gives the raw text of the file:
    ///   [`TextInEffect::NoGroup`] if the file does not hold the group, and
    ///   [`TextInEffect::NoKey`] if the group does not hold the key. The file
    ///   of a remote is the file that holds its section.
    ///
    /// [`ClientAccess::from_config`]: crate::access::ClientAccess::from_config
    ///
    /// # Errors
    ///
    /// The errors of the typed read of the key, and the errors of the methods
    /// that the list names.
    #[doc(hidden)]
    pub fn text_in_effect(&self, group: &str, key: &str) -> Result<TextInEffect> {
        if let Some(name) = remote_group_name(group) {
            return match self.section::<remote::Group>(name) {
                Some(section) => section.text_in_effect(key),
                None => Ok(TextInEffect::NoGroup),
            };
        }
        if is_header_of::<client::Group>(group) {
            return match self.section_of_header::<client::Group>(group) {
                Some(section) => section.text_in_effect(key),
                None => Ok(TextInEffect::NoGroup),
            };
        }
        if is_header_of::<trust::Group>(group) {
            return match self.section_of_header::<trust::Group>(group) {
                Some(section) => section.text_in_effect(key),
                None => Ok(TextInEffect::NoGroup),
            };
        }
        if is_header_of::<key::Group>(group) {
            return match self.section_of_header::<key::Group>(group) {
                Some(section) => section.text_in_effect(key),
                None => Ok(TextInEffect::NoGroup),
            };
        }
        let keyfile = &self.keyfile;
        let overrides: Option<&Overrides> = Some(&self.overrides);
        let typed = if group == <repo::Group as Group>::NAME {
            repo::text_in_effect(keyfile, group, overrides, key).map(|r| r.map_err(Error::from))
        } else if group == <archive::Group as Group>::NAME {
            archive::text_in_effect(keyfile, group, overrides, key).map(|r| r.map_err(Error::from))
        } else if group == <ex_integrity::Group as Group>::NAME {
            if key == <ex_integrity::Fsverity as Key<ex_integrity::Group>>::NAME {
                Some(self.fsverity().map(|value| Some(value.format())))
            } else {
                ex_integrity::text_in_effect(keyfile, group, overrides, key)
                    .map(|r| r.map_err(Error::from))
            }
        } else if group == <ex_ostrya::Group as Group>::NAME {
            if key == <ex_ostrya::GcWeakReferences as Key<ex_ostrya::Group>>::NAME {
                Some(
                    self.gc_weak_references()
                        .map(|value| value.map(|selector| selector.format())),
                )
            } else {
                ex_ostrya::text_in_effect(keyfile, group, overrides, key)
                    .map(|r| r.map_err(Error::from))
            }
        } else if group == <server::Group as Group>::NAME {
            server::text_in_effect(keyfile, group, overrides, key).map(|r| r.map_err(Error::from))
        } else {
            None
        };
        if let Some(text) = typed {
            return Ok(text?.map_or(TextInEffect::NoKey, TextInEffect::Value));
        }
        if !keyfile.has_group(group) {
            return Ok(TextInEffect::NoGroup);
        }
        Ok(keyfile
            .get_value(group, key)
            .map_or(TextInEffect::NoKey, |raw| {
                TextInEffect::Value(raw.to_owned())
            }))
    }

    /// Returns the section of the named group `G` whose header is `group`,
    /// or `None` if `group` names no section of `G` that
    /// [`section`](RepoConfig::section) gives.
    fn section_of_header<G: Group>(&self, group: &str) -> Option<Section<'_, G>> {
        section_name::<G>(group).and_then(|name| self.section::<G>(name))
    }

    /// Returns the `[ex-integrity] fsverity` setting.
    ///
    /// [`ex_integrity::Fsverity`] states the effect of each value. An explicit
    /// value applies as written. If the key is absent, the default is `No`. If
    /// the key is absent and [`ex_integrity::Composefs`] is `Yes` or `Maybe`,
    /// the default is `Maybe`. The call reads `composefs` only when the key is
    /// absent.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is not `no`, `maybe`, or `yes`.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    /// - If the key is absent, the same errors for `composefs`.
    pub fn fsverity(&self) -> Result<Tristate> {
        if let Some(explicit) = self.get::<ex_integrity::Fsverity>()? {
            return Ok(explicit);
        }
        Ok(match self.get::<ex_integrity::Composefs>()? {
            Tristate::No => Tristate::No,
            Tristate::Maybe | Tristate::Yes => Tristate::Maybe,
        })
    }

    /// Returns the parsed key file of `config`.
    ///
    /// A caller can read the keys that this type does not model. The key file
    /// keeps the order of the source text when it writes the config again.
    /// The key file holds no group of the `.conf` files of the remotes
    /// directory.
    pub fn keyfile(&self) -> &KeyFile {
        &self.keyfile
    }

    /// Returns the parsed key file of `config` by value.
    pub(crate) fn into_keyfile(self) -> KeyFile {
        self.keyfile
    }

    /// Returns the config with the overrides `overrides` in place of its own.
    pub(crate) fn with_overrides(mut self, overrides: Arc<Overrides>) -> RepoConfig {
        self.overrides = overrides;
        self
    }

    /// Returns the overrides of the config.
    pub(crate) fn overrides(&self) -> &Arc<Overrides> {
        &self.overrides
    }
}

/// Methods that write the config and the keyring of a remote.
impl Repo {
    /// Replaces the repository `config` with the document in `keyfile`.
    ///
    /// The call writes the file as the write path writes each file at the
    /// repository root:
    ///
    /// 1. It writes a new named temp file `tmp/.ostrya-tmp-<pid>-XXXXXX` at
    ///    mode `0644`. It makes `tmp/` if it does not exist.
    /// 2. If `[core] fsync` is on, it syncs the file with `fsync`.
    /// 3. It renames the file over `config`.
    /// 4. If `[core] fsync` is on, it syncs the repository directory.
    ///
    /// A reader sees the old document or the new one.
    ///
    /// # Edits
    ///
    /// The call writes the document as given and does not check its
    /// `[core]` keys. It does not call [`RepoConfig::check`]. A caller that
    /// must write a document with valid values calls the check on a
    /// `RepoConfig` of the document before the write. The `ostree` command also writes the document of
    /// `config unset core.mode` with no check. If a caller removes `[core]
    /// mode` or `[core] repo_version`, [`Repo::open`] refuses the written
    /// file. To change a key, a caller reads the current document through
    /// [`RepoConfig::keyfile`], changes it with the setters and removers of
    /// [`KeyFile`], and writes it back.
    ///
    /// The call refuses a document with a `[remote "NAME"]` group when a
    /// `.conf` file of the remotes directory of the handle defines `NAME`,
    /// because each later open refuses a remote name in two sources. Under
    /// the locks, the call reads the files of the directory again for this
    /// check.
    ///
    /// This handle keeps the configuration that it was opened with. To read
    /// the new values, open the repository again. This also applies to
    /// `[core] collection-id`, as
    /// [`UpdateGuard::set_ref`](crate::UpdateGuard::set_ref) states.
    ///
    /// # Locks
    ///
    /// The call takes the repository lock shared, as
    /// [`LockKind`](crate::LockKind) describes. Then it takes the update lock
    /// for its write step, as [`Repo::begin_update`] does. It writes under both
    /// locks.
    ///
    /// The locks cover the write alone. A document that a caller read from
    /// this handle before the call can miss the write of another writer. A
    /// read-modify-write that must see the current file reads and writes it
    /// through an [`UpdateGuard`](crate::UpdateGuard).
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the document is larger than 1 MiB, the
    ///   size that an open accepts. The call then writes nothing.
    /// - [`Error::RemoteExists`] if the document has a group of a remote of
    ///   the remotes directory. The call then writes nothing.
    /// - The errors of [`OpenOptions::open`](crate::OpenOptions::open) for the
    ///   remotes directory and its `.conf` files.
    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
    ///   lock-timeout-secs`. Each of the two waits gets the full timeout.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` of this handle
    ///   is less than `-1`.
    /// - [`Error::Core`] if `[core] fsync` or `[core] locking` of this handle
    ///   is not a boolean, or if `[core] lock-timeout-secs` is not an integer.
    /// - [`Error::InvalidFormat`] if a symlink or an entry that is not a
    ///   regular file is at `.lock` or at `.update.lock`. The lock open
    ///   follows no symlink. If the process cannot open a FIFO, a socket, or
    ///   a device there for write, the error is [`Error::Io`].
    /// - [`Error::InvalidFormat`] if `tmp` or `tmp/cache` is a symlink or is
    ///   not a directory.
    /// - [`Error::Io`] if a lock file, the write, the rename, or a sync fails
    ///   on the file system.
    pub async fn write_config(&self, keyfile: &KeyFile) -> Result<()> {
        let fsync = self.config().get::<repo::Fsync>()?;
        let bytes = keyfile.to_string().into_bytes();
        check_config_size(&bytes)?;
        let names = remotes_dir::config_remote_names(keyfile);
        self.write_locked(move |repo| {
            remotes_dir::check_config_remotes(repo.repo_fd(), repo.remotes_dir(), &names)?;
            repo.root_dir()
                .write_root_file(RootFile::Config, &bytes, Publish::Replace, fsync)?;
            Ok(())
        })
        .await
    }

    /// Removes the trusted GPG keyring of a remote at the repository root.
    ///
    /// The file is `<remote>.trustedkeys.gpg`. If the keyring is absent, the
    /// call succeeds. For a symlink, the call removes the link, and the
    /// target stays. The keyring belongs to the config section of the remote,
    /// so a deletion of the section also deletes this file. With `[core]
    /// fsync` on, the call syncs the repository directory with `fsync` after
    /// the removal.
    ///
    /// The call takes the same locks as [`write_config`](Repo::write_config)
    /// and waits for them in the same way.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidInput`] if [`valid_remote_name`] refuses `remote`.
    ///   The call refuses the name before it takes a lock, and removes no
    ///   file.
    /// - [`Error::Core`] if `[core] fsync` of this handle is not a boolean.
    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
    ///   lock-timeout-secs`.
    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` of this handle
    ///   is less than `-1`.
    /// - [`Error::Core`] if `[core] locking` of this handle is not a boolean,
    ///   or if `[core] lock-timeout-secs` is not an integer.
    /// - [`Error::InvalidFormat`] if a symlink or an entry that is not a
    ///   regular file is at `.lock` or at `.update.lock`. The lock open
    ///   follows no symlink. If the process cannot open a FIFO, a socket, or
    ///   a device there for write, the error is [`Error::Io`].
    /// - [`Error::Io`] if a lock file or the removal fails on the file system.
    pub async fn remove_remote_keyring(&self, remote: &str) -> Result<()> {
        if !valid_remote_name(remote) {
            return Err(Error::InvalidInput(format!(
                "invalid remote name: {remote}"
            )));
        }
        let name = remote_keyring_name(remote);
        let fsync = self.config().get::<repo::Fsync>()?;
        self.write_locked(move |repo| {
            repo.root_dir().remove_file(&name, fsync)?;
            Ok(())
        })
        .await
    }
}

/// Returns `selector`, a value of `[ex-ostrya] gc-weak-references`, or an
/// error if it is a list with no positive entry.
fn refuse_no_positive(selector: Option<ReceiveSelector>) -> Result<Option<ReceiveSelector>> {
    if selector.as_ref().is_some_and(|s| !s.has_positive()) {
        return Err(Error::InvalidFormat(format!(
            "[{EX_OSTRYA}] gc-weak-references: the list holds no pattern without '!'"
        )));
    }
    Ok(selector)
}

/// Returns the name of the trusted keyring of a remote at the repository root.
pub(crate) fn remote_keyring_name(remote: &str) -> String {
    format!("{remote}.trustedkeys.gpg")
}

/// Returns the key-file group name of a remote: `remote "<name>"`.
///
/// The function is not a stable API.
#[doc(hidden)]
pub fn remote_group(name: &str) -> String {
    format!("remote \"{name}\"")
}

/// Returns `true` if the `ostree` command accepts `name` as a remote name.
///
/// A valid name obeys these rules:
///
/// - It has at least one character.
/// - Each character is alphanumeric, `-`, `_`, or `.`.
/// - The first character is alphanumeric or `_`.
///
/// For example, `_` is a valid name, and `-`, `.`, and `..` are not.
/// "Alphanumeric" is [`char::is_alphanumeric`], so a non-ASCII letter counts.
pub fn valid_remote_name(name: &str) -> bool {
    let mut chars = name.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    if !(first.is_alphanumeric() || first == '_') {
        return false;
    }
    name.chars()
        .all(|c| c.is_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

/// Returns the remote name in a `remote "<name>"` group header, or `None` for
/// another group.
///
/// The function is not a stable API.
#[doc(hidden)]
pub fn remote_group_name(group: &str) -> Option<&str> {
    group
        .strip_prefix("remote \"")
        .and_then(|rest| rest.strip_suffix('"'))
}

/// Returns the group name in an `ex-ostrya trust "<name>"` group header, or
/// `None` for another group.
///
/// The function is not a stable API.
#[doc(hidden)]
pub fn trust_group_name(group: &str) -> Option<&str> {
    group
        .strip_prefix(<trust::Group as Group>::NAME)
        .and_then(|rest| rest.strip_prefix(" \""))
        .and_then(|rest| rest.strip_suffix('"'))
}

/// Returns `true` if `group` has the form of a header of the named group
/// `G`: `NAME "..."`, with any text between the quotes.
fn is_header_of<G: Group>(group: &str) -> bool {
    group
        .strip_prefix(G::NAME)
        .and_then(|rest| rest.strip_prefix(" \""))
        .is_some_and(|rest| rest.ends_with('"'))
}

/// The value in effect of one key, as [`RepoConfig::text_in_effect`] gives
/// it.
///
/// The type is not a stable API.
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextInEffect {
    /// The raw text of the value, as a key file holds it.
    Value(String),
    /// The group holds no value of the key.
    NoKey,
    /// The config holds no such group.
    NoGroup,
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use ostrya_core::Ref;

    const ARCHIVE_CONFIG: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";

    /// Returns the names of the remote sections of `cfg`, in the order of
    /// [`RepoConfig::sections`].
    fn remote_names(cfg: &RepoConfig) -> Vec<&str> {
        cfg.sections::<remote::Group>().map(|s| s.name()).collect()
    }

    #[test]
    fn valid_remote_name_takes_the_names_the_tool_takes() {
        for name in ["_", "1o", "a..b", "\u{e9}", "origin"] {
            assert!(valid_remote_name(name), "{name:?}");
        }
        for name in ["", "-", ".", "..", "a b", "a/b", "a+b"] {
            assert!(!valid_remote_name(name), "{name:?}");
        }
    }

    #[test]
    fn parses_core_mode_and_version() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert_eq!(cfg.mode(), RepoMode::Archive);
        assert_eq!(cfg.repo_version(), 1);
        assert_eq!(cfg.collection_id(), None);
        assert_eq!(remote_names(&cfg).len(), 0);
    }

    #[test]
    fn rejects_unsupported_repo_version() {
        let err = RepoConfig::parse("[core]\nrepo_version=2\nmode=bare\n").unwrap_err();
        assert!(matches!(err, Error::InvalidFormat(_)));
        assert!(err.to_string().contains("version 2"));
    }

    #[test]
    fn rejects_missing_core_group_and_keys() {
        assert!(RepoConfig::parse("[other]\nx=1\n").is_err());
        assert!(RepoConfig::parse("[core]\nmode=bare\n").is_err());
        assert!(RepoConfig::parse("[core]\nrepo_version=1\n").is_err());
    }

    #[test]
    fn rejects_unknown_mode() {
        let err = RepoConfig::parse("[core]\nrepo_version=1\nmode=bogus\n").unwrap_err();
        assert!(err.to_string().contains("unknown repository mode 'bogus'"));
    }

    #[test]
    fn reads_collection_id() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\ncollection-id=org.ex.C\n")
            .unwrap();
        assert_eq!(cfg.collection_id(), Some("org.ex.C"));
    }

    #[test]
    fn tunables_default_when_absent() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert!(cfg.get::<repo::Fsync>().unwrap());
        assert!(!cfg.get::<repo::PerObjectFsync>().unwrap());
        assert!(cfg.get::<repo::Locking>().unwrap());
        assert_eq!(cfg.get::<repo::LockTimeoutSecs>().unwrap().get(), 300);
        assert_eq!(cfg.get::<repo::TmpExpirySecs>().unwrap(), 86400);
        assert!(!cfg.get::<repo::DisableXattrs>().unwrap());
        assert_eq!(
            cfg.get::<repo::DefaultRepoFinders>().unwrap(),
            vec!["config".to_owned(), "mount".to_owned()]
        );
        assert_eq!(cfg.get::<archive::ZlibLevel>().unwrap(), 6);
        assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(3));
    }

    #[test]
    fn tunables_read_configured_values() {
        let text = "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\
                    per-object-fsync=1\nlock-timeout-secs=30\nmin-free-space-percent=5\n\
                    [archive]\nzlib-level=9\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert!(!cfg.get::<repo::Fsync>().unwrap());
        assert!(cfg.get::<repo::PerObjectFsync>().unwrap());
        assert_eq!(cfg.get::<repo::LockTimeoutSecs>().unwrap().get(), 30);
        assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(5));
        assert_eq!(cfg.get::<archive::ZlibLevel>().unwrap(), 9);
    }

    #[test]
    fn lock_timeout_secs_takes_minus_one_and_refuses_below() {
        let with = |v: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=bare\nlock-timeout-secs={v}\n"
            ))
            .unwrap()
        };
        let read = |v: &str| with(v).get::<repo::LockTimeoutSecs>();
        assert_eq!(read("-1").unwrap().get(), -1);
        assert_eq!(read("0").unwrap().get(), 0);
        let err = read("-2").unwrap_err();
        assert!(err.to_string().contains("lock-timeout-secs -2 is below -1"));
    }

    #[test]
    fn bad_boolean_value_is_an_error() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=yes\n").unwrap();
        assert!(cfg.get::<repo::Fsync>().is_err());
    }

    #[test]
    fn min_free_space_size_wins_over_percent() {
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    min-free-space-percent=5\nmin-free-space-size=2GB\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(
            cfg.min_free_space().unwrap(),
            MinFreeSpace::Size(SizeSpec {
                value: 2,
                unit: SizeUnit::Giga
            })
        );
    }

    #[test]
    fn rejects_out_of_range_min_free_space_percent() {
        for bad in ["-1", "101"] {
            let text = format!("[core]\nrepo_version=1\nmode=bare\nmin-free-space-percent={bad}\n");
            let cfg = RepoConfig::parse(&text).unwrap();
            assert!(cfg.min_free_space().is_err(), "should reject {bad}");
        }
    }

    #[test]
    fn ex_integrity_defaults_off() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert_eq!(cfg.get::<ex_integrity::Composefs>().unwrap(), Tristate::No);
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn composefs_raises_fsverity_default_to_maybe() {
        for composefs in ["yes", "maybe"] {
            let text = format!(
                "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs={composefs}\n"
            );
            let cfg = RepoConfig::parse(&text).unwrap();
            assert_eq!(
                cfg.fsverity().unwrap(),
                Tristate::Maybe,
                "composefs={composefs}"
            );
        }
        // composefs=no leaves fsverity off.
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\ncomposefs=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn explicit_fsverity_overrides_the_composefs_default() {
        // An explicit fsverity value wins over the composefs-derived default.
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    [ex-integrity]\ncomposefs=yes\nfsverity=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);

        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=yes\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::Yes);
    }

    #[test]
    fn malformed_tristate_is_an_error() {
        let text = "[core]\nrepo_version=1\nmode=bare\n[ex-integrity]\nfsverity=true\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert!(cfg.fsverity().is_err());
    }

    #[test]
    fn explicit_fsverity_ignores_a_malformed_composefs() {
        // The call does not read composefs when fsverity has an explicit
        // value, so a malformed composefs does not fail the fsverity read.
        let text = "[core]\nrepo_version=1\nmode=bare\n\
                    [ex-integrity]\ncomposefs=perhaps\nfsverity=no\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(cfg.fsverity().unwrap(), Tristate::No);
    }

    #[test]
    fn keep_detached_related_is_true_when_absent() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert!(cfg.get::<ex_ostrya::KeepDetachedRelated>().unwrap());
    }

    #[test]
    fn keep_detached_related_reads_a_boolean() {
        let read = |value: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
                 keep-detached-related={value}\n"
            ))
            .unwrap()
            .get::<ex_ostrya::KeepDetachedRelated>()
        };
        assert!(!read("false").unwrap());
        assert!(!read("0").unwrap());
        assert!(read("true").unwrap());
        assert!(read("1").unwrap());
        assert!(read("maybe").is_err());
        assert!(read("yes").is_err());
    }

    #[test]
    fn gc_weak_references_is_none_when_absent() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n").unwrap();
        assert!(cfg.gc_weak_references().unwrap().is_none());
    }

    #[test]
    fn gc_weak_references_reads_a_pattern_list() {
        let read = |value: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=bare\n[ex-ostrya]\n\
                 gc-weak-references={value}\n"
            ))
            .unwrap()
            .gc_weak_references()
        };
        let sel = read("tmp/**;!tmp/keep;*:**;@org.example.X:**")
            .unwrap()
            .unwrap();
        let own = Some("org.example.Own");
        assert!(sel.matches(&Ref::local("tmp/a"), own));
        assert!(sel.matches(&Ref::local("tmp/a/b"), own));
        assert!(!sel.matches(&Ref::local("tmp/keep"), own));
        assert!(!sel.matches(&Ref::local("main"), own));
        assert!(sel.matches(&Ref::remote("origin", "main"), own));
        assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
        assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));

        for value in ["", " ", ";", "!tmp/**", "!tmp/a;!tmp/b"] {
            let err = read(value).unwrap_err();
            assert!(
                matches!(&err, Error::InvalidFormat(m)
                    if m.contains("[ex-ostrya] gc-weak-references")),
                "{value:?}: {err}"
            );
        }

        let err = read("tmp/**;r*:x").unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m)
                if m.contains("[ex-ostrya] gc-weak-references")
                    && m.contains("malformed receive pattern")),
            "{err}"
        );
    }

    #[test]
    fn push_branches_is_none_when_absent() {
        let cfg = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\nurl=http://a/\n",
        )
        .unwrap();
        let origin = cfg.section::<remote::Group>("origin").unwrap();
        assert!(origin.get::<remote::PushBranches>().unwrap().is_none());
    }

    #[test]
    fn push_branches_reads_a_pattern_list() {
        let read = |value: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\n\
                 url=http://a/\npush-branches={value}\n"
            ))
            .unwrap()
            .section::<remote::Group>("origin")
            .unwrap()
            .get::<remote::PushBranches>()
        };
        let sel = read("apps/**;!apps/b;@org.example.X:**;@org.example.Own:**")
            .unwrap()
            .unwrap();
        let own = Some("org.example.Own");
        assert!(sel.matches(&Ref::local("apps/a"), own));
        assert!(!sel.matches(&Ref::local("apps/b"), own));
        assert!(sel.matches(&Ref::local("main"), own));
        assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
        assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));

        let empty = read("").unwrap().unwrap();
        assert!(empty.matches(&Ref::local("main"), None));

        let err = read("apps/**;r*:x").unwrap_err();
        assert!(
            matches!(&err, ConfigError::InvalidFormat(m)
                if m.contains("[remote \"origin\"] push-branches")
                    && m.contains("malformed receive pattern")),
            "{err}"
        );
    }

    #[test]
    fn pull_branches_is_none_when_absent() {
        let cfg = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\nurl=http://a/\n\
             branches=main;\n",
        )
        .unwrap();
        let origin = cfg.section::<remote::Group>("origin").unwrap();
        assert!(origin.get::<remote::PullBranches>().unwrap().is_none());
    }

    #[test]
    fn pull_branches_reads_a_pattern_list() {
        let read = |value: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=bare\n[remote \"origin\"]\n\
                 url=http://a/\npull-branches={value}\n"
            ))
            .unwrap()
            .section::<remote::Group>("origin")
            .unwrap()
            .get::<remote::PullBranches>()
        };
        let sel = read("apps/**;!apps/b;@org.example.X:**").unwrap().unwrap();
        let own = Some("org.example.Own");
        assert!(sel.matches(&Ref::local("apps/a"), own));
        assert!(!sel.matches(&Ref::local("apps/b"), own));
        assert!(sel.matches(&Ref::collection("org.example.X", "main"), own));
        assert!(!sel.matches(&Ref::collection("org.example.Y", "main"), own));

        let err = read("apps/**;r*:x").unwrap_err();
        assert!(
            matches!(&err, ConfigError::InvalidFormat(m)
                if m.contains("[remote \"origin\"] pull-branches")
                    && m.contains("malformed receive pattern")),
            "{err}"
        );
    }

    /// Summary regeneration is off by default, and `auto-update-summary`
    /// turns it on. The read does not see `commit-update-summary`.
    #[test]
    fn auto_update_summary_reads_its_key_alone() {
        let read = |extra: &str| {
            RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
                .unwrap()
                .get::<repo::AutoUpdateSummary>()
        };
        assert!(!read("").unwrap());
        assert!(read("auto-update-summary=true\n").unwrap());
        assert!(!read("auto-update-summary=false\n").unwrap());
        assert!(!read("commit-update-summary=true\n").unwrap());
        assert!(!read("commit-update-summary=yes\n").unwrap());
        assert!(read("auto-update-summary=true\ncommit-update-summary=yes\n").unwrap());
        assert!(!read("auto-update-summary=false\ncommit-update-summary=true\n").unwrap());
    }

    /// A value of `auto-update-summary` that is not a boolean is an error, also
    /// when `commit-update-summary` is true.
    #[test]
    fn a_malformed_auto_update_summary_is_an_error() {
        for extra in [
            "auto-update-summary=yes\n",
            "auto-update-summary=yes\ncommit-update-summary=true\n",
        ] {
            let cfg = RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
                .unwrap();
            assert!(
                matches!(
                    cfg.get::<repo::AutoUpdateSummary>(),
                    Err(Error::Core(ostrya_core::Error::KeyFile(_)))
                ),
                "{extra:?}"
            );
        }
    }

    #[test]
    fn parses_remote_sections() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"origin\"]\nurl=https://example.com/repo\nbranches=main;\n\
                    gpg-verify=false\n\n\
                    [remote \"withkey\"]\nurl=https://ex2.com/r\ncollection-id=org.ex.C\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(remote_names(&cfg), ["origin", "withkey"]);

        let origin = cfg.section::<remote::Group>("origin").unwrap();
        assert_eq!(
            origin.get::<remote::Url>().unwrap().as_deref(),
            Some("https://example.com/repo")
        );
        assert!(!origin.get::<remote::GpgVerify>().unwrap());
        assert!(!origin.get::<remote::GpgVerifySummary>().unwrap());
        assert_eq!(origin.raw_value::<remote::Branches>(), Some("main;"));
        assert_eq!(
            origin.get::<remote::Branches>().unwrap(),
            Some(vec!["main".to_owned()])
        );
        assert!(!origin.get::<remote::TlsPermissive>().unwrap());
        assert_eq!(origin.get::<remote::TlsCaPath>().unwrap(), None);

        let withkey = cfg.section::<remote::Group>("withkey").unwrap();
        assert!(withkey.get::<remote::GpgVerify>().unwrap()); // default true
        assert_eq!(
            withkey.get::<remote::CollectionId>().unwrap().as_deref(),
            Some("org.ex.C")
        );

        assert!(cfg.section::<remote::Group>("absent").is_none());
    }

    /// Returns a remote file `name` with the text `text`.
    fn remote_file(name: &str, text: &str) -> RemoteFile {
        RemoteFile {
            name: name.to_owned(),
            keyfile: KeyFile::parse(text).unwrap(),
        }
    }

    /// The config with the remote `origin` and the remote files `a.conf` and
    /// `b.conf` under the directory `/etc/r.d`.
    fn config_with_files() -> RepoConfig {
        let text = format!("{ARCHIVE_CONFIG}\n[remote \"origin\"]\nurl=https://o\n");
        RepoConfig::parse(&text)
            .unwrap()
            .with_remote_files(
                Path::new("/etc/r.d"),
                vec![
                    remote_file(
                        "a.conf",
                        "[remote \"z\"]\nurl=https://z\n\n[remote \"y\"]\nurl=https://y\n",
                    ),
                    remote_file("b.conf", "[remote \"x\"]\nurl=https://x\n"),
                ],
            )
            .unwrap()
    }

    #[test]
    fn remotes_list_config_first_then_each_file_in_group_order() {
        let cfg = config_with_files();
        assert_eq!(remote_names(&cfg), ["origin", "z", "y", "x"]);
        assert_eq!(
            cfg.section::<remote::Group>("y")
                .unwrap()
                .get::<remote::Url>()
                .unwrap()
                .as_deref(),
            Some("https://y")
        );
    }

    #[test]
    fn remote_source_is_config_or_the_file_name() {
        let cfg = config_with_files();
        assert_eq!(
            cfg.section::<remote::Group>("origin").unwrap().source(),
            RemoteSource::Config
        );
        assert_eq!(
            cfg.section::<remote::Group>("z").unwrap().source(),
            RemoteSource::File("a.conf")
        );
        assert_eq!(
            cfg.section::<remote::Group>("x").unwrap().source(),
            RemoteSource::File("b.conf")
        );
        assert!(cfg.section::<remote::Group>("absent").is_none());
    }

    #[test]
    fn section_and_resolve_find_a_remote_of_a_conf_file() {
        let cfg = config_with_files();
        let y = cfg.section::<remote::Group>("y").unwrap();
        assert_eq!(y.name(), "y");
        assert_eq!(y.source(), RemoteSource::File("a.conf"));
        assert_eq!(
            y.get::<remote::Url>().unwrap().as_deref(),
            Some("https://y")
        );
        let x = cfg
            .resolve(&GroupRef::<remote::Group>::new("x").unwrap())
            .unwrap();
        assert_eq!(x.source(), RemoteSource::File("b.conf"));
        assert_eq!(
            x.get::<remote::Url>().unwrap().as_deref(),
            Some("https://x")
        );
        let origin = cfg
            .resolve(&GroupRef::<remote::Group>::new("origin").unwrap())
            .unwrap();
        assert_eq!(origin.source(), RemoteSource::Config);
        let err = cfg
            .resolve(&GroupRef::<remote::Group>::new("absent").unwrap())
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the config has no [remote \"absent\"] group"
        );
        let sources: Vec<_> = cfg
            .sections::<remote::Group>()
            .map(|s| (s.name(), s.source()))
            .collect();
        assert_eq!(
            sources,
            [
                ("origin", RemoteSource::Config),
                ("z", RemoteSource::File("a.conf")),
                ("y", RemoteSource::File("a.conf")),
                ("x", RemoteSource::File("b.conf")),
            ]
        );
    }

    /// The `.conf` files give the sections of the remote group alone: a
    /// section of another named group in such a file is not a section.
    #[test]
    fn a_conf_file_gives_no_section_of_another_group() {
        crate::config_group! {
            pub group image = named "ex-image" {
                Arch: Option<String> = "arch";
            }
        }
        let cfg = RepoConfig::parse(&format!("{ARCHIVE_CONFIG}[ex-image \"c\"]\narch=amd64\n"))
            .unwrap()
            .with_remote_files(
                Path::new("r.d"),
                vec![remote_file(
                    "a.conf",
                    "[ex-image \"f\"]\narch=arm64\n\n[remote \"x\"]\nurl=https://x\n",
                )],
            )
            .unwrap();
        let names: Vec<_> = cfg.sections::<image::Group>().map(|s| s.name()).collect();
        assert_eq!(names, ["c"]);
        assert_eq!(
            cfg.section::<image::Group>("c")
                .unwrap()
                .get::<image::Arch>()
                .unwrap()
                .as_deref(),
            Some("amd64")
        );
        assert!(cfg.section::<image::Group>("f").is_none());
        assert!(
            cfg.resolve(&GroupRef::<image::Group>::new("f").unwrap())
                .is_err()
        );
        assert_eq!(remote_names(&cfg), ["x"]);
    }

    /// A remote group with an empty name or with a name that holds `"` is no
    /// remote section, in `config` and in a `.conf` file.
    #[test]
    fn a_remote_name_is_not_empty_and_holds_no_quote() {
        let cfg = RepoConfig::parse(&format!(
            "{ARCHIVE_CONFIG}[remote \"\"]\nurl=https://e\n\
             [remote \"a\" \"b\"]\nurl=https://q\n[remote \"c\"]\nurl=https://c\n"
        ))
        .unwrap()
        .with_remote_files(
            Path::new("r.d"),
            vec![remote_file(
                "a.conf",
                "[remote \"x\" \"y\"]\nurl=https://f\n\n[remote \"d\"]\nurl=https://d\n",
            )],
        )
        .unwrap();
        assert_eq!(remote_names(&cfg), ["c", "d"]);
        assert!(cfg.section::<remote::Group>("").is_none());
        assert!(cfg.section::<remote::Group>("a\" \"b").is_none());
        assert!(cfg.section::<remote::Group>("x\" \"y").is_none());
    }

    /// A trust section reads the keys that the trust group shares with a
    /// remote group, with the defaults of the trust group.
    #[test]
    fn a_trust_section_reads_the_shared_keys() {
        let cfg = RepoConfig::parse(&format!(
            "{ARCHIVE_CONFIG}[ex-ostrya trust \"t\"]\nsign-verify=ed25519\ngpgkeypath=/k.gpg\n\
             verification-ed25519-key=AAAA\n\
             [ex-ostrya trust \"g\"]\ngpg-verify=true\n"
        ))
        .unwrap();
        let t = cfg.section::<trust::Group>("t").unwrap();
        assert_eq!(t.name(), "t");
        assert_eq!(
            t.get::<trust::SignVerify>().unwrap(),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        assert_eq!(
            t.verification_key("ed25519").unwrap().as_deref(),
            Some("AAAA")
        );
        assert_eq!(t.verification_key("other").unwrap(), None);
        assert_eq!(t.raw_value::<trust::GpgKeyPath>(), Some("/k.gpg"));
        assert!(t.contains::<trust::GpgKeyPath>());
        assert!(!t.contains::<trust::VerificationSpkiKey>());
        assert_eq!(
            t.key_names().collect::<Vec<_>>(),
            ["sign-verify", "gpgkeypath", "verification-ed25519-key"]
        );
        // An absent `gpg-verify` is `false` in a trust group, and `true` in
        // a remote group.
        assert_eq!(t.file_value::<trust::GpgVerify>().unwrap(), None);
        assert!(!t.get::<trust::GpgVerify>().unwrap());
        let remote = RepoConfig::parse(&format!("{ARCHIVE_CONFIG}[remote \"o\"]\n")).unwrap();
        assert!(
            remote
                .section::<remote::Group>("o")
                .unwrap()
                .get::<remote::GpgVerify>()
                .unwrap()
        );
        let g = cfg.section::<trust::Group>("g").unwrap();
        assert_eq!(g.name(), "g");
        assert!(g.get::<trust::GpgVerify>().unwrap());
        assert!(g.get::<trust::GpgKeyPath>().unwrap().entries().is_empty());
        assert_eq!(g.get::<trust::SignVerify>().unwrap(), SignVerify::Off);
    }

    #[test]
    fn a_name_in_two_sources_is_refused() {
        let text = format!("{ARCHIVE_CONFIG}\n[remote \"origin\"]\nurl=https://o\n");
        let base = Path::new("/etc/r.d");
        let err = RepoConfig::parse(&text)
            .unwrap()
            .with_remote_files(
                base,
                vec![remote_file(
                    "o.conf",
                    "[remote \"origin\"]\nurl=https://f\n",
                )],
            )
            .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m)
                if m == "remote \"origin\" is defined in config and in /etc/r.d/o.conf"),
            "{err}"
        );
        let err = RepoConfig::parse(ARCHIVE_CONFIG)
            .unwrap()
            .with_remote_files(
                base,
                vec![
                    remote_file("a.conf", "[remote \"x\"]\nurl=https://a\n"),
                    remote_file("b.conf", "[remote \"x\"]\nurl=https://b\n"),
                ],
            )
            .unwrap_err();
        assert!(
            matches!(&err, Error::InvalidFormat(m)
                if m == "remote \"x\" is defined in /etc/r.d/a.conf and in /etc/r.d/b.conf"),
            "{err}"
        );
    }

    #[test]
    fn two_groups_of_one_name_in_one_file_give_one_remote() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG)
            .unwrap()
            .with_remote_files(
                Path::new("r.d"),
                vec![remote_file(
                    "a.conf",
                    "[remote \"x\"]\nurl=https://1\nbranches=main;\n\n\
                     [remote \"x\"]\nurl=https://2\n",
                )],
            )
            .unwrap();
        assert_eq!(remote_names(&cfg), ["x"]);
        let remote = cfg.section::<remote::Group>("x").unwrap();
        assert_eq!(
            remote.get::<remote::Url>().unwrap().as_deref(),
            Some("https://2")
        );
        assert_eq!(remote.key_names().collect::<Vec<_>>(), ["url", "branches"]);
    }

    #[test]
    fn a_file_skips_groups_that_are_not_remotes() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG)
            .unwrap()
            .with_remote_files(
                Path::new("r.d"),
                vec![remote_file(
                    "a.conf",
                    "[core]\nfsync=false\n\n[ex-ostrya]\nremotes-config-dir=x\n\n\
                     [remote \"x\"]\nurl=https://x\n",
                )],
            )
            .unwrap();
        assert_eq!(remote_names(&cfg), ["x"]);
        assert!(cfg.get::<repo::Fsync>().unwrap());
        assert!(!cfg.keyfile().has_group("ex-ostrya"));
    }

    #[test]
    fn from_keyfile_and_parse_have_no_remote_files() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert!(cfg.remote_files.is_empty());
        let cfg = RepoConfig::from_keyfile(KeyFile::parse(ARCHIVE_CONFIG).unwrap()).unwrap();
        assert!(cfg.remote_files.is_empty());
    }

    /// A config of `RepoConfig::parse` and of `RepoConfig::from_keyfile` has
    /// no override, also when its text comes from a config with overrides.
    #[test]
    fn from_keyfile_and_parse_have_no_override() {
        let mut overrides = Overrides::default();
        overrides.force::<repo::Fsync>(false);
        overrides.fallback::<repo::TmpExpirySecs>(5);
        let text = format!("{ARCHIVE_CONFIG}fsync=true\n");
        let held = RepoConfig::parse(&text)
            .unwrap()
            .with_overrides(Arc::new(overrides));
        assert_eq!(
            held.lookup::<repo::Fsync>().unwrap(),
            Some(Lookup::Forced(false))
        );
        assert_eq!(
            held.lookup::<repo::TmpExpirySecs>().unwrap(),
            Some(Lookup::Fallback(5))
        );
        for cfg in [
            RepoConfig::parse(&text).unwrap(),
            RepoConfig::from_keyfile(held.keyfile().clone()).unwrap(),
        ] {
            assert_eq!(
                cfg.lookup::<repo::Fsync>().unwrap(),
                Some(Lookup::File(true))
            );
            assert_eq!(
                cfg.lookup::<repo::TmpExpirySecs>().unwrap(),
                Some(Lookup::Default(86400))
            );
        }
    }

    /// The X.509 keys of the spki engine of a remote: the check refuses a CA
    /// file with no identity, and an intermediates file or an EKU with no
    /// anchor source. It checks the form of the EKU and of the identities.
    #[test]
    fn the_x509_keys_of_a_remote_need_an_anchor_source() {
        let check = |keys: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode=archive-z2\n[remote \"o\"]\nurl=x\n{keys}"
            ))
            .unwrap()
            .check()
            .map_err(|e| e.to_string())
        };
        for keys in [
            "verification-spki-identity=*\n",
            "verification-spki-ca-file=ca.pem\nverification-spki-identity=dns:a.example\n",
            "verification-spki-identity=uri:x\nverification-spki-eku=1.3.6.1.5.5.7.3.1\n\
             verification-spki-intermediates-file=i.pem\n",
            "verification-spki-identity=*\nverification-spki-crl-file=crl.pem\n\
             verification-spki-revocation=required\n",
            "verification-spki-identity=*\nverification-spki-revocation=best-effort\n",
        ] {
            assert_eq!(check(keys), Ok(()), "{keys}");
        }
        for (keys, text) in [
            (
                "verification-spki-ca-file=ca.pem\n",
                "invalid format: [remote \"o\"] holds 'verification-spki-ca-file', and no \
                 verification-spki-identity: an anchor needs an identity",
            ),
            (
                "verification-spki-eku=1.3.6.1.5.5.7.3.3\n",
                "invalid format: [remote \"o\"] holds 'verification-spki-eku', and no anchor \
                 source: set verification-spki-ca-file or verification-spki-identity",
            ),
            (
                "verification-spki-intermediates-file=i.pem\n",
                "invalid format: [remote \"o\"] holds 'verification-spki-intermediates-file', \
                 and no anchor source: set verification-spki-ca-file or \
                 verification-spki-identity",
            ),
            (
                "verification-spki-identity=*\nverification-spki-eku=codeSigning\n",
                "invalid format: malformed [remote \"o\"] verification-spki-eku value \
                 'codeSigning': the value is an OID in dotted form, for example \
                 1.3.6.1.5.5.7.3.3",
            ),
            (
                "verification-spki-crl-file=crl.pem\n",
                "invalid format: [remote \"o\"] holds 'verification-spki-crl-file', and no \
                 anchor source: set verification-spki-ca-file or verification-spki-identity",
            ),
            (
                "verification-spki-revocation=required\n",
                "invalid format: [remote \"o\"] holds 'verification-spki-revocation', and no \
                 anchor source: set verification-spki-ca-file or verification-spki-identity",
            ),
            (
                "verification-spki-identity=*\nverification-spki-revocation=strict\n",
                "invalid format: malformed [remote \"o\"] verification-spki-revocation value \
                 'strict': the value is best-effort or required",
            ),
            (
                "verification-spki-identity=*;dns:a\n",
                "invalid format: malformed [remote \"o\"] verification-spki-identity item '*': \
                 * is valid as the only identity",
            ),
            (
                "verification-spki-identity=host.example\n",
                "invalid format: malformed [remote \"o\"] verification-spki-identity item \
                 'host.example': an identity is uri:VALUE, email:VALUE, dns:VALUE, or *",
            ),
        ] {
            assert_eq!(check(keys), Err(text.to_owned()), "{keys}");
        }
    }

    /// The verification keys a pull reads its policy from: the two sign-api
    /// switches, the per-engine key sources, and the GPG keyring list.
    #[test]
    fn reads_remote_verification_keys() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"signed\"]\nurl=https://ex.com/r\nsign-verify=ed25519\n\
                    sign-verify-summary=true\nverification-ed25519-key=AAAA\n\
                    verification-ed25519-file=/etc/keys.ed25519\n\
                    gpgkeypath=/etc/one.gpg;/etc/keys.d\n";
        let cfg = RepoConfig::parse(text).unwrap();
        let remote = cfg.section::<remote::Group>("signed").unwrap();
        assert_eq!(
            remote.get::<remote::SignVerify>().unwrap(),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        assert_eq!(
            remote.get::<remote::SignVerifySummary>().unwrap(),
            SignVerify::All
        );
        assert_eq!(
            remote.verification_key("ed25519").unwrap().as_deref(),
            Some("AAAA")
        );
        assert_eq!(
            remote.verification_file("ed25519").unwrap(),
            Some(KeyPath {
                value: PathBuf::from("/etc/keys.ed25519"),
                origin: KeyOrigin::Config,
            })
        );
        assert_eq!(remote.verification_key("spki").unwrap(), None);
        assert_eq!(
            remote.get::<remote::GpgKeyPath>().unwrap().entries(),
            ["/etc/one.gpg", "/etc/keys.d"]
        );

        // The defaults: no sign-api verification and no extra keyring.
        let plain = cfg.section::<remote::Group>("signed").unwrap();
        assert!(plain.get::<remote::GpgVerify>().unwrap());
        let bare = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=bare\n\n[remote \"plain\"]\nurl=http://ex/r\n",
        )
        .unwrap();
        let bare = bare.section::<remote::Group>("plain").unwrap();
        assert_eq!(bare.get::<remote::SignVerify>().unwrap(), SignVerify::Off);
        assert_eq!(
            bare.get::<remote::SignVerifySummary>().unwrap(),
            SignVerify::Off
        );
        assert!(
            bare.get::<remote::GpgKeyPath>()
                .unwrap()
                .entries()
                .is_empty()
        );
    }

    /// `gpgkeypath` is the raw value split on `;`: no escape is decoded, one
    /// empty entry at the end is removed, and each other empty entry stays.
    #[test]
    fn gpgkeypath_splits_the_raw_value() {
        let cases: &[(&str, &[&str])] = &[
            (r"k\sspace.gpg", &[r"k\sspace.gpg"]),
            (r"\q", &[r"\q"]),
            ("", &[""]),
            (";", &[""]),
            (";a", &["", "a"]),
            ("a;;b", &["a", "", "b"]),
            ("a;", &["a"]),
            ("a;;", &["a", ""]),
            ("a;b", &["a", "b"]),
        ];
        for (value, want) in cases {
            let text = format!(
                "[core]\nrepo_version=1\nmode=bare\n\n\
                 [remote \"r\"]\nurl=http://ex/r\ngpgkeypath={value}\n"
            );
            let cfg = RepoConfig::parse(&text).unwrap();
            assert_eq!(
                cfg.section::<remote::Group>("r")
                    .unwrap()
                    .get::<remote::GpgKeyPath>()
                    .unwrap()
                    .entries(),
                *want,
                "gpgkeypath={value}"
            );
        }
    }

    /// The TLS keys from which a pull fills the options of its fetcher.
    #[test]
    fn reads_remote_tls_keys() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"secure\"]\nurl=https://ex.com/r\ntls-ca-path=/etc/ca.pem\n\
                    tls-client-cert-path=/etc/client.pem\ntls-client-key-path=/etc/client.key\n\
                    tls-permissive=true\n";
        let cfg = RepoConfig::parse(text).unwrap();
        let remote = cfg.section::<remote::Group>("secure").unwrap();
        assert_eq!(
            remote
                .get::<remote::TlsCaPath>()
                .unwrap()
                .as_ref()
                .map(ConfigPath::as_str),
            Some("/etc/ca.pem")
        );
        assert_eq!(
            remote
                .get::<remote::TlsClientCertPath>()
                .unwrap()
                .as_ref()
                .map(ConfigPath::as_str),
            Some("/etc/client.pem")
        );
        assert_eq!(
            remote
                .get::<remote::TlsClientKeyPath>()
                .unwrap()
                .as_ref()
                .map(ConfigPath::as_str),
            Some("/etc/client.key")
        );
        assert!(remote.get::<remote::TlsPermissive>().unwrap());
    }

    /// The `proxy` key of a remote section, read as written.
    ///
    /// The value keeps its trailing spaces, and the read decodes its escapes.
    /// It is empty when the value is empty or spaces, and absent when the
    /// section does not set it.
    #[test]
    fn reads_remote_proxy_key() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"set\"]\nurl=http://ex.com/r\n\
                    proxy=http://user:pw@proxy.ex.com:3128\n\n\
                    [remote \"empty\"]\nurl=http://ex.com/r\nproxy=\n\n\
                    [remote \"blank\"]\nurl=http://ex.com/r\nproxy=  \n\n\
                    [remote \"trail\"]\nurl=http://ex.com/r\nproxy=http://p:1  \n\n\
                    [remote \"escape\"]\nurl=http://ex.com/r\nproxy=\\s\n\n\
                    [remote \"plain\"]\nurl=http://ex.com/r\n";
        let cfg = RepoConfig::parse(text).unwrap();
        assert_eq!(
            cfg.section::<remote::Group>("set")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap()
                .as_deref(),
            Some("http://user:pw@proxy.ex.com:3128")
        );
        assert_eq!(
            cfg.section::<remote::Group>("empty")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap()
                .as_deref(),
            Some("")
        );
        assert_eq!(
            cfg.section::<remote::Group>("blank")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap()
                .as_deref(),
            Some("")
        );
        assert_eq!(
            cfg.section::<remote::Group>("trail")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap()
                .as_deref(),
            Some("http://p:1  ")
        );
        assert_eq!(
            cfg.section::<remote::Group>("escape")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap()
                .as_deref(),
            Some(" ")
        );
        assert_eq!(
            cfg.section::<remote::Group>("plain")
                .unwrap()
                .get::<remote::Proxy>()
                .unwrap(),
            None
        );
    }

    /// The push keys and the pull keys of ostrya in a remote section. Each key
    /// is read as written, and is absent when the section does not set it.
    #[test]
    fn reads_remote_push_keys() {
        let text = "[core]\nrepo_version=1\nmode=archive-z2\n\n\
                    [remote \"central\"]\nurl=https://ex.com/r\n\
                    push-url=ssh://pusher@ex.com/srv/repo\n\
                    ssh-command=ssh -o BatchMode=yes\n\
                    receive-command=/opt/bin/ostrya receive\n\
                    push-token-file=/etc/push token\n\
                    push-user=alice\n\
                    pull-url=puller@ex.com:srv/repo\n\
                    send-command=/opt/bin/ostrya send -v\n\n\
                    [remote \"plain\"]\nurl=https://ex.com/r\n";
        let cfg = RepoConfig::parse(text).unwrap();
        let remote = cfg.section::<remote::Group>("central").unwrap();
        assert_eq!(
            remote.get::<remote::PushUrl>().unwrap().as_deref(),
            Some("ssh://pusher@ex.com/srv/repo")
        );
        assert_eq!(
            remote.get::<remote::SshCommand>().unwrap().as_deref(),
            Some("ssh -o BatchMode=yes")
        );
        assert_eq!(
            remote.get::<remote::ReceiveCommand>().unwrap().as_deref(),
            Some("/opt/bin/ostrya receive")
        );
        assert_eq!(
            remote
                .get::<remote::PushTokenFile>()
                .unwrap()
                .as_ref()
                .map(ConfigPath::as_str),
            Some("/etc/push token")
        );
        assert_eq!(
            remote.get::<remote::PushUser>().unwrap().as_deref(),
            Some("alice")
        );
        assert_eq!(
            remote.get::<remote::PullUrl>().unwrap().as_deref(),
            Some("puller@ex.com:srv/repo")
        );
        assert_eq!(
            remote.get::<remote::SendCommand>().unwrap().as_deref(),
            Some("/opt/bin/ostrya send -v")
        );

        let plain = cfg.section::<remote::Group>("plain").unwrap();
        assert_eq!(plain.get::<remote::PushUrl>().unwrap(), None);
        assert_eq!(plain.get::<remote::SshCommand>().unwrap(), None);
        assert_eq!(plain.get::<remote::ReceiveCommand>().unwrap(), None);
        assert_eq!(plain.get::<remote::PushTokenFile>().unwrap(), None);
        assert_eq!(plain.get::<remote::PushUser>().unwrap(), None);
        assert_eq!(plain.get::<remote::PullUrl>().unwrap(), None);
        assert_eq!(plain.get::<remote::SendCommand>().unwrap(), None);
    }

    /// The key keeps the order of its ids and drops a repeated id. It needs
    /// no `collection-id`, and refuses an empty list, an empty id, an id that
    /// fails the rule, and the `collection-id` of the remote.
    #[test]
    fn mirrored_collection_ids_reads_the_checked_ids() {
        let ids = |keys: &str| {
            let text = format!("[core]\nrepo_version=1\nmode=archive-z2\n\n[remote \"r\"]\n{keys}");
            RepoConfig::parse(&text)
                .unwrap()
                .section::<remote::Group>("r")
                .unwrap()
                .mirrored_collection_ids()
        };
        assert_eq!(ids("url=https://ex.com/r\n").unwrap(), Vec::<String>::new());
        assert_eq!(
            ids("mirrored-collection-ids=org.ex.B;org.ex.A;org.ex.B;\n").unwrap(),
            ["org.ex.B", "org.ex.A"]
        );
        assert_eq!(
            ids("collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A\n").unwrap(),
            ["org.ex.A"]
        );
        let key = "[remote \"r\"] mirrored-collection-ids";
        for (keys, reason) in [
            ("mirrored-collection-ids=\n", "holds no collection id"),
            (
                "mirrored-collection-ids=;\n",
                "holds the invalid collection id ''",
            ),
            (
                "mirrored-collection-ids=org.ex.A;;org.ex.B\n",
                "holds the invalid collection id ''",
            ),
            (
                "mirrored-collection-ids=org/ex\n",
                "holds the invalid collection id 'org/ex'",
            ),
            (
                "mirrored-collection-ids=1org.ex\n",
                "holds the invalid collection id '1org.ex'",
            ),
            (
                "collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A;org.ex.C\n",
                "holds 'org.ex.C', the collection-id of the remote",
            ),
            // The list is parsed before `collection-id` is read.
            (
                "collection-id=\\q\nmirrored-collection-ids=org/ex\n",
                "holds the invalid collection id 'org/ex'",
            ),
        ] {
            assert!(
                matches!(ids(keys), Err(Error::InvalidFormat(m)) if m == format!("{key} {reason}")),
                "{keys:?}: {:?}",
                ids(keys)
            );
        }
    }

    /// Reads the file that `path` names from the base of
    /// [`KeyPath::locate`] with `repo`, and gives its text and the path of a
    /// message.
    fn read_located(path: &KeyPath, repo: Option<&Repo>) -> (String, PathBuf) {
        use std::io::Read as _;

        let (base, at, shown) = path.locate(repo);
        let fd = crate::repo_fs::open_named(base, &at, crate::repo_fs::Named::File).unwrap();
        let mut text = String::new();
        std::fs::File::from(fd).read_to_string(&mut text).unwrap();
        (text, shown)
    }

    /// A relative path of a key in `config` resolves against the repository
    /// root, and a relative path of a key in a `.conf` file against the
    /// remotes directory, for each form of the directory. No relative path
    /// resolves against the working directory. An absolute path with a `..`
    /// component opens, and a relative path with a `..` component is
    /// refused at the read of the key.
    #[test]
    fn a_relative_key_path_resolves_against_the_base_of_its_source() {
        use std::sync::Arc;

        use crate::repo::RemotesDir;
        use crate::repo_fs::TestDir;
        use crate::{CreateOptions, OpenOptions};

        let dir = TestDir::new("key-path");
        let root = dir.path().join("repo");
        let remotes = dir.path().join("remotes.d");
        let conf = "[remote \"o\"]\nurl=http://h/\ntls-ca-path=k.pem\n";
        let repo = ostrya_rt::block_on(async {
            Repo::create(&root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap()
        });
        drop(repo);
        let mut text = std::fs::read_to_string(root.join("config")).unwrap();
        text.push_str(&format!(
            "[remote \"c\"]\nurl=http://h/\ntls-ca-path=k.pem\n\
             [remote \"a\"]\nurl=http://h/\ntls-ca-path={}\n\
             [remote \"p\"]\nurl=http://h/\ntls-ca-path=../k.pem\n",
            root.join("in.d/../k.pem").display()
        ));
        std::fs::write(root.join("config"), text).unwrap();
        std::fs::create_dir(root.join("in.d")).unwrap();
        std::fs::create_dir(&remotes).unwrap();
        std::fs::write(root.join("k.pem"), "root").unwrap();
        std::fs::write(root.join("in.d/k.pem"), "in-repo").unwrap();
        std::fs::write(root.join("in.d/o.conf"), conf).unwrap();
        std::fs::write(remotes.join("k.pem"), "path").unwrap();
        std::fs::write(remotes.join("o.conf"), conf).unwrap();
        let open = |dir: RemotesDir| {
            ostrya_rt::block_on(OpenOptions::new().remotes_dir(dir).open(&root)).unwrap()
        };
        let fd = rustix::fs::open(
            &remotes,
            rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
            rustix::fs::Mode::empty(),
        )
        .unwrap();
        let cases = [
            (RemotesDir::path(&remotes), "path", remotes.join("k.pem")),
            (
                RemotesDir::InRepo("in.d".into()),
                "in-repo",
                PathBuf::from("in.d/k.pem"),
            ),
            (RemotesDir::Fd(Arc::new(fd)), "path", PathBuf::from("k.pem")),
        ];
        for (remotes_dir, text, shown) in cases {
            let repo = open(remotes_dir);
            let path = repo
                .config()
                .section::<remote::Group>("o")
                .unwrap()
                .key_path::<remote::TlsCaPath>()
                .unwrap()
                .unwrap();
            assert_eq!(path.origin, KeyOrigin::RemotesFile);
            assert_eq!(read_located(&path, Some(&repo)), (text.to_owned(), shown));
            let path = repo
                .config()
                .section::<remote::Group>("c")
                .unwrap()
                .key_path::<remote::TlsCaPath>()
                .unwrap()
                .unwrap();
            assert_eq!(path.origin, KeyOrigin::Config);
            assert_eq!(
                read_located(&path, Some(&repo)),
                ("root".to_owned(), PathBuf::from("k.pem"))
            );
        }
        let repo = open(RemotesDir::path(&remotes));
        let absolute = repo.config().section::<remote::Group>("a").unwrap();
        let path = absolute.key_path::<remote::TlsCaPath>().unwrap().unwrap();
        assert_eq!(read_located(&path, Some(&repo)).0, "root");
        let caller = KeyPath::caller(root.join("in.d/k.pem"));
        assert_eq!(read_located(&caller, Some(&repo)).0, "in-repo");
        let parent = repo.config().section::<remote::Group>("p").unwrap();
        for result in [
            parent.get::<remote::TlsCaPath>().map_err(Error::from),
            parent.key_path::<remote::TlsCaPath>().map(|_| None),
        ] {
            assert!(
                matches!(&result, Err(Error::InvalidFormat(m)) if m == "[remote \"p\"] tls-ca-path \
                    ../k.pem has a `..` component, which a relative path in a config cannot have"),
                "{result:?}"
            );
        }
    }

    /// Creates a repository at `root`. Its `config` ends with `sections`, and
    /// its remotes directory `remotes.d` holds the file `o.conf` with the
    /// text `conf`. Returns a handle of the repository for each form of the
    /// remotes directory: a path, a path relative to the repository, and a
    /// descriptor.
    pub(crate) fn repos_with_remotes_file(root: &Path, sections: &str, conf: &str) -> Vec<Repo> {
        use crate::repo::RemotesDir;
        use crate::{CreateOptions, OpenOptions};

        ostrya_rt::block_on(async {
            Repo::create(root, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
        });
        let mut text = std::fs::read_to_string(root.join("config")).unwrap();
        text.push_str(sections);
        std::fs::write(root.join("config"), text).unwrap();
        let remotes = root.join("remotes.d");
        std::fs::create_dir(&remotes).unwrap();
        std::fs::write(remotes.join("o.conf"), conf).unwrap();
        let fd = std::os::fd::OwnedFd::from(std::fs::File::open(&remotes).unwrap());
        [
            RemotesDir::path(&remotes),
            RemotesDir::InRepo(PathBuf::from("remotes.d")),
            RemotesDir::from(fd),
        ]
        .into_iter()
        .map(|dir| ostrya_rt::block_on(OpenOptions::new().remotes_dir(dir).open(root)).unwrap())
        .collect()
    }
}

#[cfg(test)]
mod typed_key_tests {
    use std::fmt::Debug;

    use super::*;
    use crate::config::{OutputOf, ValueOf};

    const BASE: &str = "[core]\nrepo_version=1\nmode=bare\n";

    /// Returns the config of `BASE` with the line `line` in the group
    /// `group`. A second `[core]` header merges into the first.
    fn config_with(group: &str, line: &str) -> RepoConfig {
        let text = if line.is_empty() {
            BASE.to_owned()
        } else {
            format!("{BASE}[{group}]\n{line}\n")
        };
        RepoConfig::parse(&text).unwrap()
    }

    /// Checks the reads of the key `K` with the raw value `raw`, which parses
    /// to `want`, and with the key absent, which gives `default`.
    fn check_key<K>(raw: &str, want: ValueOf<K>, default: Option<ValueOf<K>>)
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
        ValueOf<K>: Value + PartialEq + Debug + Clone,
        OutputOf<K>: PartialEq + Debug,
    {
        let group = <<K as SingleKey>::Group as Group>::NAME;
        let name = <K as Key<<K as SingleKey>::Group>>::NAME;
        let set = config_with(group, &format!("{name}={raw}"));
        assert_eq!(set.file_value::<K>().unwrap(), Some(want.clone()), "{name}");
        assert_eq!(
            set.lookup::<K>().unwrap(),
            Some(Lookup::File(want.clone())),
            "{name}"
        );
        assert_eq!(
            set.get::<K>().unwrap(),
            K::output(Some(want.clone())).unwrap(),
            "{name}"
        );
        assert_eq!(ValueOf::<K>::parse(&want.format()), Ok(want), "{name}");

        let absent = config_with(group, "");
        assert_eq!(absent.file_value::<K>().unwrap(), None, "{name}");
        assert_eq!(K::default_value(), default, "{name}");
        assert_eq!(
            absent.lookup::<K>().unwrap(),
            default.clone().map(Lookup::Default),
            "{name}"
        );
        if let Some(default) = default {
            assert_eq!(
                absent.get::<K>().unwrap(),
                K::output(Some(default.clone())).unwrap(),
                "{name}"
            );
            assert_eq!(
                ValueOf::<K>::parse(&default.format()),
                Ok(default),
                "{name}"
            );
        }
    }

    /// Checks the reads of the key `K` of a remote section with the raw value
    /// `raw`, which parses to `want`, and with the key absent, which gives
    /// `default`.
    fn check_remote_key<K>(raw: &str, want: K::Value, default: Option<K::Value>)
    where
        K: Key<remote::Group>,
        K::Value: Value + PartialEq + Debug + Clone,
        K::Output: PartialEq + Debug,
    {
        let name = K::NAME;
        let set = RepoConfig::parse(&format!("{BASE}[remote \"r\"]\n{name}={raw}\n")).unwrap();
        let section = set.section::<remote::Group>("r").unwrap();
        assert_eq!(
            section.file_value::<K>().unwrap(),
            Some(want.clone()),
            "{name}"
        );
        assert_eq!(
            section.lookup::<K>().unwrap(),
            Some(Lookup::File(want.clone())),
            "{name}"
        );
        assert_eq!(
            section.get::<K>().unwrap(),
            K::output(Some(want.clone())).unwrap(),
            "{name}"
        );
        assert_eq!(K::Value::parse(&want.format()), Ok(want), "{name}");

        let absent = RepoConfig::parse(&format!("{BASE}[remote \"r\"]\nother=1\n")).unwrap();
        let section = absent.section::<remote::Group>("r").unwrap();
        assert_eq!(section.file_value::<K>().unwrap(), None, "{name}");
        assert_eq!(K::default_value(), default, "{name}");
        assert_eq!(
            section.lookup::<K>().unwrap(),
            default.clone().map(Lookup::Default),
            "{name}"
        );
        assert_eq!(
            section.get::<K>().unwrap(),
            K::output(default).unwrap(),
            "{name}"
        );
    }

    #[test]
    fn the_groups_list_their_keys_in_order() {
        assert_eq!(<repo::Group as Group>::NAME, "core");
        assert_eq!(
            <repo::Group as Group>::KEYS,
            [
                "repo_version",
                "mode",
                "collection-id",
                "fsync",
                "per-object-fsync",
                "locking",
                "lock-timeout-secs",
                "tmp-expiry-secs",
                "tombstone-commits",
                "indexed-deltas",
                "disable-xattrs",
                "default-repo-finders",
                "min-free-space-size",
                "min-free-space-percent",
                "auto-update-summary",
                "add-remotes-config-dir",
            ]
        );
        assert_eq!(<archive::Group as Group>::NAME, "archive");
        assert_eq!(<archive::Group as Group>::KEYS, ["zlib-level"]);
        assert_eq!(<ex_integrity::Group as Group>::NAME, "ex-integrity");
        assert_eq!(
            <ex_integrity::Group as Group>::KEYS,
            ["composefs", "fsverity"]
        );
        assert_eq!(<ex_ostrya::Group as Group>::NAME, "ex-ostrya");
        assert_eq!(
            <ex_ostrya::Group as Group>::KEYS,
            [
                "keep-detached-related",
                "gc-weak-references",
                "remotes-config-dir"
            ]
        );
        assert_eq!(<server::Group as Group>::NAME, "ex-ostrya server");
        assert_eq!(
            <server::Group as Group>::KEYS,
            [
                "listen",
                "tls-cert",
                "tls-key",
                "tls-client-ca",
                "trusted-proxy",
                "trusted-proxy-header",
                "trusted-proxy-client-cert",
                "proxy-protocol",
                "allow-cleartext-credentials",
                "session-timeout",
                "max-sessions",
                "parallel-uploads",
                "body-timeout",
                "sign-summary",
            ]
        );
        const { assert!(!<server::Group as Group>::NAMED) };
        const { assert!(<server::Group as Group>::CLOSED) };
        assert!(<server::Group as Group>::OVERRIDABLE.is_empty());
        assert_eq!(
            <server::Group as Group>::SETTABLE,
            <server::Group as Group>::KEYS
        );
        assert_eq!(<remote::Group as Group>::NAME, "remote");
        assert_eq!(
            <remote::Group as Group>::KEYS,
            [
                "url",
                "contenturl",
                "metalink",
                "branches",
                "collection-id",
                "mirrored-collection-ids",
                "gpg-verify",
                "gpg-verify-summary",
                "gpgkeypath",
                "sign-verify",
                "sign-verify-summary",
                "verification-ed25519-key",
                "verification-ed25519-file",
                "verification-spki-key",
                "verification-spki-file",
                "verification-spki-ca-file",
                "verification-spki-intermediates-file",
                "verification-spki-eku",
                "verification-spki-identity",
                "verification-spki-crl-file",
                "verification-spki-revocation",
                "trust",
                "tls-ca-path",
                "tls-client-cert-path",
                "tls-client-key-path",
                "tls-permissive",
                "proxy",
                "push-url",
                "pull-url",
                "push-branches",
                "pull-branches",
                "ssh-command",
                "receive-command",
                "send-command",
                "push-token-file",
                "push-user",
                "s3-region",
                "s3-endpoint",
                "s3-addressing",
                "s3-profile",
            ]
        );
        const { assert!(<remote::Group as Group>::NAMED) };
        const { assert!(!<remote::Group as Group>::CLOSED) };
        assert!(<remote::Group as Group>::OVERRIDABLE.is_empty());
        assert!(<remote::Group as Group>::SETTABLE.is_empty());
        for (named, closed) in [
            (
                <repo::Group as Group>::NAMED,
                <repo::Group as Group>::CLOSED,
            ),
            (
                <archive::Group as Group>::NAMED,
                <archive::Group as Group>::CLOSED,
            ),
            (
                <ex_integrity::Group as Group>::NAMED,
                <ex_integrity::Group as Group>::CLOSED,
            ),
            (
                <ex_ostrya::Group as Group>::NAMED,
                <ex_ostrya::Group as Group>::CLOSED,
            ),
        ] {
            assert!(!named);
            assert!(!closed);
        }
    }

    #[test]
    fn each_key_parses_defaults_and_formats() {
        let text = |items: &[&str]| items.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
        check_key::<repo::CollectionId>(
            "org.ex.C",
            CollectionIdValue::try_from("org.ex.C").unwrap(),
            None,
        );
        check_key::<repo::Fsync>("false", false, Some(true));
        check_key::<repo::PerObjectFsync>("1", true, Some(false));
        check_key::<repo::Locking>("0", false, Some(true));
        check_key::<repo::LockTimeoutSecs>(
            "-1",
            LockTimeout::try_from(-1).unwrap(),
            Some(LockTimeout::try_from(300).unwrap()),
        );
        check_key::<repo::TmpExpirySecs>("60", 60, Some(86400));
        check_key::<repo::TombstoneCommits>("true", true, Some(false));
        check_key::<repo::IndexedDeltas>("false", false, Some(true));
        check_key::<repo::DisableXattrs>("true", true, Some(false));
        check_key::<repo::DefaultRepoFinders>(
            "lan;config;",
            text(&["lan", "config"]),
            Some(text(&["config", "mount"])),
        );
        check_key::<repo::MinFreeSpaceSize>(
            "2GB",
            SizeSpec {
                value: 2,
                unit: SizeUnit::Giga,
            },
            None,
        );
        check_key::<repo::MinFreeSpacePercent>(
            "100",
            FreeSpacePercent::try_from(100).unwrap(),
            Some(FreeSpacePercent::try_from(3).unwrap()),
        );
        check_key::<repo::AutoUpdateSummary>("true", true, Some(false));
        check_key::<repo::AddRemotesConfigDir>("true", true, Some(false));
        check_key::<archive::ZlibLevel>("9", 9, Some(6));
        check_key::<ex_integrity::Composefs>("maybe", Tristate::Maybe, Some(Tristate::No));
        check_key::<ex_integrity::Fsverity>("yes", Tristate::Yes, None);
        check_key::<ex_ostrya::KeepDetachedRelated>("false", false, Some(true));
        check_key::<ex_ostrya::GcWeakReferences>(
            "tmp/**;!tmp/keep",
            ReceiveSelector::parse(["tmp/**", "!tmp/keep"]).unwrap(),
            None,
        );
        check_key::<ex_ostrya::RemotesConfigDir>(
            "/etc/r.d",
            RemotesConfigPath::try_from("/etc/r.d").unwrap(),
            None,
        );
        check_key::<server::Listen>(
            "127.0.0.1:80;[::1]:81",
            ListenAddrs::try_from(vec![
                "127.0.0.1:80".parse().unwrap(),
                "[::1]:81".parse().unwrap(),
            ])
            .unwrap(),
            None,
        );
        let pem = |p: &str| PemPath::try_from(p).unwrap();
        check_key::<server::TlsCert>(r"c\s.pem", pem("c .pem"), None);
        check_key::<server::TlsKey>("/k.pem", pem("/k.pem"), None);
        check_key::<server::TlsClientCa>("ca.pem", pem("ca.pem"), None);
        check_key::<server::TrustedProxy>(
            "10.0.0.0/8",
            TrustedNets::try_from(vec![crate::access::IpNet::parse("10.0.0.0/8").unwrap()])
                .unwrap(),
            None,
        );
        check_key::<server::TrustedProxyHeader>(
            "x-real-ip",
            crate::access::ForwardedHeader::XRealIp,
            None,
        );
        check_key::<server::TrustedProxyClientCert>(
            "X-Cert",
            HeaderName::try_from("X-Cert").unwrap(),
            None,
        );
        check_key::<server::ProxyProtocol>("1", true, None);
        check_key::<server::AllowCleartextCredentials>("false", false, None);
        let positive = |n: i64| PositiveInt::try_from(n).unwrap();
        check_key::<server::SessionTimeout>("600", positive(600), None);
        check_key::<server::MaxSessions>("9223372036854775807", positive(i64::MAX), None);
        check_key::<server::ParallelUploads>("31", UploadStreams::try_from(31).unwrap(), None);
        check_key::<server::BodyTimeout>("1", positive(1), None);
        check_key::<server::SignSummary>(
            "b;a;b",
            KeyGroupNames::try_from(text(&["b", "a"])).unwrap(),
            None,
        );

        let path = |p: &str| ConfigPath::try_from(p).unwrap();
        let text_of = |v: &str| v.to_owned();
        check_remote_key::<remote::Url>("https://h/r", text_of("https://h/r"), None);
        check_remote_key::<remote::ContentUrl>(r"https://h/\sc", text_of("https://h/ c"), None);
        check_remote_key::<remote::Metalink>("https://h/m", text_of("https://h/m"), None);
        check_remote_key::<remote::Branches>("a;b;", text(&["a", "b"]), None);
        check_remote_key::<remote::CollectionId>("org.ex.C", text_of("org.ex.C"), None);
        check_remote_key::<remote::MirroredCollectionIds>(
            "org.ex.A;org.ex.B;org.ex.A",
            CollectionIdList::try_from(text(&["org.ex.A", "org.ex.B"])).unwrap(),
            None,
        );
        check_remote_key::<remote::GpgVerify>("false", false, Some(true));
        check_remote_key::<remote::GpgVerifySummary>("1", true, Some(false));
        check_remote_key::<remote::GpgKeyPath>(
            r"/a.gpg;k\s.gpg;",
            KeyringPaths::parse(r"/a.gpg;k\s.gpg").unwrap(),
            Some(KeyringPaths::default()),
        );
        check_remote_key::<remote::SignVerify>(
            "ed25519",
            SignVerify::Engines(text(&["ed25519"])),
            Some(SignVerify::Off),
        );
        check_remote_key::<remote::SignVerifySummary>(
            "true",
            SignVerify::All,
            Some(SignVerify::Off),
        );
        check_remote_key::<remote::VerificationEd25519Key>("AAAA", text_of("AAAA"), None);
        check_remote_key::<remote::VerificationEd25519File>("/k", path("/k"), None);
        check_remote_key::<remote::VerificationSpkiKey>("BBBB", text_of("BBBB"), None);
        check_remote_key::<remote::VerificationSpkiFile>("k.pem", path("k.pem"), None);
        check_remote_key::<remote::Trust>("t", TrustGroupName::try_from("t").unwrap(), None);
        check_remote_key::<remote::TlsCaPath>("/ca.pem", path("/ca.pem"), None);
        check_remote_key::<remote::TlsClientCertPath>(r"c\s.pem", path("c .pem"), None);
        check_remote_key::<remote::TlsClientKeyPath>("", path(""), None);
        check_remote_key::<remote::TlsPermissive>("true", true, Some(false));
        check_remote_key::<remote::Proxy>("http://p:1  ", text_of("http://p:1  "), None);
        check_remote_key::<remote::PushUrl>("ssh://h/p", text_of("ssh://h/p"), None);
        check_remote_key::<remote::PullUrl>("s3://b/p", text_of("s3://b/p"), None);
        check_remote_key::<remote::PushBranches>(
            "apps/**;!apps/b",
            ReceiveSelector::parse(["apps/**", "!apps/b"]).unwrap(),
            None,
        );
        check_remote_key::<remote::PullBranches>(
            "",
            ReceiveSelector::parse(std::iter::empty::<&str>()).unwrap(),
            None,
        );
        check_remote_key::<remote::SshCommand>("ssh -v", text_of("ssh -v"), None);
        check_remote_key::<remote::ReceiveCommand>("r", text_of("r"), None);
        check_remote_key::<remote::SendCommand>("s", text_of("s"), None);
        check_remote_key::<remote::PushTokenFile>("t.txt", path("t.txt"), None);
        check_remote_key::<remote::PushUser>("alice", text_of("alice"), None);
        check_remote_key::<remote::S3Region>("eu-1", text_of("eu-1"), None);
        check_remote_key::<remote::S3Endpoint>("https://s3", text_of("https://s3"), None);
        check_remote_key::<remote::S3Addressing>("path", text_of("path"), None);
        check_remote_key::<remote::S3Profile>("p", text_of("p"), None);

        // The required keys of `[core]` are in each config.
        let cfg = RepoConfig::parse(BASE).unwrap();
        assert_eq!(cfg.get::<repo::RepoVersion>().unwrap(), 1);
        assert_eq!(cfg.get::<repo::Mode>().unwrap(), RepoMode::Bare);
        assert_eq!(
            cfg.lookup::<repo::Mode>().unwrap(),
            Some(Lookup::File(RepoMode::Bare))
        );
        assert_eq!(
            <repo::RepoVersion as Key<repo::Group>>::default_value(),
            None
        );
        assert_eq!(<repo::Mode as Key<repo::Group>>::default_value(), None);
    }

    #[test]
    fn the_marker_traits_follow_the_key_table() {
        fn ov<K: Overridable>() {}
        fn st<K: Settable>() {}
        ov::<repo::Fsync>();
        ov::<repo::PerObjectFsync>();
        ov::<repo::LockTimeoutSecs>();
        ov::<repo::TmpExpirySecs>();
        ov::<repo::TombstoneCommits>();
        ov::<repo::IndexedDeltas>();
        ov::<repo::DefaultRepoFinders>();
        ov::<repo::MinFreeSpaceSize>();
        ov::<repo::MinFreeSpacePercent>();
        ov::<repo::AutoUpdateSummary>();
        ov::<repo::AddRemotesConfigDir>();
        ov::<archive::ZlibLevel>();
        ov::<ex_integrity::Composefs>();
        ov::<ex_integrity::Fsverity>();
        ov::<ex_ostrya::KeepDetachedRelated>();
        ov::<ex_ostrya::GcWeakReferences>();
        st::<repo::CollectionId>();
        st::<repo::Fsync>();
        st::<repo::PerObjectFsync>();
        st::<repo::Locking>();
        st::<repo::LockTimeoutSecs>();
        st::<repo::TmpExpirySecs>();
        st::<repo::TombstoneCommits>();
        st::<repo::IndexedDeltas>();
        st::<repo::DisableXattrs>();
        st::<repo::DefaultRepoFinders>();
        st::<repo::MinFreeSpaceSize>();
        st::<repo::MinFreeSpacePercent>();
        st::<repo::AutoUpdateSummary>();
        st::<repo::AddRemotesConfigDir>();
        st::<archive::ZlibLevel>();
        st::<ex_integrity::Composefs>();
        st::<ex_integrity::Fsverity>();
        st::<ex_ostrya::KeepDetachedRelated>();
        st::<ex_ostrya::GcWeakReferences>();
        st::<ex_ostrya::RemotesConfigDir>();
    }

    #[test]
    fn the_marker_lists_follow_the_marker_traits() {
        fn ov<K: Overridable + Key<<K as SingleKey>::Group>>() -> &'static str {
            <K as Key<<K as SingleKey>::Group>>::NAME
        }
        fn st<K: Settable + Key<<K as SingleKey>::Group>>() -> &'static str {
            <K as Key<<K as SingleKey>::Group>>::NAME
        }
        assert_eq!(
            <repo::Group as Group>::OVERRIDABLE,
            [
                ov::<repo::Fsync>(),
                ov::<repo::PerObjectFsync>(),
                ov::<repo::LockTimeoutSecs>(),
                ov::<repo::TmpExpirySecs>(),
                ov::<repo::TombstoneCommits>(),
                ov::<repo::IndexedDeltas>(),
                ov::<repo::DefaultRepoFinders>(),
                ov::<repo::MinFreeSpaceSize>(),
                ov::<repo::MinFreeSpacePercent>(),
                ov::<repo::AutoUpdateSummary>(),
                ov::<repo::AddRemotesConfigDir>(),
            ]
        );
        assert_eq!(
            <repo::Group as Group>::OVERRIDABLE,
            [
                "fsync",
                "per-object-fsync",
                "lock-timeout-secs",
                "tmp-expiry-secs",
                "tombstone-commits",
                "indexed-deltas",
                "default-repo-finders",
                "min-free-space-size",
                "min-free-space-percent",
                "auto-update-summary",
                "add-remotes-config-dir",
            ]
        );
        assert_eq!(
            <archive::Group as Group>::OVERRIDABLE,
            [ov::<archive::ZlibLevel>()]
        );
        assert_eq!(<archive::Group as Group>::OVERRIDABLE, ["zlib-level"]);
        assert_eq!(
            <ex_integrity::Group as Group>::OVERRIDABLE,
            [
                ov::<ex_integrity::Composefs>(),
                ov::<ex_integrity::Fsverity>()
            ]
        );
        assert_eq!(
            <ex_integrity::Group as Group>::OVERRIDABLE,
            ["composefs", "fsverity"]
        );
        assert_eq!(
            <ex_ostrya::Group as Group>::OVERRIDABLE,
            [
                ov::<ex_ostrya::KeepDetachedRelated>(),
                ov::<ex_ostrya::GcWeakReferences>()
            ]
        );
        assert_eq!(
            <ex_ostrya::Group as Group>::OVERRIDABLE,
            ["keep-detached-related", "gc-weak-references"]
        );

        assert_eq!(
            <repo::Group as Group>::SETTABLE,
            [
                st::<repo::CollectionId>(),
                st::<repo::Fsync>(),
                st::<repo::PerObjectFsync>(),
                st::<repo::Locking>(),
                st::<repo::LockTimeoutSecs>(),
                st::<repo::TmpExpirySecs>(),
                st::<repo::TombstoneCommits>(),
                st::<repo::IndexedDeltas>(),
                st::<repo::DisableXattrs>(),
                st::<repo::DefaultRepoFinders>(),
                st::<repo::MinFreeSpaceSize>(),
                st::<repo::MinFreeSpacePercent>(),
                st::<repo::AutoUpdateSummary>(),
                st::<repo::AddRemotesConfigDir>(),
            ]
        );
        // Each key of `[core]` except `repo_version` and `mode`.
        assert_eq!(
            <repo::Group as Group>::SETTABLE,
            &<repo::Group as Group>::KEYS[2..]
        );
        assert_eq!(
            <archive::Group as Group>::SETTABLE,
            [st::<archive::ZlibLevel>()]
        );
        assert_eq!(
            <archive::Group as Group>::SETTABLE,
            <archive::Group as Group>::KEYS
        );
        assert_eq!(
            <ex_integrity::Group as Group>::SETTABLE,
            [
                st::<ex_integrity::Composefs>(),
                st::<ex_integrity::Fsverity>()
            ]
        );
        assert_eq!(
            <ex_integrity::Group as Group>::SETTABLE,
            <ex_integrity::Group as Group>::KEYS
        );
        assert_eq!(
            <ex_ostrya::Group as Group>::SETTABLE,
            [
                st::<ex_ostrya::KeepDetachedRelated>(),
                st::<ex_ostrya::GcWeakReferences>(),
                st::<ex_ostrya::RemotesConfigDir>()
            ]
        );
        assert_eq!(
            <ex_ostrya::Group as Group>::SETTABLE,
            <ex_ostrya::Group as Group>::KEYS
        );

        assert_eq!(<test_single::Group as Group>::OVERRIDABLE, ["jobs"]);
        assert_eq!(<test_single::Group as Group>::SETTABLE, ["name", "jobs"]);
        assert!(<test_named::Group as Group>::OVERRIDABLE.is_empty());
        assert!(<test_named::Group as Group>::SETTABLE.is_empty());
    }

    /// Checks that `got` is `want`: the same value, or an error whose text is
    /// the text of `want`.
    fn expect<T: PartialEq + Debug>(
        got: Result<T>,
        want: std::result::Result<T, &str>,
        case: &str,
    ) {
        assert_eq!(
            got.map_err(|err| err.to_string()),
            want.map_err(str::to_owned),
            "{case}"
        );
    }

    #[test]
    fn typed_reads_give_the_value_of_the_file_or_the_default() {
        type Bool = fn(&RepoConfig) -> Result<bool>;
        let bools: [(&str, &str, Bool, bool); 9] = [
            ("core", "fsync", |c| c.get::<repo::Fsync>(), true),
            (
                "core",
                "per-object-fsync",
                |c| c.get::<repo::PerObjectFsync>(),
                false,
            ),
            ("core", "locking", |c| c.get::<repo::Locking>(), true),
            (
                "core",
                "tombstone-commits",
                |c| c.get::<repo::TombstoneCommits>(),
                false,
            ),
            (
                "core",
                "indexed-deltas",
                |c| c.get::<repo::IndexedDeltas>(),
                true,
            ),
            (
                "core",
                "disable-xattrs",
                |c| c.get::<repo::DisableXattrs>(),
                false,
            ),
            (
                "core",
                "auto-update-summary",
                |c| c.get::<repo::AutoUpdateSummary>(),
                false,
            ),
            (
                "core",
                "add-remotes-config-dir",
                |c| c.get::<repo::AddRemotesConfigDir>(),
                false,
            ),
            (
                "ex-ostrya",
                "keep-detached-related",
                |c| c.get::<ex_ostrya::KeepDetachedRelated>(),
                true,
            ),
        ];
        for (group, key, read, default) in bools {
            let not_bool =
                |raw: &str| format!("keyfile: value '{raw}' for {group}.{key} is not a boolean");
            let (yes, empty) = (not_bool("yes"), not_bool(""));
            for (raw, want) in [
                (None, Ok(default)),
                (Some("true"), Ok(true)),
                (Some("0"), Ok(false)),
                (Some("yes"), Err(yes.as_str())),
                (Some(""), Err(empty.as_str())),
            ] {
                let line = raw.map(|r| format!("{key}={r}")).unwrap_or_default();
                let cfg = config_with(group, &line);
                expect(read(&cfg), want, &format!("{key}={raw:?}"));
            }
        }

        type Int = fn(&RepoConfig) -> Result<i64>;
        let ints: [(&str, &str, Int, i64, Option<&str>); 3] = [
            (
                "core",
                "lock-timeout-secs",
                |c| c.get::<repo::LockTimeoutSecs>().map(LockTimeout::get),
                300,
                Some("invalid format: [core] lock-timeout-secs -2 is below -1"),
            ),
            (
                "core",
                "tmp-expiry-secs",
                |c| c.get::<repo::TmpExpirySecs>(),
                86400,
                None,
            ),
            (
                "archive",
                "zlib-level",
                |c| c.get::<archive::ZlibLevel>(),
                6,
                None,
            ),
        ];
        for (group, key, read, default, below) in ints {
            let not_int =
                |raw: &str| format!("keyfile: value '{raw}' for {group}.{key} is not an integer");
            let (plus, x) = (not_int("+3"), not_int("x"));
            for (raw, want) in [
                (None, Ok(default)),
                (Some("-1"), Ok(-1)),
                (Some("30"), Ok(30)),
                (Some("-2"), below.map_or(Ok(-2), Err)),
                (Some("+3"), Err(plus.as_str())),
                (Some("x"), Err(x.as_str())),
            ] {
                let line = raw.map(|r| format!("{key}={r}")).unwrap_or_default();
                let cfg = config_with(group, &line);
                expect(read(&cfg), want, &format!("{key}={raw:?}"));
            }
        }

        let finders = |v: &[&str]| v.iter().map(|s| (*s).to_owned()).collect::<Vec<_>>();
        for (raw, want) in [
            (None, Ok(finders(&["config", "mount"]))),
            (Some("a;b;"), Ok(finders(&["a", "b"]))),
            (Some(r"a\sb"), Ok(finders(&["a b"]))),
            (Some(r"a\q"), Err(r"keyfile: invalid escape '\q'")),
        ] {
            let line = raw
                .map(|r| format!("default-repo-finders={r}"))
                .unwrap_or_default();
            let cfg = config_with("core", &line);
            expect(
                cfg.get::<repo::DefaultRepoFinders>(),
                want,
                &format!("default-repo-finders={raw:?}"),
            );
        }

        for (raw, want) in [
            (None, Ok(MinFreeSpace::Percent(3))),
            (Some("0"), Ok(MinFreeSpace::Percent(0))),
            (Some("100"), Ok(MinFreeSpace::Percent(100))),
            (
                Some("101"),
                Err("invalid format: [core] min-free-space-percent 101 is out of the range 0-100"),
            ),
            (
                Some("-1"),
                Err("invalid format: [core] min-free-space-percent -1 is out of the range 0-100"),
            ),
            (
                Some("x"),
                Err("keyfile: value 'x' for core.min-free-space-percent is not an integer"),
            ),
        ] {
            let line = raw
                .map(|r| format!("min-free-space-percent={r}"))
                .unwrap_or_default();
            let cfg = config_with("core", &line);
            expect(
                cfg.min_free_space(),
                want,
                &format!("min-free-space-percent={raw:?}"),
            );
        }
        let size = |value, unit| Ok(MinFreeSpace::Size(SizeSpec { value, unit }));
        for (raw, want) in [
            ("min-free-space-size=2GB", size(2, SizeUnit::Giga)),
            ("min-free-space-size=1TB", size(1, SizeUnit::Tera)),
            (
                "min-free-space-size=5XB",
                Err(
                    "invalid format: [core] min-free-space-size value '5XB' is not of the form \
                     123MB, 123GB, or 123TB",
                ),
            ),
            // The size wins, and the call does not read the percent.
            (
                "min-free-space-size=3MB\nmin-free-space-percent=x",
                size(3, SizeUnit::Mega),
            ),
        ] {
            expect(config_with("core", raw).min_free_space(), want, raw);
        }

        for (raw, want) in [
            (None, Ok(Tristate::No)),
            (Some("maybe"), Ok(Tristate::Maybe)),
            (
                Some("x"),
                Err("invalid format: [ex-integrity] composefs value 'x' is not no, maybe, or yes"),
            ),
            (Some(r"\q"), Err(r"keyfile: invalid escape '\q'")),
        ] {
            let line = raw.map(|r| format!("composefs={r}")).unwrap_or_default();
            let cfg = config_with("ex-integrity", &line);
            expect(
                cfg.get::<ex_integrity::Composefs>(),
                want,
                &format!("composefs={raw:?}"),
            );
        }
        for (raw, want) in [
            ("yes", Ok(Tristate::Yes)),
            (
                "true",
                Err(
                    "invalid format: [ex-integrity] fsverity value 'true' is not no, maybe, or yes",
                ),
            ),
            (r"\q", Err(r"keyfile: invalid escape '\q'")),
        ] {
            let cfg = config_with("ex-integrity", &format!("fsverity={raw}"));
            expect(cfg.fsverity(), want, raw);
        }
        assert_eq!(
            config_with("ex-integrity", "")
                .get::<ex_integrity::Fsverity>()
                .unwrap(),
            None
        );

        for (raw, want) in [
            (None, Ok(None)),
            (
                Some("tmp/**;!tmp/keep;"),
                Ok(Some("tmp/**;!tmp/keep;".to_owned())),
            ),
            (
                Some("tmp/**;r*:x"),
                Err(
                    "invalid format: [ex-ostrya] gc-weak-references holds a malformed entry: \
                     malformed receive pattern 'r*:x': a remote part is one remote or '*'",
                ),
            ),
            (
                Some("!tmp/**"),
                Err(
                    "invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern \
                     without '!'",
                ),
            ),
            (Some(r"a\q"), Err(r"keyfile: invalid escape '\q'")),
        ] {
            let line = raw
                .map(|r| format!("gc-weak-references={r}"))
                .unwrap_or_default();
            let cfg = config_with("ex-ostrya", &line);
            expect(
                cfg.gc_weak_references()
                    .map(|s| s.as_ref().map(Value::format)),
                want,
                &format!("gc-weak-references={raw:?}"),
            );
        }

        for raw in [None, Some("org.ex.C"), Some(r"org\q")] {
            let line = raw
                .map(|r| format!("collection-id={r}"))
                .unwrap_or_default();
            let text = format!("{BASE}{line}\n");
            match RepoConfig::parse(&text) {
                Ok(cfg) => assert_eq!(
                    cfg.get::<repo::CollectionId>()
                        .unwrap()
                        .as_ref()
                        .map(CollectionIdValue::as_str),
                    cfg.collection_id(),
                    "{raw:?}"
                ),
                Err(err) => {
                    let mut kf = KeyFile::parse(BASE).unwrap();
                    kf.set_value(CORE, "collection-id", raw.unwrap()).unwrap();
                    let cfg_err = typed_read_of(kf);
                    assert_eq!(cfg_err, err.to_string(), "{raw:?}");
                }
            }
        }

        let cfg = RepoConfig::parse(BASE).unwrap();
        assert_eq!(cfg.get::<repo::Mode>().unwrap(), cfg.mode());
        assert_eq!(cfg.get::<repo::RepoVersion>().unwrap(), cfg.repo_version());

        let dir = |kind: &'static str, path: &str| Ok(Some((kind, PathBuf::from(path))));
        for (raw, want) in [
            ("/etc/r.d", dir("path", "/etc/r.d")),
            ("r.d", dir("in-repo", "r.d")),
            ("/etc/../r.d", dir("path", "/etc/../r.d")),
            (
                "",
                Err("invalid format: [ex-ostrya] remotes-config-dir is empty"),
            ),
            (
                "a\0b",
                Err("invalid format: [ex-ostrya] remotes-config-dir holds a NUL byte"),
            ),
            (
                "../r.d",
                Err(
                    "invalid format: [ex-ostrya] remotes-config-dir ../r.d has a `..` \
                     component, which a relative path in a config cannot have",
                ),
            ),
            (r"\q", Err(r"keyfile: invalid escape '\q'")),
        ] {
            let cfg = config_with("ex-ostrya", &format!("remotes-config-dir={raw}"));
            let read = crate::remotes_dir::from_key(&cfg).map(|dir| {
                dir.map(|dir| match dir {
                    crate::repo::RemotesDir::Path(p) => ("path", p),
                    crate::repo::RemotesDir::InRepo(p) => ("in-repo", p),
                    crate::repo::RemotesDir::Fd(_) => unreachable!(),
                })
            });
            expect(read, want, raw);
        }
        assert!(
            crate::remotes_dir::from_key(&config_with("ex-ostrya", ""))
                .unwrap()
                .is_none()
        );
    }

    /// A typed read of a remote key names the remote section in a refusal.
    #[test]
    fn a_remote_key_refusal_names_the_section() {
        let read =
            |line: &str| RepoConfig::parse(&format!("{BASE}[remote \"o\"]\n{line}\n")).unwrap();
        let cfg = read("pull-branches=apps/**;r*:x");
        let section = cfg.section::<remote::Group>("o").unwrap();
        assert_eq!(
            section
                .get::<remote::PullBranches>()
                .unwrap_err()
                .to_string(),
            "invalid format: [remote \"o\"] pull-branches holds a malformed entry: malformed \
             receive pattern 'r*:x': a remote part is one remote or '*'"
        );
        let cfg = read("gpgkeypath=/a;../b");
        let section = cfg.section::<remote::Group>("o").unwrap();
        assert_eq!(
            section.get::<remote::GpgKeyPath>().unwrap_err().to_string(),
            "invalid format: [remote \"o\"] gpgkeypath ../b has a `..` component, which a \
             relative path in a config cannot have"
        );
        let cfg = read("gpg-verify=maybe");
        let section = cfg.section::<remote::Group>("o").unwrap();
        assert_eq!(
            section.get::<remote::GpgVerify>().unwrap_err().to_string(),
            "keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
        );
    }

    /// Returns the text of the error of a typed read of `collection-id` in
    /// the document `kf`, which [`RepoConfig::from_keyfile`] refuses.
    fn typed_read_of(kf: KeyFile) -> String {
        let raw = kf.get_value(CORE, "collection-id").unwrap();
        let err = <CollectionIdValue as Value>::parse(raw).unwrap_err();
        value::value_error(CORE, "collection-id", raw, err).to_string()
    }

    #[test]
    fn collection_id_refuses_an_id_that_fails_the_rule() {
        let cfg = config_with("core", "collection-id=a b");
        assert_eq!(cfg.collection_id(), Some("a b"));
        assert_eq!(
            cfg.get::<repo::CollectionId>().unwrap_err().to_string(),
            "invalid format: [core] collection-id value 'a b' is not a valid collection id"
        );
    }

    crate::config_group! {
        /// A single group of a test.
        pub group test_single = "ex-test" {
            Name: Option<String> = "name";
            Jobs: u32 = "jobs", default 4, overridable;
            Strict: bool = "strict", default false, fixed;
        }
    }

    crate::config_group! {
        /// A named group of a test.
        pub group test_named = named "ex-test n", closed {
            Arch: String = "arch", required;
            Tags: Vec<String> = "tags", default Vec::new();
            Next: Option<GroupRef<test_named::Group>> = "next";
        }
    }

    #[test]
    fn a_user_group_reads_its_sections() {
        let text = format!(
            "{BASE}[ex-test]\njobs=8\n\
             [ex-test n \"b\"]\narch=arm64\nnext=a\n\
             [remote \"o\"]\nurl=http://o/\n\
             [ex-test n \"a\"]\narch=amd64\ntags=x;y;\n\
             [ex-test n \"c\"]\ntags=z\n\
             [ex-test nx \"d\"]\narch=amd64\n"
        );
        let cfg = RepoConfig::parse(&text).unwrap();
        assert_eq!(cfg.get::<test_single::Jobs>().unwrap(), 8);
        assert_eq!(cfg.get::<test_single::Name>().unwrap(), None);
        assert!(!cfg.get::<test_single::Strict>().unwrap());

        let names: Vec<_> = cfg
            .sections::<test_named::Group>()
            .map(|s| s.name().to_owned())
            .collect();
        assert_eq!(names, ["b", "a", "c"]);
        assert!(cfg.section::<test_named::Group>("absent").is_none());
        let b = cfg.section::<test_named::Group>("b").unwrap();
        assert_eq!(b.name(), "b");
        assert_eq!(b.get::<test_named::Arch>().unwrap(), "arm64");
        assert_eq!(b.get::<test_named::Tags>().unwrap(), Vec::<String>::new());
        assert_eq!(
            b.lookup::<test_named::Tags>().unwrap(),
            Some(Lookup::Default(Vec::new()))
        );
        assert_eq!(b.file_value::<test_named::Tags>().unwrap(), None);
        let next = b.get::<test_named::Next>().unwrap().unwrap();
        assert_eq!(next, GroupRef::new("a").unwrap());
        let a = cfg.resolve(&next).unwrap();
        assert_eq!(a.get::<test_named::Tags>().unwrap(), ["x", "y"]);
        assert_eq!(a.get::<test_named::Next>().unwrap(), None);

        let err = cfg
            .resolve(&GroupRef::<test_named::Group>::new("z").unwrap())
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the config has no [ex-test n \"z\"] group"
        );
        let c = cfg.section::<test_named::Group>("c").unwrap();
        assert_eq!(
            c.get::<test_named::Arch>().unwrap_err().to_string(),
            "invalid format: [ex-test n \"c\"] has no arch"
        );
        assert_eq!(c.lookup::<test_named::Arch>().unwrap(), None);
        const { assert!(<test_named::Group as Group>::CLOSED) };
        const { assert!(<test_named::Group as Group>::NAMED) };
        assert_eq!(<test_named::Group as Group>::KEYS, ["arch", "tags", "next"]);
    }

    #[test]
    fn a_typed_read_names_the_group_header_in_an_error() {
        let text = format!(
            "{BASE}[ex-test]\njobs=-1\n[ex-test n \"a\"]\narch=amd64\nnext=\n\
             [ex-test n \"b\"]\narch=\\q\n"
        );
        let cfg = RepoConfig::parse(&text).unwrap();
        assert_eq!(
            cfg.get::<test_single::Jobs>().unwrap_err().to_string(),
            "invalid format: [ex-test] jobs -1 is out of the range 0-4294967295"
        );
        let a = cfg.section::<test_named::Group>("a").unwrap();
        assert_eq!(
            a.get::<test_named::Next>().unwrap_err().to_string(),
            "invalid format: [ex-test n \"a\"] next is empty"
        );
        let b = cfg.section::<test_named::Group>("b").unwrap();
        assert_eq!(
            b.get::<test_named::Arch>().unwrap_err().to_string(),
            r"keyfile: invalid escape '\q'"
        );
        // A typed read of a boolean names the group header.
        crate::config_group! {
            pub group flags = named "ex-flags" {
                On: Option<bool> = "on";
            }
        }
        let cfg = RepoConfig::parse(&format!("{BASE}[ex-flags \"s\"]\non=x\n")).unwrap();
        assert_eq!(
            cfg.section::<flags::Group>("s")
                .unwrap()
                .get::<flags::On>()
                .unwrap_err()
                .to_string(),
            "keyfile: value 'x' for ex-flags \"s\".on is not a boolean"
        );
    }

    #[test]
    fn config_edit_sets_and_removes_keys() {
        let mut kf = KeyFile::parse(&format!("{BASE}fsync=true\n")).unwrap();
        let mut edit = ConfigEdit::new(&mut kf);
        edit.set::<repo::Fsync>(false).unwrap();
        edit.set::<repo::Locking>(false).unwrap();
        edit.set::<archive::ZlibLevel>(9).unwrap();
        edit.set::<ex_ostrya::RemotesConfigDir>(RemotesConfigPath::try_from(" r.d").unwrap())
            .unwrap();
        assert!(edit.remove::<repo::Locking>());
        assert!(!edit.remove::<repo::Locking>());
        edit.set::<test_single::Name>("  x".to_owned()).unwrap();
        assert_eq!(
            kf.to_string(),
            "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\n\
             [archive]\nzlib-level=9\n\n\
             [ex-ostrya]\nremotes-config-dir=\\sr.d\n\n\
             [ex-test]\nname=\\s\\sx\n"
        );
        let cfg = RepoConfig::from_keyfile(kf.clone()).unwrap();
        assert!(!cfg.get::<repo::Fsync>().unwrap());
        assert_eq!(cfg.get::<archive::ZlibLevel>().unwrap(), 9);
        assert_eq!(
            cfg.get::<test_single::Name>().unwrap().as_deref(),
            Some("  x")
        );
        assert_eq!(
            cfg.get::<ex_ostrya::RemotesConfigDir>()
                .unwrap()
                .unwrap()
                .as_str(),
            " r.d"
        );

        let mut edit = ConfigEdit::new(&mut kf);
        edit.keyfile_mut().set_value("core", "other", "1").unwrap();
        assert_eq!(kf.get_value("core", "other"), Some("1"));
    }

    #[test]
    fn a_section_name_is_not_empty_and_holds_no_quote() {
        crate::config_group! {
            pub group h = named "ex-h" {
                X: Option<String> = "x";
            }
        }
        let cfg = RepoConfig::parse(&format!(
            "{BASE}[ex-h \"\"]\nx=1\n[ex-h \"a\" \"b\"]\nx=2\n[ex-h \"c\"]\nx=3\n"
        ))
        .unwrap();
        assert!(cfg.keyfile().has_group("ex-h \"\""));
        assert!(cfg.keyfile().has_group("ex-h \"a\" \"b\""));
        let names: Vec<_> = cfg
            .sections::<h::Group>()
            .map(|s| s.name().to_owned())
            .collect();
        assert_eq!(names, ["c"]);
        assert!(cfg.section::<h::Group>("").is_none());
        assert!(cfg.section::<h::Group>("a\" \"b").is_none());
        assert_eq!(
            cfg.section::<h::Group>("c")
                .unwrap()
                .get::<h::X>()
                .unwrap()
                .as_deref(),
            Some("3")
        );
        assert!(GroupRef::<h::Group>::new("").is_err());
        let err = cfg
            .resolve(&GroupRef::<h::Group>::new("a\" \"b").unwrap())
            .unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid format: the config has no [ex-h \"a\" \"b\"] group"
        );
    }
}

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

    const BASE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";

    /// Returns the config of `BASE` followed by `text`.
    fn config(text: &str) -> RepoConfig {
        RepoConfig::parse(&format!("{BASE}{text}")).unwrap()
    }

    /// Returns the text of the error of the check of `cfg`.
    fn refusal(cfg: &RepoConfig) -> String {
        cfg.check().unwrap_err().to_string()
    }

    #[test]
    fn a_valid_config_passes() {
        let cfg = config(
            "fsync=false\nlock-timeout-secs=-1\nmin-free-space-size=5GB\n\
             min-free-space-percent=10\ncollection-id=org.example.Repo\n\
             [archive]\nzlib-level=99\n\
             [ex-integrity]\ncomposefs=maybe\nfsverity=yes\n\
             [ex-ostrya]\ngc-weak-references=tmp/**;!tmp/keep\n\
             remotes-config-dir=remotes.d\n\
             [remote \"o\"]\nurl=https://o\ngpg-verify=false\n\
             collection-id=org.example.A\nmirrored-collection-ids=org.example.B\n",
        );
        cfg.check().unwrap();
        RepoConfig::parse(BASE).unwrap().check().unwrap();
    }

    #[test]
    fn a_bad_value_of_each_group_is_refused() {
        let cfg = config("tombstone-commits=maybe\n");
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<repo::TombstoneCommits>()
                .unwrap_err()
                .to_string()
        );
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for core.tombstone-commits is not a boolean"
        );

        let cfg = config("[archive]\nzlib-level=abc\n");
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<archive::ZlibLevel>()
                .unwrap_err()
                .to_string()
        );

        let cfg = config("[ex-integrity]\ncomposefs=sometimes\n");
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<ex_integrity::Composefs>()
                .unwrap_err()
                .to_string()
        );

        let cfg = config("[ex-ostrya]\nkeep-detached-related=maybe\n");
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<ex_ostrya::KeepDetachedRelated>()
                .unwrap_err()
                .to_string()
        );

        let cfg = config("[remote \"o\"]\nurl=https://o\ngpg-verify=maybe\n");
        let remote = cfg.section::<remote::Group>("o").unwrap();
        assert_eq!(
            refusal(&cfg),
            remote
                .file_value::<remote::GpgVerify>()
                .unwrap_err()
                .to_string()
        );
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
        );
    }

    #[test]
    fn the_check_gives_the_first_error_in_group_and_key_order() {
        let cfg = config(
            "[remote \"o\"]\ngpg-verify=maybe\n\
             [ex-ostrya]\nkeep-detached-related=maybe\n\
             [core]\nindexed-deltas=maybe\nfsync=maybe\n",
        );
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for core.fsync is not a boolean"
        );
        let cfg = config("[remote \"b\"]\ngpg-verify=maybe\n[remote \"a\"]\ngpg-verify=maybe\n");
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for remote \"b\".gpg-verify is not a boolean"
        );
    }

    #[test]
    fn each_key_of_a_pair_is_checked() {
        let cfg = config("min-free-space-size=5GB\nmin-free-space-percent=200\n");
        cfg.min_free_space().unwrap();
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<repo::MinFreeSpacePercent>()
                .unwrap_err()
                .to_string()
        );

        let cfg = config("[ex-integrity]\ncomposefs=yes\nfsverity=sometimes\n");
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<ex_integrity::Fsverity>()
                .unwrap_err()
                .to_string()
        );
        let cfg = config("[ex-integrity]\ncomposefs=sometimes\nfsverity=yes\n");
        cfg.fsverity().unwrap();
        assert_eq!(
            refusal(&cfg),
            cfg.file_value::<ex_integrity::Composefs>()
                .unwrap_err()
                .to_string()
        );
    }

    #[test]
    fn a_gc_weak_references_list_with_no_positive_entry_is_refused() {
        for value in ["", "!tmp/**"] {
            let cfg = config(&format!("[ex-ostrya]\ngc-weak-references={value}\n"));
            assert_eq!(
                refusal(&cfg),
                cfg.gc_weak_references().unwrap_err().to_string()
            );
            assert_eq!(
                refusal(&cfg),
                "invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern \
                 without '!'"
            );
        }
    }

    #[test]
    fn a_mirrored_id_that_is_the_collection_id_of_the_remote_is_refused() {
        let cfg = config(
            "[remote \"o\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.C;org.a.B\n",
        );
        assert_eq!(
            refusal(&cfg),
            "invalid format: [remote \"o\"] mirrored-collection-ids holds 'org.a.B', the \
             collection-id of the remote"
        );
    }

    #[test]
    fn a_collection_id_that_fails_the_rule_is_refused() {
        let cfg = config("collection-id=a b\n");
        assert_eq!(
            refusal(&cfg),
            "invalid format: [core] collection-id value 'a b' is not a valid collection id"
        );
    }

    #[test]
    fn keys_and_groups_that_the_port_does_not_define_pass() {
        let cfg = config(
            "parent=/nonexistent\ncommit-update-summary=maybe\nzzz=maybe\n\
             [archive]\nzzz=x\n\
             [ex-ostrya]\ngenerate-composefs=maybe\n\
             [ex-debles]\ntarget=anything\nparallel=many\n\
             [ex-ostrya trust \"\"]\nzzz=1\n\
             [ex-ostrya key \"a\"b\"]\nzzz=1\n\
             [remote \"o\"]\nzzz=maybe\n\
             [remote \"\"]\ngpg-verify=maybe\n",
        );
        cfg.check().unwrap();
    }

    #[test]
    fn an_unknown_key_of_the_server_group_is_refused() {
        let cfg = config("[ex-ostrya server]\nlisten=bad\nzzz=1\nyyy=2\n");
        assert_eq!(
            refusal(&cfg),
            "invalid format: [ex-ostrya server] holds the unknown key 'zzz'"
        );
        config("[ex-ostrya server]\n").check().unwrap();
        config("[ex-debles]\nzzz=1\n").check().unwrap();
    }

    /// The check refuses a bad server value with the text of the reader of
    /// the server group.
    #[test]
    fn a_bad_server_value_is_refused_with_the_text_of_the_reader() {
        for keys in [
            "listen=\n",
            "listen=localhost:8080\n",
            "listen=a\\\n",
            "tls-cert=\n",
            "tls-key=../k.pem\n",
            "tls-client-ca=a\\q\n",
            "trusted-proxy=\n",
            "trusted-proxy=10.0.0.1/24\n",
            "trusted-proxy-header=X-Real-IP\n",
            "trusted-proxy-client-cert=X Client\n",
            "proxy-protocol=yes\n",
            "allow-cleartext-credentials=2\n",
            "session-timeout=0\n",
            "max-sessions=9223372036854775808\n",
            "parallel-uploads=32\n",
            "body-timeout=+1\n",
            "sign-summary=\n",
        ] {
            let cfg = config(&format!("[ex-ostrya server]\n{keys}"));
            let read = crate::access::ClientAccess::from_config(&cfg)
                .unwrap_err()
                .to_string();
            assert_eq!(refusal(&cfg), read, "{keys:?}");
        }
    }

    /// The check reads the server keys in the order of their definition,
    /// after the remotes. It does not check the references of
    /// `sign-summary`.
    #[test]
    fn the_server_group_is_checked_after_the_remotes_in_key_order() {
        let cfg = config("[ex-ostrya server]\ntrusted-proxy=\ntls-cert=\n");
        assert_eq!(
            refusal(&cfg),
            "invalid format: [ex-ostrya server] tls-cert is empty; remove the key or name a file"
        );
        let cfg = config("[ex-ostrya server]\nzzz=1\n[remote \"o\"]\ngpg-verify=maybe\n");
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for remote \"o\".gpg-verify is not a boolean"
        );
        config(
            "[ex-ostrya server]\nlisten=127.0.0.1:80;[::1]:81\ntls-cert=c.pem\n\
             tls-key=/k.pem\ntls-client-ca=ca.pem\ntrusted-proxy=10.0.0.0/8\n\
             trusted-proxy-header=forwarded\ntrusted-proxy-client-cert=X-Cert\n\
             proxy-protocol=1\nallow-cleartext-credentials=false\nsession-timeout=5\n\
             max-sessions=9223372036854775807\nparallel-uploads=31\nbody-timeout=1\n\
             sign-summary=nokey;nokey\n",
        )
        .check()
        .unwrap();
    }

    #[test]
    fn an_unknown_key_of_a_client_group_is_refused() {
        let cfg = config("[ex-ostrya client \"c\"]\nauth=bogus\nzzz=1\nyyy=2\n");
        assert_eq!(
            refusal(&cfg),
            "invalid format: [ex-ostrya client \"c\"] holds the unknown key 'zzz'"
        );
        let cfg = config("[ex-ostrya client \"c\"]\nzzz=1\ncollection=x\n");
        assert_eq!(
            refusal(&cfg),
            "invalid format: [ex-ostrya client \"c\"] holds the removed key 'collection'; an \
             allow item or a deny item names the refs of a collection as @ID:PATTERN"
        );
        config("[ex-ostrya client \"c\"]\n").check().unwrap();
    }

    /// The check refuses a bad client value with the text of the reader of
    /// the client groups.
    #[test]
    fn a_bad_client_value_is_refused_with_the_text_of_the_reader() {
        for keys in [
            "auth=bogus\n",
            "auth=;\n",
            "auth=a\\q\n",
            "auth=anonymous\nallow=R:a\n",
            "auth=anonymous\nallow=a\\\n",
            "auth=anonymous\ndeny=@a.b\n",
            "auth=tls:*\ntls-accept-claim=yes\n",
            "auth=anonymous\nverify=off\n",
            "auth=anonymous\nverify=remote:origin\n",
            "auth=anonymous\nverify=trust:\n",
            "auth=anonymous\nallow-unsigned=maybe\n",
            "auth=anonymous\nsign=\n",
            "auth=anonymous\nallow-privileged=2\n",
            "auth=anonymous\ndisable-verify-bindings=on\n",
            "auth=anonymous\nsummary=yes\n",
            "auth=anonymous\nzzz=1\n",
            "auth=anonymous\ncollection=x\n",
        ] {
            let cfg = config(&format!("[ex-ostrya client \"c\"]\n{keys}"));
            let read = crate::access::ClientAccess::from_config(&cfg)
                .unwrap_err()
                .to_string();
            assert_eq!(refusal(&cfg), read, "{keys:?}");
        }
    }

    /// The check reads the client groups after the server group, in the
    /// order of the file, and the keys of a group in the order of their
    /// definition.
    #[test]
    fn the_client_groups_are_checked_after_the_server_in_file_order() {
        let cfg = config(
            "[ex-ostrya client \"b\"]\nsummary=yes\n[ex-ostrya server]\nzzz=1\n\
             [ex-ostrya client \"a\"]\nzzz=1\n",
        );
        assert_eq!(
            refusal(&cfg),
            "invalid format: [ex-ostrya server] holds the unknown key 'zzz'"
        );
        let cfg =
            config("[ex-ostrya client \"b\"]\nsummary=yes\n[ex-ostrya client \"a\"]\nzzz=1\n");
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'yes' for ex-ostrya client \"b\".summary is not a boolean"
        );
        // The definition puts `tls-accept-claim` before `summary`.
        let cfg = config("[ex-ostrya client \"c\"]\nsummary=yes\ntls-accept-claim=maybe\n");
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for ex-ostrya client \"c\".tls-accept-claim is not a \
             boolean"
        );
    }

    /// The check does not apply the rules of the reader that need more than
    /// the value of one key.
    #[test]
    fn the_check_does_not_apply_the_rules_of_the_client_reader() {
        for text in [
            "[ex-ostrya client \"c\"]\n",
            "[ex-ostrya client \"c\"]\nauth=\n",
            "[ex-ostrya client \"c\"]\nauth=anonymous\ntls-accept-claim=true\n",
            "[ex-ostrya client \"c\"]\nauth=tls:*\ntls-accept-claim=true\nsummary=true\n",
            "[ex-ostrya client \"c\"]\nauth=anonymous\nverify=trust:nosuch\n",
            "[ex-ostrya client \"c\"]\nauth=anonymous\nsign=nosuch\n",
            "[ex-ostrya client \"c\"]\nauth=anonymous\nallow-unsigned=false\n",
            "[ex-ostrya client \"a\"]\nauth=anonymous\n[ex-ostrya client \"b\"]\nauth=anonymous\n",
            "[ex-ostrya client \"a\tb\"]\nauth=anonymous\n",
        ] {
            let cfg = config(text);
            cfg.check().unwrap();
            crate::access::ClientAccess::from_config(&cfg).unwrap_err();
        }
    }

    /// The header of the trust group of the check tests.
    const TRUST_T: &str = "ex-ostrya trust \"t\"";

    /// Returns the text of the error of the reader of the trust group `t` of
    /// `cfg`.
    fn trust_reader_refusal(cfg: &RepoConfig) -> String {
        let section = cfg.section::<trust::Group>("t").unwrap();
        crate::verify::trust::check_trust(&section)
            .unwrap_err()
            .to_string()
    }

    /// Returns the text of the error of the reader of the key group `k` of
    /// `cfg`.
    fn key_reader_refusal(cfg: &RepoConfig) -> String {
        let section = cfg.section::<key::Group>("k").unwrap();
        match crate::sign::key_group::parse_key(&section) {
            Ok(_) => panic!("the key group is accepted"),
            Err(err) => err.to_string(),
        }
    }

    /// The check refuses an unknown key of a trust group with the text of
    /// the reader of the trust groups. The keys of a summary check and the
    /// keys of an engine other than ed25519 and spki get the text that
    /// states the reason. The check names the first such key in the order
    /// of the file.
    #[test]
    fn an_unknown_key_of_a_trust_group_is_refused_with_the_text_of_the_reader() {
        let base = "sign-verify=ed25519\nverification-ed25519-key=AAAA\n";
        for (keys, text) in [
            (
                "zzz=1\n",
                "invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
            ),
            (
                "gpg-verify-summary=true\n",
                "invalid format: [ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a \
                 trust group sets a commit policy alone",
            ),
            (
                "sign-verify-summary=maybe\\q\n",
                "invalid format: [ex-ostrya trust \"t\"] holds 'sign-verify-summary', and a \
                 trust group sets a commit policy alone",
            ),
            (
                "verification-foo-key=AAAA\n",
                "invalid format: [ex-ostrya trust \"t\"] holds 'verification-foo-key', and \
                 'foo' is not ed25519 or spki",
            ),
            (
                "verification-dummy-file=../k\n",
                "invalid format: [ex-ostrya trust \"t\"] holds 'verification-dummy-file', and \
                 'dummy' is not ed25519 or spki",
            ),
            (
                "zzz=1\ngpg-verify-summary=true\n",
                "invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
            ),
            (
                "gpg-verify-summary=true\nzzz=1\n",
                "invalid format: [ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a \
                 trust group sets a commit policy alone",
            ),
            (
                "gpg-verify=maybe\nzzz=1\n",
                "invalid format: [ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
            ),
        ] {
            let cfg = config(&format!("[{TRUST_T}]\n{base}{keys}"));
            assert_eq!(refusal(&cfg), text, "{keys:?}");
            assert_eq!(trust_reader_refusal(&cfg), text, "{keys:?}");
        }
        config(&format!("[{TRUST_T}]\n")).check().unwrap();
    }

    /// The check refuses a bad value of a trust key with the text of the
    /// typed read of the key, in the order of the definition of the keys.
    #[test]
    fn a_bad_trust_value_is_refused() {
        for (keys, text) in [
            (
                "gpg-verify=maybe\n",
                "keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
            ),
            (
                "gpgkeypath=/a.gpg;../k.gpg\n",
                "invalid format: [ex-ostrya trust \"t\"] gpgkeypath ../k.gpg has a `..` \
                 component, which a relative path in a config cannot have",
            ),
            ("sign-verify=a\\q\n", "keyfile: invalid escape '\\q'"),
            (
                "verification-ed25519-key=\\q\n",
                "keyfile: invalid escape '\\q'",
            ),
            (
                "verification-ed25519-file=../k\n",
                "invalid format: [ex-ostrya trust \"t\"] verification-ed25519-file ../k has a \
                 `..` component, which a relative path in a config cannot have",
            ),
            (
                "verification-spki-key=\\q\n",
                "keyfile: invalid escape '\\q'",
            ),
            (
                "verification-spki-file=k/../../k\n",
                "invalid format: [ex-ostrya trust \"t\"] verification-spki-file k/../../k has \
                 a `..` component, which a relative path in a config cannot have",
            ),
            // The definition puts `gpg-verify` before `sign-verify`.
            (
                "sign-verify=a\\q\ngpg-verify=2\n",
                "keyfile: value '2' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
            ),
        ] {
            let cfg = config(&format!("[{TRUST_T}]\n{keys}"));
            assert_eq!(refusal(&cfg), text, "{keys:?}");
        }
    }

    /// The check refuses an unknown key and a bad value of a key group. The
    /// texts of an unknown key and of a bad type are the texts of the reader
    /// of the key groups.
    #[test]
    fn a_key_group_is_checked() {
        for (keys, text, reader) in [
            (
                "type=rsa\nzzz=1\n",
                "invalid format: [ex-ostrya key \"k\"] holds the unknown key 'zzz'",
                true,
            ),
            (
                "type=rsa\n",
                "invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
                 ed25519, spki, or gpg",
                true,
            ),
            (
                "type=dummy\n",
                "invalid format: malformed [ex-ostrya key \"k\"] type value 'dummy': the dummy \
                 engine is not a signing key, its signature is its key",
                true,
            ),
            ("type=ed\\q\n", "keyfile: invalid escape '\\q'", true),
            (
                "type=ed25519\nsecret-key-file=../s\n",
                "invalid format: [ex-ostrya key \"k\"] secret-key-file ../s has a `..` \
                 component, which a relative path in a config cannot have",
                true,
            ),
            (
                "type=ed25519\ncertificate-chain-file=../c\n",
                "invalid format: [ex-ostrya key \"k\"] certificate-chain-file ../c has a `..` \
                 component, which a relative path in a config cannot have",
                false,
            ),
            (
                "type=spki\nsecret-key-file=/s\ncrl-file=a/../c\n",
                "invalid format: [ex-ostrya key \"k\"] crl-file a/../c has a `..` \
                 component, which a relative path in a config cannot have",
                true,
            ),
            (
                "certificate-chain-file=\\q\n",
                "keyfile: invalid escape '\\q'",
                false,
            ),
            ("crl-file=\\q\n", "keyfile: invalid escape '\\q'", false),
            (
                "secret-key-file=\\q\n",
                "keyfile: invalid escape '\\q'",
                false,
            ),
            ("gpg-key=\\q\n", "keyfile: invalid escape '\\q'", false),
            ("gpg-homedir=\\q\n", "keyfile: invalid escape '\\q'", false),
            // The definition puts `type` before `gpg-homedir`.
            (
                "gpg-homedir=\\q\ntype=rsa\n",
                "invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
                 ed25519, spki, or gpg",
                false,
            ),
        ] {
            let cfg = config(&format!("[ex-ostrya key \"k\"]\n{keys}"));
            assert_eq!(refusal(&cfg), text, "{keys:?}");
            if reader {
                assert_eq!(key_reader_refusal(&cfg), text, "{keys:?}");
            }
        }
    }

    /// The check reads the client groups, then the trust groups, then the
    /// key groups, each in the order of the file.
    #[test]
    fn the_trust_and_key_groups_are_checked_after_the_clients_in_file_order() {
        let key_b = "[ex-ostrya key \"b\"]\nzzz=1\n";
        let trust_b = "[ex-ostrya trust \"b\"]\nzzz=1\n";
        let client_b = "[ex-ostrya client \"b\"]\nzzz=1\n";
        let key_a = "[ex-ostrya key \"a\"]\nzzz=1\n";
        let trust_a = "[ex-ostrya trust \"a\"]\nzzz=1\n";
        for (groups, header) in [
            (
                [key_b, trust_b, client_b, key_a, trust_a].concat(),
                "ex-ostrya client \"b\"",
            ),
            (
                [key_b, trust_b, key_a, trust_a].concat(),
                "ex-ostrya trust \"b\"",
            ),
            ([key_b, key_a, trust_a].concat(), "ex-ostrya trust \"a\""),
            ([key_b, key_a].concat(), "ex-ostrya key \"b\""),
        ] {
            assert_eq!(
                refusal(&config(&groups)),
                format!("invalid format: [{header}] holds the unknown key 'zzz'"),
                "{groups:?}"
            );
        }
    }

    /// The check does not apply the rules of the readers of the trust groups
    /// and the key groups that need more than the value of one key.
    #[test]
    fn the_check_does_not_apply_the_rules_of_the_trust_and_key_readers() {
        for keys in [
            "",
            "gpg-verify=false\nsign-verify=false\n",
            "sign-verify=dummy\n",
            "sign-verify=ed25519;foo\nverification-ed25519-key=AAAA\n",
            "gpgkeypath=/k.gpg\nsign-verify=ed25519\nverification-ed25519-key=AAAA\n",
            "gpg-verify=true\n",
            "gpg-verify=true\ngpgkeypath=;;/k.gpg\n",
            "sign-verify=ed25519\nverification-spki-key=AAAA\n",
        ] {
            let cfg = config(&format!("[{TRUST_T}]\n{keys}"));
            cfg.check().unwrap();
            trust_reader_refusal(&cfg);
        }
        for keys in [
            "",
            "secret-key-file=/s\n",
            "type=ed25519\n",
            "type=ed25519\nsecret-key-file=\n",
            "type=gpg\ngpg-key=\n",
            "type=ed25519\nsecret-key-file=/s\ngpg-key=A\n",
            "type=gpg\ngpg-key=A\nsecret-key-file=/s\n",
            "type=ed25519\nsecret-key-file=/s\ncertificate-chain-file=/c\n",
            "type=gpg\ngpg-key=A\ncrl-file=/c\n",
            "type=spki\nsecret-key-file=/s\ncertificate-chain-file=\n",
            "type=spki\nsecret-key-file=/s\ncrl-file=\n",
        ] {
            let cfg = config(&format!("[ex-ostrya key \"k\"]\n{keys}"));
            cfg.check().unwrap();
            key_reader_refusal(&cfg);
        }
        // A group name with a control character is a section, and the
        // reader of the client groups refuses it.
        config("[ex-ostrya trust \"a\tb\"]\nsign-verify=ed25519\n[ex-ostrya key \"a\tb\"]\n")
            .check()
            .unwrap();
    }

    /// The closed check of a group refuses an unknown key, and does nothing
    /// for an open group.
    #[test]
    fn the_closed_check_refuses_an_unknown_key() {
        let cfg = config(
            "zzz=1\n[ex-ostrya client \"a\"]\nauth=x\n[ex-ostrya client \"b\"]\nzzz=1\n\
             [ex-ostrya server]\nyyy=1\n",
        );
        cfg.refuse_unknown_keys::<repo::Group>().unwrap();
        cfg.refuse_unknown_keys::<remote::Group>().unwrap();
        assert_eq!(
            cfg.refuse_unknown_keys::<client::Group>()
                .unwrap_err()
                .to_string(),
            "invalid format: [ex-ostrya client \"b\"] holds the unknown key 'zzz'"
        );
        assert_eq!(
            cfg.refuse_unknown_keys::<server::Group>()
                .unwrap_err()
                .to_string(),
            "invalid format: [ex-ostrya server] holds the unknown key 'yyy'"
        );
        let a = cfg.section::<client::Group>("a").unwrap();
        a.refuse_unknown_keys().unwrap();
        let b = cfg.section::<client::Group>("b").unwrap();
        assert_eq!(
            b.refuse_unknown_keys().unwrap_err().to_string(),
            "invalid format: [ex-ostrya client \"b\"] holds the unknown key 'zzz'"
        );
        config("").refuse_unknown_keys::<server::Group>().unwrap();
    }

    #[test]
    fn an_override_does_not_hide_a_bad_value_of_the_file() {
        let mut overrides = Overrides::default();
        overrides.force::<repo::Fsync>(false);
        let cfg = config("fsync=maybe\n").with_overrides(Arc::new(overrides));
        assert!(!cfg.get::<repo::Fsync>().unwrap());
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for core.fsync is not a boolean"
        );
    }

    #[test]
    fn a_bad_value_of_a_remote_of_a_conf_file_is_refused() {
        let cfg = config("[remote \"o\"]\nurl=https://o\n")
            .with_remote_files(
                Path::new("/etc/r.d"),
                vec![RemoteFile {
                    name: "a.conf".to_owned(),
                    keyfile: KeyFile::parse("[remote \"a\"]\ntls-permissive=maybe\n").unwrap(),
                }],
            )
            .unwrap();
        assert_eq!(
            refusal(&cfg),
            "keyfile: value 'maybe' for remote \"a\".tls-permissive is not a boolean"
        );
    }
}

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

    const BASE: &str = "[core]\nrepo_version=1\nmode=archive-z2\n";

    /// Returns the config of `BASE` followed by `text`.
    fn config(text: &str) -> RepoConfig {
        RepoConfig::parse(&format!("{BASE}{text}")).unwrap()
    }

    /// Returns the value text `text`.
    fn value(text: &str) -> TextInEffect {
        TextInEffect::Value(text.to_owned())
    }

    #[test]
    fn each_key_of_each_builtin_group_dispatches() {
        let keyfile = KeyFile::parse(BASE).unwrap();
        type Dispatch = fn(
            &KeyFile,
            &str,
            Option<&Overrides>,
            &str,
        ) -> Option<std::result::Result<Option<String>, ConfigError>>;
        let groups: [(&[&str], &str, Dispatch); 7] = [
            (<repo::Group as Group>::KEYS, "core", repo::text_in_effect),
            (
                <archive::Group as Group>::KEYS,
                "archive",
                archive::text_in_effect,
            ),
            (
                <ex_integrity::Group as Group>::KEYS,
                "ex-integrity",
                ex_integrity::text_in_effect,
            ),
            (
                <ex_ostrya::Group as Group>::KEYS,
                "ex-ostrya",
                ex_ostrya::text_in_effect,
            ),
            (
                <remote::Group as Group>::KEYS,
                "remote \"o\"",
                remote::text_in_effect,
            ),
            (
                <server::Group as Group>::KEYS,
                "ex-ostrya server",
                server::text_in_effect,
            ),
            (
                <client::Group as Group>::KEYS,
                "ex-ostrya client \"c\"",
                client::text_in_effect,
            ),
        ];
        for (keys, header, dispatch) in groups {
            for key in keys {
                assert!(
                    dispatch(&keyfile, header, None, key).is_some(),
                    "[{header}] {key}"
                );
            }
            assert!(
                dispatch(&keyfile, header, None, "zzz").is_none(),
                "{header}"
            );
        }
    }

    #[test]
    fn text_in_effect_applies_the_forced_and_the_fallback_values() {
        let mut overrides = Overrides::default();
        overrides.force::<repo::Fsync>(false);
        overrides.fallback::<repo::TmpExpirySecs>(5);
        overrides.fallback::<archive::ZlibLevel>(9);
        let cfg = config("fsync=true\n").with_overrides(Arc::new(overrides));
        assert_eq!(cfg.text_in_effect("core", "fsync").unwrap(), value("false"));
        assert_eq!(
            cfg.text_in_effect("core", "tmp-expiry-secs").unwrap(),
            value("5")
        );
        assert_eq!(
            cfg.text_in_effect("archive", "zlib-level").unwrap(),
            value("9")
        );
        let cfg = config("fsync=true\ntmp-expiry-secs=7\n");
        assert_eq!(cfg.text_in_effect("core", "fsync").unwrap(), value("true"));
        assert_eq!(
            cfg.text_in_effect("core", "tmp-expiry-secs").unwrap(),
            value("7")
        );
    }

    #[test]
    fn text_in_effect_reads_a_remote_of_a_conf_file() {
        let cfg = config("[remote \"o\"]\nurl=https://o\n")
            .with_remote_files(
                Path::new("/etc/r.d"),
                vec![RemoteFile {
                    name: "a.conf".to_owned(),
                    keyfile: KeyFile::parse("[remote \"a\"]\nurl=https://a\nzzz=1\n").unwrap(),
                }],
            )
            .unwrap();
        assert_eq!(
            cfg.text_in_effect("remote \"a\"", "url").unwrap(),
            value("https://a")
        );
        assert_eq!(
            cfg.text_in_effect("remote \"a\"", "zzz").unwrap(),
            value("1")
        );
        assert_eq!(
            cfg.text_in_effect("remote \"a\"", "gpg-verify").unwrap(),
            value("true")
        );
        assert_eq!(
            cfg.text_in_effect("remote \"a\"", "nope").unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(
            cfg.text_in_effect("remote \"b\"", "url").unwrap(),
            TextInEffect::NoGroup
        );
        assert_eq!(
            cfg.text_in_effect("remote \"o\"", "url").unwrap(),
            value("https://o")
        );
    }

    #[test]
    fn text_in_effect_gives_the_raw_file_text_of_an_unknown_key() {
        let cfg = config(
            "zzz=a\\sb\ncommit-update-summary=maybe\n[ex-debles]\nparallel=many\n\
             [remote \"\"]\nurl=https://e\n",
        );
        assert_eq!(cfg.text_in_effect("core", "zzz").unwrap(), value("a\\sb"));
        assert_eq!(
            cfg.text_in_effect("core", "commit-update-summary").unwrap(),
            value("maybe")
        );
        assert_eq!(
            cfg.text_in_effect("ex-debles", "parallel").unwrap(),
            value("many")
        );
        assert_eq!(
            cfg.text_in_effect("core", "nope").unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(
            cfg.text_in_effect("nope", "x").unwrap(),
            TextInEffect::NoGroup
        );
        assert_eq!(
            cfg.text_in_effect("remote \"\"", "url").unwrap(),
            TextInEffect::NoGroup
        );
        // A known key of a group that the file does not hold.
        assert_eq!(
            cfg.text_in_effect("archive", "zlib-level").unwrap(),
            value("6")
        );
        assert_eq!(
            cfg.text_in_effect("ex-ostrya", "gc-weak-references")
                .unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(
            cfg.text_in_effect("archive", "nope").unwrap(),
            TextInEffect::NoGroup
        );
    }

    #[test]
    fn text_in_effect_reads_the_server_keys() {
        let cfg = config(
            "[ex-ostrya server]\nlisten=127.0.0.1:80\nproxy-protocol=1\n\
             parallel-uploads=04\nsign-summary=b;a;b\nzzz=a\\sb\n",
        );
        let server = "ex-ostrya server";
        assert_eq!(
            cfg.text_in_effect(server, "listen").unwrap(),
            value("127.0.0.1:80;")
        );
        assert_eq!(
            cfg.text_in_effect(server, "proxy-protocol").unwrap(),
            value("true")
        );
        assert_eq!(
            cfg.text_in_effect(server, "parallel-uploads").unwrap(),
            value("4")
        );
        assert_eq!(
            cfg.text_in_effect(server, "sign-summary").unwrap(),
            value("b;a;")
        );
        assert_eq!(
            cfg.text_in_effect(server, "max-sessions").unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(cfg.text_in_effect(server, "zzz").unwrap(), value("a\\sb"));
        assert_eq!(
            cfg.text_in_effect(server, "nope").unwrap(),
            TextInEffect::NoKey
        );
        let cfg = config("[ex-ostrya server]\nmax-sessions=0\n");
        assert_eq!(
            cfg.text_in_effect(server, "max-sessions")
                .unwrap_err()
                .to_string(),
            "invalid format: [ex-ostrya server] max-sessions is 0; the value is a positive \
             integer"
        );
        let cfg = config("");
        assert_eq!(
            cfg.text_in_effect(server, "listen").unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(
            cfg.text_in_effect(server, "zzz").unwrap(),
            TextInEffect::NoGroup
        );
    }

    #[test]
    fn text_in_effect_reads_the_client_keys() {
        let cfg = config(
            "[ex-ostrya client \"c\"]\nauth=ssh:a;anonymous;ssh:a\nallow=r:@a.b:x;wr:y\n\
             deny=@a.b:z\nsummary=1\nsign=b;a;b\nverify=trust:t\nzzz=a\\sb\n\
             [ex-ostrya client \"d\"]\nauth=anonymous\nallow-unsigned=true\nverify=trust:t\n",
        );
        let c = "ex-ostrya client \"c\"";
        let d = "ex-ostrya client \"d\"";
        for (group, key, want) in [
            (c, "auth", value("ssh:a;anonymous;")),
            (c, "allow", value("r:@a.b:x;rw:y;")),
            (c, "deny", value("@a.b:z;")),
            (c, "summary", value("true")),
            (c, "sign", value("b;a;")),
            (c, "verify", value("trust:t")),
            (c, "allow-unsigned", value("false")),
            (c, "tls-accept-claim", value("false")),
            (c, "allow-privileged", value("false")),
            (c, "disable-verify-bindings", value("false")),
            (c, "zzz", value("a\\sb")),
            (c, "nope", TextInEffect::NoKey),
            (d, "allow-unsigned", value("true")),
            (d, "allow", value("")),
            (d, "deny", value("")),
            (d, "sign", TextInEffect::NoKey),
            ("ex-ostrya client \"e\"", "auth", TextInEffect::NoGroup),
            (
                "ex-ostrya client \"anonymous\"",
                "auth",
                TextInEffect::NoGroup,
            ),
        ] {
            assert_eq!(
                cfg.text_in_effect(group, key).unwrap(),
                want,
                "[{group}] {key}"
            );
        }
        let cfg = config("[ex-ostrya client \"c\"]\nallow=x\n");
        let c = "ex-ostrya client \"c\"";
        assert_eq!(cfg.text_in_effect(c, "auth").unwrap(), TextInEffect::NoKey);
        assert_eq!(
            cfg.text_in_effect(c, "verify").unwrap(),
            TextInEffect::NoKey
        );
        assert_eq!(
            cfg.text_in_effect(c, "allow-unsigned").unwrap(),
            value("true")
        );
        let cfg = config("[ex-ostrya client \"c\"]\nverify=off\n");
        assert_eq!(
            cfg.text_in_effect(c, "allow-unsigned")
                .unwrap_err()
                .to_string(),
            "invalid format: malformed [ex-ostrya client \"c\"] verify value 'off': the value \
             is trust:NAME; leave out the key for no verification"
        );
    }

    #[test]
    fn text_in_effect_reads_the_trust_and_key_keys() {
        let cfg = config(
            "[ex-ostrya trust \"t\"]\ngpg-verify=1\ngpgkeypath=k\\s.gpg;\n\
             sign-verify=ed25519;spki\nverification-spki-file=k\\s.pem\nzzz=a\\sb\n\
             [ex-ostrya trust \"u\"]\n\
             [ex-ostrya key \"k\"]\ntype=gpg\ngpg-key=A\\sB\nzzz=1\n\
             [ex-ostrya key \"l\"]\n",
        );
        let t = "ex-ostrya trust \"t\"";
        let u = "ex-ostrya trust \"u\"";
        let k = "ex-ostrya key \"k\"";
        let l = "ex-ostrya key \"l\"";
        for (group, key, want) in [
            (t, "gpg-verify", value("true")),
            (t, "gpgkeypath", value("k\\s.gpg")),
            (t, "sign-verify", value("ed25519;spki;")),
            (t, "verification-spki-file", value("k .pem")),
            (t, "verification-ed25519-key", TextInEffect::NoKey),
            (t, "zzz", value("a\\sb")),
            (t, "nope", TextInEffect::NoKey),
            (u, "gpg-verify", value("false")),
            (u, "sign-verify", value("false")),
            (u, "gpgkeypath", value("")),
            (u, "verification-ed25519-key", TextInEffect::NoKey),
            (u, "verification-ed25519-file", TextInEffect::NoKey),
            (u, "verification-spki-key", TextInEffect::NoKey),
            (u, "verification-spki-file", TextInEffect::NoKey),
            (k, "type", value("gpg")),
            (k, "gpg-key", value("A B")),
            (k, "zzz", value("1")),
            (k, "secret-key-file", TextInEffect::NoKey),
            (k, "certificate-chain-file", TextInEffect::NoKey),
            (k, "crl-file", TextInEffect::NoKey),
            (l, "type", TextInEffect::NoKey),
            (l, "secret-key-file", TextInEffect::NoKey),
            (l, "gpg-key", TextInEffect::NoKey),
            (l, "gpg-homedir", TextInEffect::NoKey),
            ("ex-ostrya trust \"v\"", "gpg-verify", TextInEffect::NoGroup),
            ("ex-ostrya key \"m\"", "type", TextInEffect::NoGroup),
        ] {
            assert_eq!(
                cfg.text_in_effect(group, key).unwrap(),
                want,
                "[{group}] {key}"
            );
        }
        let cfg =
            config("[ex-ostrya trust \"t\"]\ngpg-verify=maybe\n[ex-ostrya key \"k\"]\ntype=rsa\n");
        assert_eq!(
            cfg.text_in_effect(t, "gpg-verify").unwrap_err().to_string(),
            "keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean"
        );
        assert_eq!(
            cfg.text_in_effect(k, "type").unwrap_err().to_string(),
            "invalid format: malformed [ex-ostrya key \"k\"] type value 'rsa': the type is \
             ed25519, spki, or gpg"
        );
    }

    #[test]
    fn text_in_effect_gives_no_group_for_a_trust_or_key_name_that_is_not_a_section_name() {
        let cfg = config(
            "[ex-ostrya trust \"\"]\ngpg-verify=true\nzzz=1\n\
             [ex-ostrya trust \"a\"b\"]\ngpg-verify=true\nzzz=1\n\
             [ex-ostrya key \"\"]\ntype=gpg\nzzz=1\n\
             [ex-ostrya key \"a\"b\"]\ntype=gpg\nzzz=1\n",
        );
        for (group, keys) in [
            ("ex-ostrya trust \"\"", ["gpg-verify", "sign-verify", "zzz"]),
            (
                "ex-ostrya trust \"a\"b\"",
                ["gpg-verify", "gpgkeypath", "zzz"],
            ),
            ("ex-ostrya key \"\"", ["type", "gpg-key", "zzz"]),
            ("ex-ostrya key \"a\"b\"", ["type", "gpg-homedir", "zzz"]),
        ] {
            for key in keys {
                assert_eq!(
                    cfg.text_in_effect(group, key).unwrap(),
                    TextInEffect::NoGroup,
                    "[{group}] {key}"
                );
            }
        }
    }

    #[test]
    fn text_in_effect_gives_no_group_for_a_client_name_that_is_not_a_section_name() {
        let cfg = config(
            "[ex-ostrya client \"\"]\nallow=x\nzzz=1\n\
             [ex-ostrya client \"a\"b\"]\nallow=x\nzzz=1\n",
        );
        for group in ["ex-ostrya client \"\"", "ex-ostrya client \"a\"b\""] {
            for key in ["allow", "allow-privileged", "zzz"] {
                assert_eq!(
                    cfg.text_in_effect(group, key).unwrap(),
                    TextInEffect::NoGroup,
                    "[{group}] {key}"
                );
            }
        }
    }

    #[test]
    fn text_in_effect_reads_the_keys_of_the_methods() {
        let cfg = config(
            "[ex-integrity]\ncomposefs=yes\n[ex-ostrya]\ngc-weak-references=!a;b\n\
             remotes-config-dir=r.d\n\
             [remote \"o\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.C;org.a.C\n\
             [remote \"p\"]\ncollection-id=org.a.B\nmirrored-collection-ids=org.a.B\n\
             [remote \"q\"]\nurl=https://q\n",
        );
        assert_eq!(
            cfg.text_in_effect("ex-integrity", "fsverity").unwrap(),
            value("maybe")
        );
        assert_eq!(
            cfg.text_in_effect("ex-ostrya", "gc-weak-references")
                .unwrap(),
            value("b;!a;")
        );
        assert_eq!(
            cfg.text_in_effect("ex-ostrya", "remotes-config-dir")
                .unwrap(),
            value("r.d")
        );
        assert_eq!(
            cfg.text_in_effect("remote \"o\"", "mirrored-collection-ids")
                .unwrap(),
            value("org.a.C;")
        );
        assert_eq!(
            cfg.text_in_effect("remote \"p\"", "mirrored-collection-ids")
                .unwrap_err()
                .to_string(),
            "invalid format: [remote \"p\"] mirrored-collection-ids holds 'org.a.B', \
             the collection-id of the remote"
        );
        assert_eq!(
            cfg.text_in_effect("remote \"q\"", "mirrored-collection-ids")
                .unwrap(),
            TextInEffect::NoKey
        );
        let cfg = config("[ex-ostrya]\ngc-weak-references=!a\n");
        assert_eq!(
            cfg.text_in_effect("ex-ostrya", "gc-weak-references")
                .unwrap_err()
                .to_string(),
            "invalid format: [ex-ostrya] gc-weak-references: the list holds no pattern without '!'"
        );
    }
}