ostrya 0.12.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
//! The typed view of the repository `config` file.
//!
//! - [`RepoConfig`] reads the keys of the repository groups.
//! - [`Remote`] reads the keys of one `[remote "<name>"]` section, of
//!   `config` or of a `.conf` file of the remotes directory.
//! - [`RemoteSource`] names the file that holds a remote.
//! - [`Repo::write_config`] writes an edited config back to the repository.
//! - [`valid_remote_name`] checks a remote name.

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

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};

const CORE: &str = "core";
const ARCHIVE: &str = "archive";
const EX_INTEGRITY: &str = "ex-integrity";
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";

/// 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`. [`remotes`](RepoConfig::remotes) and
/// [`remote`](RepoConfig::remote) give the remotes of both sources.
/// [`keyfile`](RepoConfig::keyfile) gives `config` alone.
///
/// # Groups
///
/// - `[core]`: `repo_version`, `mode`, and the other tunables, each with its
///   default.
/// - `[archive]`: [`zlib_level`](RepoConfig::zlib_level).
/// - `[ex-integrity]`: [`composefs`](RepoConfig::composefs) and
///   [`fsverity`](RepoConfig::fsverity).
/// - `[remote "<name>"]`: one section for each remote, read through
///   [`Remote`].
/// - `[ex-ostrya]`: the keys that are ostrya extensions,
///   [`keep_detached_related`](RepoConfig::keep_detached_related),
///   [`generate_composefs`](RepoConfig::generate_composefs), and
///   [`gc_weak_references`](RepoConfig::gc_weak_references).
/// - 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]` and the `[ex-ostrya client "NAME"]` groups.
///   Under the `receive` feature, `ReceivePolicies::from_config` also reads
///   the `[ex-ostrya trust "NAME"]` and `[ex-ostrya key "NAME"]` groups.
///
/// # 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 accessor reads its key when it is called. If the key is absent,
/// the accessor returns the default. If the value is malformed, the accessor
/// returns an error, as the `ostree` command reports a value that it cannot
/// read.
#[derive(Debug, Clone)]
pub struct RepoConfig {
    keyfile: KeyFile,
    mode: RepoMode,
    repo_version: i64,
    collection_id: Option<String>,
    remotes: Vec<String>,
    remote_files: Vec<RemoteFile>,
}

/// 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 file that holds a remote.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RemoteSource<'a> {
    /// The `config` file of the repository.
    Config,
    /// A `.conf` file of the remotes directory, by its name in that
    /// directory, for example `origin.conf`.
    File(&'a str),
}

/// 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()),
    }
}

/// Returns `true` if `path` is relative and has a `..` component. A path of
/// a key or of a caller cannot have such a component.
pub(crate) fn relative_with_parent(path: &Path) -> bool {
    path.is_relative() && path.components().any(|c| c == Component::ParentDir)
}

/// 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),
}

/// A `min-free-space-size` value: a magnitude and a unit suffix.
///
/// The `ostree` command accepts the suffixes `MB`, `GB`, and `TB`, with the
/// regex `^([0-9]+)(G|M|T)B$`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SizeSpec {
    /// The numeric magnitude.
    pub value: u64,
    /// The unit suffix.
    pub unit: SizeUnit,
}

/// The unit suffix of a `min-free-space-size` value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeUnit {
    /// `MB`.
    Mega,
    /// `GB`.
    Giga,
    /// `TB`.
    Tera,
}

impl SizeUnit {
    /// Returns the byte multiplier of this unit.
    ///
    /// The suffixes `MB`, `GB`, and `TB` are binary multiples: 2^20, 2^30, and
    /// 2^40.
    pub fn multiplier(self) -> u64 {
        match self {
            SizeUnit::Mega => 1 << 20,
            SizeUnit::Giga => 1 << 30,
            SizeUnit::Tera => 1 << 40,
        }
    }
}

impl SizeSpec {
    /// Returns the value in bytes, or `u64::MAX` if the product overflows.
    pub fn bytes(self) -> u64 {
        self.value.saturating_mul(self.unit.multiplier())
    }
}

/// The value of a `sign-verify` key: the engines that verify signatures.
///
/// The value is a boolean in the key-file spelling (`true`, `false`, `1`,
/// `0`), or a list of engine names. A `,` or a `;` separates the names.
///
/// Each name is used as written. In `ed25519, ed25519`, the second name starts
/// with a space, so no engine has that name. The `ostree` command also refuses
/// this value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignVerify {
    /// No sign-api verification: the key is absent, `false`, or names no
    /// engine.
    Off,
    /// Every engine of this build, selected by `true`.
    All,
    /// The engines that the value names, in the order of the value.
    Engines(Vec<String>),
}

/// A tri-state repository setting: `no`, `maybe`, or `yes`.
///
/// The `[ex-integrity]` keys use this form.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tristate {
    /// The feature is off.
    No,
    /// Best effort: on where the file system supports the feature.
    ///
    /// Where the file system cannot provide the feature, the operation ignores
    /// it.
    Maybe,
    /// Required: the operation fails where the file system cannot provide it.
    Yes,
}

