ostrya 0.7.0

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
//! 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.
//! - [`Repo::write_config`] writes an edited config back to the repository.
//! - [`valid_remote_name`] checks a remote name.

use ostrya_core::{KeyFile, RepoMode};

use crate::error::{Error, Result};
use crate::repo::{Repo, check_config_size};
use crate::summary::{remove_root_file_blocking, write_root_file_blocking};

const CORE: &str = "core";
const ARCHIVE: &str = "archive";
const EX_INTEGRITY: &str = "ex-integrity";
const EX_OSTRYA: &str = "ex-ostrya";
/// 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.
///
/// # 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 key that is an ostrya extension,
///   [`keep_detached_related`](RepoConfig::keep_detached_related).
/// - 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>,
}

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

    /// 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, in the order of their sections.
    pub fn remotes(&self) -> impl Iterator<Item = &str> {
        self.remotes.iter().map(String::as_str)
    }

    /// Returns the accessor of one remote, or `None` if the section does not
    /// exist.
    pub fn remote(&self, name: &str) -> Option<Remote<'_>> {
        Remote::in_keyfile(&self.keyfile, name)
    }

    /// 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 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 this view.
    ///
    /// 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.
    pub fn keyfile(&self) -> &KeyFile {
        &self.keyfile
    }

    /// Returns the parsed key file of this view 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 temporary file at mode `0644`.
    /// 2. If `[core] fsync` is on, it syncs the file with `fdatasync`.
    /// 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 it. 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.
    ///
    /// This handle keeps the configuration that it was opened with. To read
    /// the new values, open the repository again.
    ///
    /// # 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::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::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)?;
        self.write_locked(move |repo| {
            write_root_file_blocking(repo.repo_fd(), CONFIG_FILE, &bytes, fsync)
        })
        .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. The keyring belongs to the config section of the remote,
    /// so a deletion of the section also deletes this file.
    ///
    /// 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::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::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);
        self.write_locked(move |repo| remove_root_file_blocking(repo.repo_fd(), &name).map(drop))
            .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.
#[derive(Debug, Clone)]
pub struct Remote<'a> {
    keyfile: &'a KeyFile,
    group: String,
}

impl<'a> Remote<'a> {
    /// Returns the `[remote "<name>"]` section of `keyfile`, or `None` if the
    /// section does not exist.
    pub(crate) fn in_keyfile(keyfile: &'a KeyFile, name: &str) -> Option<Remote<'a>> {
        let group = remote_group(name);
        keyfile
            .has_group(&group)
            .then_some(Remote { keyfile, group })
    }

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

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 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. The GPG
    /// verifier refuses an empty entry, because it cannot read it. It reads
    /// each regular file of a directory. 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
    ///
    /// The call gives no error.
    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();
        }
        Ok(entries)
    }

    /// 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.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn verification_file(&self, engine: &str) -> Result<Option<String>> {
        self.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 `branches` key: the refs of a pull that names no ref.
    ///
    /// # 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 `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
    /// a relative path from the current directory of the process. They do not
    /// expand `~`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_ca_path(&self) -> Result<Option<String>> {
        self.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 relative path is read as
    /// [`tls_ca_path`](Remote::tls_ca_path) states.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_client_cert_path(&self) -> Result<Option<String>> {
        self.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 relative path
    /// is read as [`tls_ca_path`](Remote::tls_ca_path) states.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn tls_client_key_path(&self) -> Result<Option<String>> {
        self.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 `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 a relative path from the current directory of the
    /// process, as a pull reads the TLS keys. It does not expand `~`.
    ///
    /// # Errors
    ///
    /// [`Error::Core`] if the value holds a malformed escape sequence.
    pub fn push_token_file(&self) -> Result<Option<String>> {
        self.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)
    }
}

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

/// Returns the key-file group name of a remote: `remote "<name>"`.
pub(crate) 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.
pub(crate) 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)]
mod tests {
    use super::*;

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

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

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