impl Tristate {
    /// Parses the `no`, `maybe`, or `yes` spelling that the `ostree` command
    /// writes.
    fn parse(raw: &str) -> Option<Tristate> {
        match raw {
            "no" => Some(Tristate::No),
            "maybe" => Some(Tristate::Maybe),
            "yes" => Some(Tristate::Yes),
            _ => None,
        }
    }
}

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")?;

        // A repeated group header merges into one group during parsing, so
        // each remote name appears once already.
        let remotes: Vec<String> = keyfile
            .groups()
            .filter_map(remote_group_name)
            .map(str::to_owned)
            .collect();

        Ok(RepoConfig {
            keyfile,
            mode,
            repo_version,
            collection_id,
            remotes,
            remote_files: Vec::new(),
        })
    }

    /// 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> {
        let mut seen: HashMap<String, Option<usize>> = self
            .remotes
            .iter()
            .map(|name| (name.clone(), None))
            .collect();
        for (index, file) in files.iter().enumerate() {
            // A repeated group header merges into one group during parsing,
            // so one file gives each name once.
            for name in file.keyfile.groups().filter_map(remote_group_name) {
                if let Some(other) = seen.insert(name.to_owned(), 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.remotes.push(name.to_owned());
            }
        }
        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 names of the remotes.
    ///
    /// The names of `config` come first, in the order of their sections.
    /// Then come the names of each `.conf` file of the remotes directory, in
    /// the byte order of the file names, and in the order of the sections of
    /// each file.
    pub fn remotes(&self) -> impl Iterator<Item = &str> {
        self.remotes.iter().map(String::as_str)
    }

    /// Returns the accessor of one remote, or `None` if no source has its
    /// section.
    ///
    /// [`Remote::source`] gives the file that holds the section.
    pub fn remote(&self, name: &str) -> Option<Remote<'_>> {
        let group = remote_group(name);
        let (keyfile, source) = if self.keyfile.has_group(&group) {
            (&self.keyfile, RemoteSource::Config)
        } else {
            let file = self
                .remote_files
                .iter()
                .find(|file| file.keyfile.has_group(&group))?;
            (&file.keyfile, RemoteSource::File(&file.name))
        };
        Some(Remote {
            keyfile,
            group,
            source,
        })
    }

    /// 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 `true` if `[core] add-remotes-config-dir` lets an add write a
    /// new remote into the remotes directory.
    ///
    /// The default is `true`. The key has an effect only for a handle with a
    /// remotes directory.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub(crate) fn add_remotes_config_dir(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "add-remotes-config-dir")?
            .unwrap_or(true))
    }

    /// Returns `true` if `[core] fsync` is on.
    ///
    /// The default is `true`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn fsync(&self) -> Result<bool> {
        Ok(self.keyfile.get_bool(CORE, "fsync")?.unwrap_or(true))
    }

    /// Returns `true` if each content object file is synced when it is staged.
    ///
    /// The key is `[core] per-object-fsync`, and the default is `false`. A
    /// metadata object is not synced alone.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn per_object_fsync(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "per-object-fsync")?
            .unwrap_or(false))
    }

    /// Returns `true` if `[core] locking` turns on the repository lock.
    ///
    /// The default is `true`. [`LockKind`](crate::LockKind) describes the
    /// repository lock.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn locking(&self) -> Result<bool> {
        Ok(self.keyfile.get_bool(CORE, "locking")?.unwrap_or(true))
    }

    /// Returns the `[core] lock-timeout-secs` limit of a lock wait, in seconds.
    ///
    /// The default is `300`. The value `-1` means no limit.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is less than `-1`.
    /// - [`Error::Core`] if the value is not an integer.
    pub fn lock_timeout_secs(&self) -> Result<i64> {
        let secs = self
            .keyfile
            .get_integer(CORE, "lock-timeout-secs")?
            .unwrap_or(300);
        if secs < -1 {
            return Err(Error::InvalidFormat(format!(
                "lock-timeout-secs {secs} is below -1"
            )));
        }
        Ok(secs)
    }

    /// Returns the `[core] tmp-expiry-secs` expiry of a stale entry in `tmp/`,
    /// in seconds.
    ///
    /// The default is `86400`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not an integer.
    pub fn tmp_expiry_secs(&self) -> Result<i64> {
        Ok(self
            .keyfile
            .get_integer(CORE, "tmp-expiry-secs")?
            .unwrap_or(86400))
    }

    /// Returns `true` if the summary announces tombstone commits.
    ///
    /// The key is `[core] tombstone-commits`, and the default is `false`. The
    /// summary writes this value as `ostree.summary.tombstone-commits`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn tombstone_commits(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "tombstone-commits")?
            .unwrap_or(false))
    }

    /// Returns `true` if the repository indexes its static deltas.
    ///
    /// The key is `[core] indexed-deltas`, and the default is `true`. A
    /// summary that names deltas writes this value as
    /// `ostree.summary.indexed-deltas`: the root summary, and in an `archive`
    /// repository the summary of each auth item
    /// ([`Repo::regenerate_summaries`](crate::Repo::regenerate_summaries),
    /// "Static deltas").
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn indexed_deltas(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "indexed-deltas")?
            .unwrap_or(true))
    }

    /// Returns `true` if `[core] disable-xattrs` turns off xattr storage.
    ///
    /// The default is `false`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn disable_xattrs(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(CORE, "disable-xattrs")?
            .unwrap_or(false))
    }

    /// Returns the `[core] parent` repository path, if it is set.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn parent(&self) -> Result<Option<String>> {
        self.keyfile.get_string(CORE, "parent").map_err(Error::from)
    }

    /// Returns the `[core] default-repo-finders` list.
    ///
    /// The default is `["config", "mount"]`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn default_repo_finders(&self) -> Result<Vec<String>> {
        Ok(self
            .keyfile
            .get_string_list(CORE, "default-repo-finders")?
            .unwrap_or_else(|| vec!["config".to_owned(), "mount".to_owned()]))
    }

    /// Returns the minimum free space that a write must leave.
    ///
    /// If `[core] min-free-space-size` is set, it applies. If it is not set,
    /// `[core] min-free-space-percent` 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(raw) = self.keyfile.get_value(CORE, "min-free-space-size") {
            let spec = parse_size(raw).ok_or_else(|| {
                Error::InvalidFormat(format!("malformed min-free-space-size '{raw}'"))
            })?;
            return Ok(MinFreeSpace::Size(spec));
        }
        let percent = self
            .keyfile
            .get_integer(CORE, "min-free-space-percent")?
            .unwrap_or(3);
        if !(0..=100).contains(&percent) {
            return Err(Error::InvalidFormat(format!(
                "min-free-space-percent {percent} is out of the range 0-100"
            )));
        }
        Ok(MinFreeSpace::Percent(percent as u32))
    }

    /// Returns the `[archive] zlib-level` compression level.
    ///
    /// The default is `6`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not an integer.
    pub fn zlib_level(&self) -> Result<i64> {
        Ok(self
            .keyfile
            .get_integer(ARCHIVE, "zlib-level")?
            .unwrap_or(6))
    }

    /// Returns `true` if a transfer into this repository stores
    /// `ostrya.related`.
    ///
    /// The key is `[ex-ostrya] keep-detached-related`, and the default is
    /// `true`. The key is an ostrya extension. If it 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_detached_related`] 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn keep_detached_related(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(EX_OSTRYA, "keep-detached-related")?
            .unwrap_or(true))
    }

    /// Returns `true` if the commit of a transaction builds the composefs
    /// image of each complete commit that it writes.
    ///
    /// The key is `[ex-ostrya] generate-composefs`, and the default is
    /// `false`. The key is an ostrya extension. If it is `true`, the commit of
    /// a transaction builds, checks, and stores the image of each commit that
    /// the writer records as complete and that carries
    /// `ostree.composefs.digest.v0`. [`Transaction::commit`] states the rule.
    /// A commit that the repository holds complete before the transaction gets
    /// no image from it.
    ///
    /// [`Repo::transaction`] reads the key before it takes the lock, so a bad
    /// value fails the open of each transaction. [`Repo::pull`],
    /// [`Repo::pull_with_session`], and [`Repo::pull_collection`] also read
    /// the key at their start, before the first request. [`Repo::fsck`] reads
    /// the key at its start.
    ///
    /// # Errors
    ///
    /// - [`Error::Core`] if the value is not a boolean.
    /// - [`Error::Unsupported`] if the value is `true` and the repository mode
    ///   is `archive`.
    ///
    /// [`Transaction::commit`]: crate::Transaction::commit
    pub fn generate_composefs(&self) -> Result<bool> {
        let on = self
            .keyfile
            .get_bool(EX_OSTRYA, "generate-composefs")?
            .unwrap_or(false);
        if on && self.mode.is_archive() {
            return Err(Error::Unsupported(
                "[ex-ostrya] generate-composefs=true in an archive repository".into(),
            ));
        }
        Ok(on)
    }

    /// 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>> {
        let selector = read_selector(&self.keyfile, EX_OSTRYA, "gc-weak-references")?;
        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 `true` if a ref change regenerates the summary.
    ///
    /// The keys are `[core] auto-update-summary` and its deprecated alias
    /// `commit-update-summary`. The default is `false`.
    ///
    /// The call reads the two keys together. If either key is true, the
    /// regeneration is on. An observation of the `ostree` command shows the
    /// same rule: with one key true and the other false, in either order,
    /// `ostree commit` writes a summary.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if either key is not a boolean, also when the other key
    /// is true. The `ostree` command also refuses this value.
    pub fn auto_update_summary(&self) -> Result<bool> {
        let canonical = self.keyfile.get_bool(CORE, "auto-update-summary")?;
        let alias = self.keyfile.get_bool(CORE, "commit-update-summary")?;
        Ok(canonical.unwrap_or(false) || alias.unwrap_or(false))
    }

    /// Returns the `[ex-integrity] composefs` setting.
    ///
    /// The default is [`Tristate::No`]. The setting sets the default of
    /// [`fsverity`](RepoConfig::fsverity). The write path does not use the
    /// composefs deployment behavior that the key also controls.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is not `no`, `maybe`, or `yes`.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn composefs(&self) -> Result<Tristate> {
        Ok(self
            .tristate(EX_INTEGRITY, "composefs")?
            .unwrap_or(Tristate::No))
    }

    /// Returns the `[ex-integrity] fsverity` setting.
    ///
    /// The setting controls the fs-verity seal of the loose objects:
    ///
    /// - `maybe` or `yes`: each loose object that the object store holds as a
    ///   regular file gets a seal at staging, in every repository mode.
    /// - `yes`: if a seal fails, the write fails with [`Error::Unsupported`].
    /// - `maybe`: the write ignores a seal that fails.
    ///
    /// An explicit value applies as written. If the key is absent, the default
    /// is `No`. If the key is absent and [`composefs`](RepoConfig::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 errors of
    ///   [`composefs`](RepoConfig::composefs).
    pub fn fsverity(&self) -> Result<Tristate> {
        if let Some(explicit) = self.tristate(EX_INTEGRITY, "fsverity")? {
            return Ok(explicit);
        }
        Ok(match self.composefs()? {
            Tristate::No => Tristate::No,
            Tristate::Maybe | Tristate::Yes => Tristate::Maybe,
        })
    }

    /// Reads a tri-state key. Returns `None` if the key is absent. A value
    /// other than `no`, `maybe`, or `yes` is a malformed config error.
    fn tristate(&self, group: &str, key: &str) -> Result<Option<Tristate>> {
        match self.keyfile.get_string(group, key)? {
            None => Ok(None),
            Some(raw) => Tristate::parse(&raw).map(Some).ok_or_else(|| {
                Error::InvalidFormat(format!("malformed [{group}] {key} value '{raw}'"))
            }),
        }
    }

    /// 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
    }
}

/// 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. 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().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().fsync()?;
        self.write_locked(move |repo| {
            repo.root_dir().remove_file(&name, fsync)?;
            Ok(())
        })
        .await
    }
}

/// 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")
}

/// A typed accessor for one `[remote "<name>"]` section.
///
/// A trust group, `[ex-ostrya trust "NAME"]`, takes the key names of a remote
/// section. A pull from a remote with the key [`trust`](Remote::trust), a pull
/// with [`PullOptions::trust_group`](crate::PullOptions::trust_group), and the
/// receive side read a trust group through this type.
///
/// # Paths
///
/// The keys `gpgkeypath`, `verification-ENGINE-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.
///
/// The accessor 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 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.
#[derive(Debug, Clone)]
pub struct Remote<'a> {
    keyfile: &'a KeyFile,
    group: String,
    source: RemoteSource<'a>,
}

impl<'a> Remote<'a> {
    /// Returns the accessors of a remote section over another group of
    /// `keyfile`. The group takes the key names and the value forms of a
    /// remote section.
    pub(crate) fn view(keyfile: &'a KeyFile, group: String) -> Remote<'a> {
        Remote {
            keyfile,
            group,
            source: RemoteSource::Config,
        }
    }

    /// Returns the file that holds the section: `config`, or a `.conf` file
    /// of the remotes directory.
    pub fn source(&self) -> RemoteSource<'a> {
        self.source
    }
}

impl Remote<'_> {
    /// Returns the `url` key: the base URL of the objects and the refs.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn url(&self) -> Result<Option<String>> {
        self.string("url")
    }

    /// Returns the `contenturl` key: the URL of the content objects.
    ///
    /// A remote sets this key if the URL differs from `url`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn contenturl(&self) -> Result<Option<String>> {
        self.string("contenturl")
    }

    /// Returns the `metalink` key: the URL of a metalink for this remote.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn metalink(&self) -> Result<Option<String>> {
        self.string("metalink")
    }

    /// Returns `true` if a pull verifies the GPG signatures of commits.
    ///
    /// The key is `gpg-verify`, and the default is `true`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn gpg_verify(&self) -> Result<bool> {
        Ok(self.gpg_verify_key()?.unwrap_or(true))
    }

    /// Returns the value of the `gpg-verify` key, or `None` if the key is
    /// absent.
    pub(crate) fn gpg_verify_key(&self) -> Result<Option<bool>> {
        Ok(self.keyfile.get_bool(&self.group, "gpg-verify")?)
    }

    /// Returns `true` if a pull verifies the GPG signature of the summary.
    ///
    /// The key is `gpg-verify-summary`, and the default is `false`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn gpg_verify_summary(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(&self.group, "gpg-verify-summary")?
            .unwrap_or(false))
    }

    /// Returns the `gpgkeypath` entries: 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 call reads 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 call
    /// removes one empty entry at the end of the list and keeps each other
    /// empty entry, so an empty value gives one empty entry. If the key is
    /// absent, the list is empty.
    ///
    /// Each entry is a keyring file or a directory of keyring files, by the
    /// rules of [`Remote#paths`]. 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.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if an entry is a relative path with a `..`
    /// component.
    pub fn gpgkeypath(&self) -> Result<Vec<String>> {
        let Some(raw) = self.get("gpgkeypath") else {
            return Ok(Vec::new());
        };
        let mut entries: Vec<String> = raw.split(';').map(str::to_owned).collect();
        if entries.len() > 1 && entries.last().is_some_and(String::is_empty) {
            entries.pop();
        }
        for entry in &entries {
            self.check_path("gpgkeypath", entry)?;
        }
        Ok(entries)
    }

    /// Returns the `gpgkeypath` entries of [`gpgkeypath`](Remote::gpgkeypath)
    /// as paths with the source of the section.
    #[cfg(feature = "verify-gpg")]
    pub(crate) fn gpgkeypath_paths(&self) -> Result<Vec<KeyPath>> {
        Ok(self
            .gpgkeypath()?
            .into_iter()
            .map(|entry| self.key_path_of(entry))
            .collect())
    }

    /// Returns the path that the key `key` names, with the source of the
    /// section, or `None` if the key is absent. The call refuses a value as
    /// [`path_string`](Remote::path_string) does.
    pub(crate) fn key_path(&self, key: &str) -> Result<Option<KeyPath>> {
        Ok(self.path_string(key)?.map(|value| self.key_path_of(value)))
    }

    /// Returns `value`, a path of a key of this section, with the source of
    /// the section.
    fn key_path_of(&self, value: String) -> KeyPath {
        KeyPath {
            value: PathBuf::from(value),
            origin: match self.source {
                RemoteSource::Config => KeyOrigin::Config,
                RemoteSource::File(_) => KeyOrigin::RemotesFile,
            },
        }
    }

    /// Returns the sign-api engines that verify the commits of this remote.
    ///
    /// The key is `sign-verify`, and the default is [`SignVerify::Off`].
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn sign_verify(&self) -> Result<SignVerify> {
        Ok(parse_sign_verify(self.string("sign-verify")?.as_deref()))
    }

    /// Returns the sign-api engines that verify the summary of this remote.
    ///
    /// The key is `sign-verify-summary`, and the default is
    /// [`SignVerify::Off`]. The call reads this key alone. `sign-verify=false`
    /// does not turn off a summary verification that this key asks for.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn sign_verify_summary(&self) -> Result<SignVerify> {
        Ok(parse_sign_verify(
            self.string("sign-verify-summary")?.as_deref(),
        ))
    }

    /// Returns the inline trusted key of one sign-api engine.
    ///
    /// The key is `verification-<engine>-key`. It holds exactly one key.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn verification_key(&self, engine: &str) -> Result<Option<String>> {
        self.string(&format!("verification-{engine}-key"))
    }

    /// Returns the path of a file of trusted keys for one sign-api engine.
    ///
    /// The key is `verification-<engine>-file`. The form of the file depends
    /// on the engine:
    ///
    /// - `ed25519`: the file holds one base64 key on each line.
    /// - `spki`: the file holds PEM `PUBLIC KEY` blocks.
    ///
    /// A pull and the receive side read the path by the rules of
    /// [`Remote#paths`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is a relative path with a `..`
    ///   component.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn verification_file(&self, engine: &str) -> Result<Option<String>> {
        self.path_string(&format!("verification-{engine}-file"))
    }

    /// Returns the `trust` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn trust(&self) -> Result<Option<String>> {
        self.string("trust")
    }

    /// Returns the `collection-id` of this remote, if it is set.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn collection_id(&self) -> Result<Option<String>> {
        self.string("collection-id")
    }

    /// Returns the `mirrored-collection-ids` key: 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 absent key gives an empty list. An id that occurs
    /// again counts one time. The key is an ostrya extension.
    ///
    /// # Errors
    ///
    /// - [`Error::Core`] if the value of the key or of `collection-id` holds
    ///   a malformed escape sequence.
    /// - The errors of [`check_mirrored_collection_ids`], with the
    ///   `collection-id` of this remote.
    pub fn mirrored_collection_ids(&self) -> Result<Vec<String>> {
        let Some(ids) = self
            .keyfile
            .get_string_list(&self.group, MIRRORED_COLLECTION_IDS)?
        else {
            return Ok(Vec::new());
        };
        check_mirrored_collection_ids(self.collection_id()?.as_deref(), ids)
    }

    /// Returns the `branches` key: the refs of a pull that names no ref.
    ///
    /// A pull with no ref also takes the refs of the summary that the key
    /// `pull-branches` selects. [`pull_branches`](Remote::pull_branches)
    /// states the rules of the two keys together.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn branches(&self) -> Result<Option<Vec<String>>> {
        self.keyfile
            .get_string_list(&self.group, "branches")
            .map_err(Error::from)
    }

    /// Returns the selector of the summary refs that a pull with no ref
    /// takes, or `None` if the key is absent.
    ///
    /// The key is `pull-branches`, 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.
    /// - `@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`](Remote::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.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if an entry is not a valid ref pattern. The
    ///   text names the section, the key, and the entry.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn pull_branches(&self) -> Result<Option<ReceiveSelector>> {
        read_selector(self.keyfile, &self.group, "pull-branches")
    }

    /// Returns the `tls-ca-path` key: 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 [`Remote#paths`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is a relative path with a `..`
    ///   component.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_ca_path(&self) -> Result<Option<String>> {
        self.path_string("tls-ca-path")
    }

    /// Returns the `tls-client-cert-path` key: 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 [`Remote#paths`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is a relative path with a `..`
    ///   component.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_client_cert_path(&self) -> Result<Option<String>> {
        self.path_string("tls-client-cert-path")
    }

    /// Returns the `tls-client-key-path` key: the PEM private key of the
    /// client.
    ///
    /// The key belongs to the chain of
    /// [`tls_client_cert_path`](Remote::tls_client_cert_path). A pull and a
    /// push read the path by the rules of [`Remote#paths`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is a relative path with a `..`
    ///   component.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_client_key_path(&self) -> Result<Option<String>> {
        self.path_string("tls-client-key-path")
    }

    /// Returns `true` if `tls-permissive` turns off the TLS chain verification.
    ///
    /// 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value is not a boolean.
    pub fn tls_permissive(&self) -> Result<bool> {
        Ok(self
            .keyfile
            .get_bool(&self.group, "tls-permissive")?
            .unwrap_or(false))
    }

    /// Returns the `push-url` key: the push address of this remote.
    ///
    /// If the key is absent and `url` is an `http://` or an `https://` URL, a
    /// push uses `url`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn push_url(&self) -> Result<Option<String>> {
        self.string("push-url")
    }

    /// Returns the selector of the refs that a push with no refspec sends, or
    /// `None` if the key is absent.
    ///
    /// The key is `push-branches`, 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.
    /// - `@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.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if an entry is not a valid ref pattern. The
    ///   text names the section, the key, and the entry.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn push_branches(&self) -> Result<Option<ReceiveSelector>> {
        read_selector(self.keyfile, &self.group, "push-branches")
    }

    /// Returns the `ssh-command` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn ssh_command(&self) -> Result<Option<String>> {
        self.string("ssh-command")
    }

    /// Returns the `receive-command` key: the remote command of a push.
    ///
    /// The remote side of a push to this remote runs this command. The remote
    /// shell parses it.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn receive_command(&self) -> Result<Option<String>> {
        self.string("receive-command")
    }

    /// Returns the `push-token-file` key: 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 [`Remote#paths`].
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if the value is a relative path with a `..`
    ///   component.
    /// - [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn push_token_file(&self) -> Result<Option<String>> {
        self.path_string("push-token-file")
    }

    /// Returns the `push-user` key: the Basic credential name of an HTTP push.
    ///
    /// The token of [`push_token_file`](Remote::push_token_file) is the
    /// password. If the key is absent, the push sends the token as a bearer
    /// token.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn push_user(&self) -> Result<Option<String>> {
        self.string("push-user")
    }

    /// Returns the `pull-url` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn pull_url(&self) -> Result<Option<String>> {
        self.string("pull-url")
    }

    /// Returns the `s3-region` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn s3_region(&self) -> Result<Option<String>> {
        self.string("s3-region")
    }

    /// Returns the `s3-endpoint` key: the `http://` or `https://` URL of the
    /// S3 server of the `s3://` address of this remote.
    ///
    /// The key is an ostrya extension.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn s3_endpoint(&self) -> Result<Option<String>> {
        self.string("s3-endpoint")
    }

    /// Returns the `s3-addressing` key: the addressing style of the bucket of
    /// the `s3://` address of this remote, `path` or `virtual`.
    ///
    /// The key is an ostrya extension. The call returns the value as written.
    /// A pull refuses each other value.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn s3_addressing(&self) -> Result<Option<String>> {
        self.string("s3-addressing")
    }

    /// Returns the `s3-profile` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn s3_profile(&self) -> Result<Option<String>> {
        self.string("s3-profile")
    }

    /// Returns the `send-command` key: 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn send_command(&self) -> Result<Option<String>> {
        self.string("send-command")
    }

    /// Returns the `proxy` key: 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 call 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn proxy(&self) -> Result<Option<String>> {
        self.string("proxy")
    }

    /// Returns the raw value of any key in this remote section.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.keyfile.get_value(&self.group, key)
    }

    /// Returns the names of the keys of this section, in file order.
    pub(crate) fn keys(&self) -> impl Iterator<Item = &str> {
        self.keyfile.keys(&self.group)
    }

    fn string(&self, key: &str) -> Result<Option<String>> {
        self.keyfile
            .get_string(&self.group, key)
            .map_err(Error::from)
    }

    /// Returns the value of the key `key`, which names a path. The call
    /// refuses a relative path with a `..` component with
    /// [`Error::InvalidFormat`].
    fn path_string(&self, key: &str) -> Result<Option<String>> {
        let value = self.string(key)?;
        if let Some(value) = &value {
            self.check_path(key, value)?;
        }
        Ok(value)
    }

    /// Refuses `value`, a path of the key `key`, if it is a relative path with
    /// a `..` component.
    fn check_path(&self, key: &str, value: &str) -> Result<()> {
        if relative_with_parent(Path::new(value)) {
            return Err(Error::InvalidFormat(format!(
                "[{}] {key} {value} has a `..` component, which a relative path in a config \
                 cannot have",
                self.group
            )));
        }
        Ok(())
    }
}

/// Reads a `sign-verify` or `sign-verify-summary` value. The value is a
/// boolean in the key-file spelling, or a list of engine names that `,` or `;`
/// separates.
fn parse_sign_verify(raw: Option<&str>) -> SignVerify {
    let Some(raw) = raw else {
        return SignVerify::Off;
    };
    match raw {
        "true" | "1" => return SignVerify::All,
        "false" | "0" => return SignVerify::Off,
        _ => {}
    }
    let engines: Vec<String> = raw
        .split([',', ';'])
        .filter(|name| !name.is_empty())
        .map(str::to_owned)
        .collect();
    if engines.is_empty() {
        return SignVerify::Off;
    }
    SignVerify::Engines(engines)
}

/// The key of a remote that lists the collections that it mirrors.
const MIRRORED_COLLECTION_IDS: &str = "mirrored-collection-ids";

/// Checks the ids `ids` of a `mirrored-collection-ids` value of a remote
/// whose `collection-id` is `own`, and returns them in order, with each id
/// that occurs again removed.
///
/// # Errors
///
/// [`Error::InvalidFormat`] if `ids` is empty, if an id fails the
/// collection-id rule ([`is_collection_id`](crate::is_collection_id)) or is
/// longer than 255 bytes, or if an id is `own`.
pub fn check_mirrored_collection_ids(own: Option<&str>, ids: Vec<String>) -> Result<Vec<String>> {
    if ids.is_empty() {
        return Err(Error::InvalidFormat(format!(
            "{MIRRORED_COLLECTION_IDS} holds no collection id"
        )));
    }
    let mut out: Vec<String> = Vec::with_capacity(ids.len());
    for id in ids {
        if !ostrya_core::is_valid_collection_id(&id) {
            return Err(Error::InvalidFormat(format!(
                "{MIRRORED_COLLECTION_IDS}: invalid collection id: '{id}'"
            )));
        }
        if Some(id.as_str()) == own {
            return Err(Error::InvalidFormat(format!(
                "{MIRRORED_COLLECTION_IDS}: {id} is the collection-id of the remote"
            )));
        }
        if !out.contains(&id) {
            out.push(id);
        }
    }
    Ok(out)
}

/// Reads the `;` list of ref patterns of `[group] key`, or `None` if the key
/// is absent. The error text of a bad entry names the group and the key.
fn read_selector(keyfile: &KeyFile, group: &str, key: &str) -> Result<Option<ReceiveSelector>> {
    let Some(entries) = keyfile.get_string_list(group, key)? else {
        return Ok(None);
    };
    ReceiveSelector::parse(entries.iter().map(String::as_str))
        .map(Some)
        .map_err(|err| match err {
            Error::InvalidFormat(m) => Error::InvalidFormat(format!("[{group}] {key}: {m}")),
            other => other,
        })
}

/// 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('"'))
}

/// Parses a `min-free-space-size` value with the pattern `^([0-9]+)(G|M|T)B$`.
fn parse_size(raw: &str) -> Option<SizeSpec> {
    let digits = raw
        .strip_suffix("MB")
        .map(|d| (d, SizeUnit::Mega))
        .or_else(|| {
            raw.strip_suffix("GB")
                .map(|d| (d, SizeUnit::Giga))
                .or_else(|| raw.strip_suffix("TB").map(|d| (d, SizeUnit::Tera)))
        });
    let (digits, unit) = digits?;
    if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    let value = digits.parse::<u64>().ok()?;
    Some(SizeSpec { value, unit })
}

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

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

    #[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!(cfg.remotes().count(), 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.fsync().unwrap());
        assert!(!cfg.per_object_fsync().unwrap());
        assert!(cfg.locking().unwrap());
        assert_eq!(cfg.lock_timeout_secs().unwrap(), 300);
        assert_eq!(cfg.tmp_expiry_secs().unwrap(), 86400);
        assert!(!cfg.disable_xattrs().unwrap());
        assert_eq!(cfg.parent().unwrap(), None);
        assert_eq!(
            cfg.default_repo_finders().unwrap(),
            vec!["config".to_owned(), "mount".to_owned()]
        );
        assert_eq!(cfg.zlib_level().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.fsync().unwrap());
        assert!(cfg.per_object_fsync().unwrap());
        assert_eq!(cfg.lock_timeout_secs().unwrap(), 30);
        assert_eq!(cfg.min_free_space().unwrap(), MinFreeSpace::Percent(5));
        assert_eq!(cfg.zlib_level().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()
        };
        assert_eq!(with("-1").lock_timeout_secs().unwrap(), -1);
        assert_eq!(with("0").lock_timeout_secs().unwrap(), 0);
        let err = with("-2").lock_timeout_secs().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.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 min_free_space_size_units_and_rejection() {
        for (raw, unit) in [
            ("500MB", SizeUnit::Mega),
            ("1GB", SizeUnit::Giga),
            ("3TB", SizeUnit::Tera),
        ] {
            assert_eq!(parse_size(raw).unwrap().unit, unit);
        }
        for bad in ["1G", "GB", "1KB", "1gb", "1GB ", "", "1.5GB"] {
            assert!(parse_size(bad).is_none(), "should reject {bad:?}");
        }
    }

    #[test]
    fn ex_integrity_defaults_off() {
        let cfg = RepoConfig::parse(ARCHIVE_CONFIG).unwrap();
        assert_eq!(cfg.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.keep_detached_related().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()
            .keep_detached_related()
        };
        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 generate_composefs_is_false_when_absent() {
        let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n").unwrap();
        assert!(!cfg.generate_composefs().unwrap());
    }

    #[test]
    fn generate_composefs_reads_a_boolean() {
        let read = |mode: &str, value: &str| {
            RepoConfig::parse(&format!(
                "[core]\nrepo_version=1\nmode={mode}\n[ex-ostrya]\n\
                 generate-composefs={value}\n"
            ))
            .unwrap()
            .generate_composefs()
        };
        assert!(!read("bare", "false").unwrap());
        assert!(read("bare", "true").unwrap());
        assert!(read("bare-user", "1").unwrap());
        assert!(matches!(read("bare", "maybe"), Err(Error::Core(_))));
        assert!(!read("archive", "false").unwrap());
        assert!(matches!(
            read("archive", "true"),
            Err(Error::Unsupported(_))
        ));
    }

    #[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.remote("origin").unwrap();
        assert!(origin.push_branches().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()
            .remote("origin")
            .unwrap()
            .push_branches()
        };
        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, Error::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.remote("origin").unwrap();
        assert!(origin.pull_branches().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()
            .remote("origin")
            .unwrap()
            .pull_branches()
        };
        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, Error::InvalidFormat(m)
                if m.contains("[remote \"origin\"] pull-branches")
                    && m.contains("malformed receive pattern")),
            "{err}"
        );
    }

    /// Summary regeneration is off by default, each key alone turns it on, and
    /// either key true wins over the other key false.
    #[test]
    fn auto_update_summary_reads_both_keys() {
        let read = |extra: &str| {
            RepoConfig::parse(&format!("[core]\nrepo_version=1\nmode=archive\n{extra}"))
                .unwrap()
                .auto_update_summary()
        };
        assert!(!read("").unwrap());
        assert!(read("auto-update-summary=true\n").unwrap());
        assert!(read("commit-update-summary=1\n").unwrap());
        assert!(!read("auto-update-summary=false\ncommit-update-summary=0\n").unwrap());
        assert!(read("auto-update-summary=true\ncommit-update-summary=false\n").unwrap());
        assert!(read("auto-update-summary=false\ncommit-update-summary=true\n").unwrap());
    }

    /// A malformed value in either key is an error, also when the other key is
    /// true.
    #[test]
    fn a_malformed_auto_update_summary_is_an_error() {
        for extra in [
            "auto-update-summary=yes\n",
            "commit-update-summary=yes\n",
            "auto-update-summary=true\ncommit-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.auto_update_summary(),
                    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!(cfg.remotes().collect::<Vec<_>>(), ["origin", "withkey"]);

        let origin = cfg.remote("origin").unwrap();
        assert_eq!(
            origin.url().unwrap().as_deref(),
            Some("https://example.com/repo")
        );
        assert!(!origin.gpg_verify().unwrap());
        assert!(!origin.gpg_verify_summary().unwrap());
        assert_eq!(origin.get("branches"), Some("main;"));
        assert_eq!(origin.branches().unwrap(), Some(vec!["main".to_owned()]));
        assert!(!origin.tls_permissive().unwrap());
        assert_eq!(origin.tls_ca_path().unwrap(), None);

        let withkey = cfg.remote("withkey").unwrap();
        assert!(withkey.gpg_verify().unwrap()); // default true
        assert_eq!(
            withkey.collection_id().unwrap().as_deref(),
            Some("org.ex.C")
        );

        assert!(cfg.remote("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!(cfg.remotes().collect::<Vec<_>>(), ["origin", "z", "y", "x"]);
        assert_eq!(
            cfg.remote("y").unwrap().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.remote("origin").unwrap().source(), RemoteSource::Config);
        assert_eq!(
            cfg.remote("z").unwrap().source(),
            RemoteSource::File("a.conf")
        );
        assert_eq!(
            cfg.remote("x").unwrap().source(),
            RemoteSource::File("b.conf")
        );
        assert!(cfg.remote("absent").is_none());
    }

    #[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!(cfg.remotes().collect::<Vec<_>>(), ["x"]);
        let remote = cfg.remote("x").unwrap();
        assert_eq!(remote.url().unwrap().as_deref(), Some("https://2"));
        assert_eq!(remote.keys().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!(cfg.remotes().collect::<Vec<_>>(), ["x"]);
        assert!(cfg.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());
    }

    /// 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.remote("signed").unwrap();
        assert_eq!(
            remote.sign_verify().unwrap(),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        assert_eq!(remote.sign_verify_summary().unwrap(), SignVerify::All);
        assert_eq!(
            remote.verification_key("ed25519").unwrap().as_deref(),
            Some("AAAA")
        );
        assert_eq!(
            remote.verification_file("ed25519").unwrap().as_deref(),
            Some("/etc/keys.ed25519")
        );
        assert_eq!(remote.verification_key("spki").unwrap(), None);
        assert_eq!(
            remote.gpgkeypath().unwrap(),
            vec!["/etc/one.gpg".to_owned(), "/etc/keys.d".to_owned()]
        );

        // The defaults: no sign-api verification and no extra keyring.
        let plain = cfg.remote("signed").unwrap();
        assert!(plain.gpg_verify().unwrap());
        let bare = RepoConfig::parse(
            "[core]\nrepo_version=1\nmode=bare\n\n[remote \"plain\"]\nurl=http://ex/r\n",
        )
        .unwrap();
        let bare = bare.remote("plain").unwrap();
        assert_eq!(bare.sign_verify().unwrap(), SignVerify::Off);
        assert_eq!(bare.sign_verify_summary().unwrap(), SignVerify::Off);
        assert!(bare.gpgkeypath().unwrap().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.remote("r").unwrap().gpgkeypath().unwrap(),
                *want,
                "gpgkeypath={value}"
            );
        }
    }

    /// `sign-verify` is a boolean or a list of engine names, split on `,` and
    /// `;`, each name taken as written.
    #[test]
    fn parses_the_sign_verify_spellings() {
        assert_eq!(parse_sign_verify(None), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("true")), SignVerify::All);
        assert_eq!(parse_sign_verify(Some("1")), SignVerify::All);
        assert_eq!(parse_sign_verify(Some("false")), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("0")), SignVerify::Off);
        assert_eq!(parse_sign_verify(Some("")), SignVerify::Off);
        assert_eq!(
            parse_sign_verify(Some("ed25519")),
            SignVerify::Engines(vec!["ed25519".to_owned()])
        );
        // Both separators, and an empty element dropped.
        assert_eq!(
            parse_sign_verify(Some("ed25519;spki,")),
            SignVerify::Engines(vec!["ed25519".to_owned(), "spki".to_owned()])
        );
        // A name is not trimmed. The `ostree` command also refuses this value.
        assert_eq!(
            parse_sign_verify(Some("ed25519, ed25519")),
            SignVerify::Engines(vec!["ed25519".to_owned(), " ed25519".to_owned()])
        );
    }

    /// 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.remote("secure").unwrap();
        assert_eq!(
            remote.tls_ca_path().unwrap().as_deref(),
            Some("/etc/ca.pem")
        );
        assert_eq!(
            remote.tls_client_cert_path().unwrap().as_deref(),
            Some("/etc/client.pem")
        );
        assert_eq!(
            remote.tls_client_key_path().unwrap().as_deref(),
            Some("/etc/client.key")
        );
        assert!(remote.tls_permissive().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.remote("set").unwrap().proxy().unwrap().as_deref(),
            Some("http://user:pw@proxy.ex.com:3128")
        );
        assert_eq!(
            cfg.remote("empty").unwrap().proxy().unwrap().as_deref(),
            Some("")
        );
        assert_eq!(
            cfg.remote("blank").unwrap().proxy().unwrap().as_deref(),
            Some("")
        );
        assert_eq!(
            cfg.remote("trail").unwrap().proxy().unwrap().as_deref(),
            Some("http://p:1  ")
        );
        assert_eq!(
            cfg.remote("escape").unwrap().proxy().unwrap().as_deref(),
            Some(" ")
        );
        assert_eq!(cfg.remote("plain").unwrap().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.remote("central").unwrap();
        assert_eq!(
            remote.push_url().unwrap().as_deref(),
            Some("ssh://pusher@ex.com/srv/repo")
        );
        assert_eq!(
            remote.ssh_command().unwrap().as_deref(),
            Some("ssh -o BatchMode=yes")
        );
        assert_eq!(
            remote.receive_command().unwrap().as_deref(),
            Some("/opt/bin/ostrya receive")
        );
        assert_eq!(
            remote.push_token_file().unwrap().as_deref(),
            Some("/etc/push token")
        );
        assert_eq!(remote.push_user().unwrap().as_deref(), Some("alice"));
        assert_eq!(
            remote.pull_url().unwrap().as_deref(),
            Some("puller@ex.com:srv/repo")
        );
        assert_eq!(
            remote.send_command().unwrap().as_deref(),
            Some("/opt/bin/ostrya send -v")
        );

        let plain = cfg.remote("plain").unwrap();
        assert_eq!(plain.push_url().unwrap(), None);
        assert_eq!(plain.ssh_command().unwrap(), None);
        assert_eq!(plain.receive_command().unwrap(), None);
        assert_eq!(plain.push_token_file().unwrap(), None);
        assert_eq!(plain.push_user().unwrap(), None);
        assert_eq!(plain.pull_url().unwrap(), None);
        assert_eq!(plain.send_command().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()
                .remote("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"]
        );
        for keys in [
            "mirrored-collection-ids=\n",
            "mirrored-collection-ids=;\n",
            "mirrored-collection-ids=org.ex.A;;org.ex.B\n",
            "mirrored-collection-ids=org/ex\n",
            "mirrored-collection-ids=1org.ex\n",
            "collection-id=org.ex.C\nmirrored-collection-ids=org.ex.A;org.ex.C\n",
        ] {
            assert!(
                matches!(ids(keys), Err(Error::InvalidFormat(_))),
                "{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()
                .remote("o")
                .unwrap()
                .key_path("tls-ca-path")
                .unwrap()
                .unwrap();
            assert_eq!(path.origin, KeyOrigin::RemotesFile);
            assert_eq!(read_located(&path, Some(&repo)), (text.to_owned(), shown));
            let path = repo
                .config()
                .remote("c")
                .unwrap()
                .key_path("tls-ca-path")
                .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().remote("a").unwrap();
        let path = absolute.key_path("tls-ca-path").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().remote("p").unwrap();
        for result in [
            parent.tls_ca_path(),
            parent.key_path("tls-ca-path").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()
    }
}