ostrya 0.17.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
//! The typed reads: the reads of `RepoConfig` and of one section of a named
//! group.

use std::marker::PhantomData;
use std::path::PathBuf;

use ostrya_core::KeyFile;

use super::typed::{OutputOf, ValueOf, lists, str_eq};
use super::value::{
    ConfigPath, Value, ValueError, decode_string, encode_string, encode_string_list, value_error,
};
use super::{
    Group, Key, KeyOrigin, KeyPath, Overrides, RemoteFile, RemoteSource, RepoConfig, SingleKey,
    TextInEffect, client, key, remote, trust,
};
use crate::error::{Error, Result};

/// The value in effect of a key, and where it comes from.
///
/// A read takes the first source that gives a value, in this order:
///
/// 1. [`Forced`](Lookup::Forced): an override of the handle that applies
///    whether the file sets the key or not.
/// 2. [`File`](Lookup::File): the value of the file.
/// 3. [`Fallback`](Lookup::Fallback): an override of the handle that applies
///    when the file does not set the key.
/// 4. [`Default`](Lookup::Default): the built-in default of the key.
///
/// [`OpenOptions::force`](crate::OpenOptions::force),
/// [`OpenOptions::fallback`](crate::OpenOptions::fallback), and
/// [`CreateOptions::fallback`](crate::CreateOptions::fallback) set the
/// overrides of a handle. The reads of [`RepoConfig`] apply them. A
/// [`Section`] and a [`RepoConfig`] with no handle, such as the result of
/// [`RepoConfig::parse`], have no override, so their reads give
/// [`File`](Lookup::File) or [`Default`](Lookup::Default).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Lookup<V> {
    /// The value comes from an override of the handle that wins over the
    /// file. The value applies also when the file does not set the key.
    Forced(V),
    /// The value comes from the file.
    File(V),
    /// The value comes from an override of the handle for a key that the
    /// file does not set.
    Fallback(V),
    /// The value is the built-in default of the key.
    Default(V),
}

impl<V> Lookup<V> {
    /// Returns the value.
    pub fn value(&self) -> &V {
        match self {
            Lookup::Forced(v) | Lookup::File(v) | Lookup::Fallback(v) | Lookup::Default(v) => v,
        }
    }

    /// Returns the value by value.
    pub fn into_value(self) -> V {
        match self {
            Lookup::Forced(v) | Lookup::File(v) | Lookup::Fallback(v) | Lookup::Default(v) => v,
        }
    }
}

/// A reference to one section of the named group `G`, by the name of the
/// section.
///
/// The value of a key that names another group has this type.
/// [`RepoConfig::resolve`] gives the section. The text form is the name of
/// the section, which is not empty.
///
/// # Examples
///
/// ```
/// use ostrya::config::GroupRef;
///
/// ostrya::config_group! {
///     pub group image = named "ex-image" {
///         Arch: Option<String> = "arch";
///     }
/// }
///
/// let base = GroupRef::<image::Group>::new("base").unwrap();
/// assert_eq!(base.name(), "base");
/// assert!(GroupRef::<image::Group>::new("").is_err());
/// ```
pub struct GroupRef<G: Group> {
    name: String,
    group: PhantomData<fn() -> G>,
}

impl<G: Group> GroupRef<G> {
    /// Returns a reference to the section `name`.
    ///
    /// # Errors
    ///
    /// A [`ValueError`] with the text `is empty` if `name` is empty.
    /// [`Value::parse`] gives the same error for an empty name.
    pub fn new(name: impl Into<String>) -> std::result::Result<GroupRef<G>, ValueError> {
        let name = name.into();
        if name.is_empty() {
            return Err(ValueError::new("is empty"));
        }
        Ok(GroupRef {
            name,
            group: PhantomData,
        })
    }

    /// Returns the name of the section.
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl<G: Group> Clone for GroupRef<G> {
    fn clone(&self) -> GroupRef<G> {
        GroupRef {
            name: self.name.clone(),
            group: PhantomData,
        }
    }
}

impl<G: Group> std::fmt::Debug for GroupRef<G> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GroupRef")
            .field("group", &G::NAME)
            .field("name", &self.name)
            .finish()
    }
}

impl<G: Group> PartialEq for GroupRef<G> {
    fn eq(&self, other: &GroupRef<G>) -> bool {
        self.name == other.name
    }
}

impl<G: Group> Eq for GroupRef<G> {}

impl<G: Group> std::hash::Hash for GroupRef<G> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.name.hash(state);
    }
}

/// The text is decoded, and is the name of a section. An empty name is
/// refused.
impl<G: Group> Value for GroupRef<G> {
    fn parse(raw: &str) -> std::result::Result<GroupRef<G>, ValueError> {
        GroupRef::new(decode_string(raw)?)
    }

    fn format(&self) -> String {
        encode_string(&self.name)
    }
}

/// One section of the named group `G`.
///
/// [`RepoConfig::section`], [`RepoConfig::sections`], and
/// [`RepoConfig::resolve`] give a section. A read takes a key of the group
/// `G` alone, and parses the value of the file each time that it is called.
///
/// A section of [`remote::Group`] comes from `config` or from a `.conf` file
/// of the remotes directory, and [`source`](Section::source) names the file.
/// A section of each other group comes from `config`.
pub struct Section<'a, G: Group> {
    keyfile: &'a KeyFile,
    /// The group header, `NAME "SECTION"`.
    header: &'a str,
    /// The name of the `.conf` file that holds the section, or `None` for
    /// `config`.
    file: Option<&'a str>,
    group: PhantomData<fn() -> G>,
}

impl<G: Group> Clone for Section<'_, G> {
    fn clone(&self) -> Self {
        Section {
            keyfile: self.keyfile,
            header: self.header,
            file: self.file,
            group: PhantomData,
        }
    }
}

impl<G: Group> std::fmt::Debug for Section<'_, G> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Section")
            .field("header", &self.header)
            .field("file", &self.file)
            .finish()
    }
}

impl<'a, G: Group> Section<'a, G> {
    /// Returns the name of the section: `SECTION` of the header
    /// `NAME "SECTION"`.
    pub fn name(&self) -> &'a str {
        let header: &'a str = self.header;
        header
            .split_once('"')
            .and_then(|(_, rest)| rest.strip_suffix('"'))
            .unwrap_or_default()
    }

    /// Returns the value in effect of the key `K`: the value of the file, or
    /// the default of the key if the file does not set it.
    ///
    /// The result type is [`Key::Output`]. It is `Option<V>` for a key with
    /// no default that is not required.
    ///
    /// # Errors
    ///
    /// - The error of the value type if the value does not parse.
    ///   [`ValueError`] states the text.
    /// - [`Error::InvalidFormat`] if the key is required and absent.
    pub fn get<K: Key<G>>(&self) -> Result<K::Output> {
        read_in_effect::<G, K>(self.keyfile, self.header, None)
    }

    /// Returns the value of the key `K` in the file, or `None` if the file
    /// does not set it. The default of the key does not apply.
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`] states the text.
    pub fn file_value<K: Key<G>>(&self) -> Result<Option<K::Value>> {
        read_file::<G, K>(self.keyfile, self.header)
    }

    /// Returns the value in effect of the key `K` and its source, or `None`
    /// if the file does not set the key and the key has no default.
    ///
    /// A section has no override, so the source is [`Lookup::File`] or
    /// [`Lookup::Default`].
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`] states the text.
    pub fn lookup<K: Key<G>>(&self) -> Result<Option<Lookup<K::Value>>> {
        lookup::<G, K>(self.keyfile, self.header, None)
    }

    /// Refuses a key of the section that the closed group `G` does not list.
    ///
    /// The call checks nothing if [`Group::CLOSED`] of `G` is `false`. It
    /// checks each key against the key list of `G` alone, and gives the
    /// unknown-key text for a key outside the list. It names the first such
    /// key in the order of the file. The crate applies this check to its own
    /// closed groups. A library user calls it for a closed group of its own.
    ///
    /// For the removed key `collection` of a client group, the call gives
    /// the unknown-key text. [`RepoConfig::check`] gives a text that starts
    /// with `[HEADER] holds the removed key 'collection'` for this key.
    ///
    /// For the keys `gpg-verify-summary`, `sign-verify-summary`, and
    /// `verification-ENGINE-key` and `verification-ENGINE-file` of an engine
    /// other than `ed25519` and `spki` in a trust group, the call also gives
    /// the unknown-key text. [`RepoConfig::check`] and the readers of a trust
    /// group give a text that states the reason, as [`trust`] states.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with the text `[HEADER] holds the unknown key
    /// 'KEY'`, where `HEADER` is the header of the section.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    ///
    /// ostrya::config_group! {
    ///     pub group image = named "ex-image", closed {
    ///         Arch: Option<String> = "arch";
    ///     }
    /// }
    ///
    /// let cfg = RepoConfig::parse(
    ///     "[core]\nrepo_version=1\nmode=bare\n[ex-image \"base\"]\narch=x86\nzzz=1\n",
    /// )?;
    /// let base = cfg.section::<image::Group>("base").unwrap();
    /// assert_eq!(
    ///     base.refuse_unknown_keys().unwrap_err().to_string(),
    ///     "invalid format: [ex-image \"base\"] holds the unknown key 'zzz'"
    /// );
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn refuse_unknown_keys(&self) -> Result<()> {
        refuse_unknown_keys::<G>(self.keyfile, self.header)
    }

    /// Returns a section of `G` over the group `header` of `keyfile`, with
    /// the source `config`.
    pub(crate) fn at(keyfile: &'a KeyFile, header: &'a str) -> Section<'a, G> {
        Section {
            keyfile,
            header,
            file: None,
            group: PhantomData,
        }
    }

    /// Returns the raw text of the key `K`, or `None` if the key is absent.
    pub(crate) fn raw_value<K: Key<G>>(&self) -> Option<&'a str> {
        const {
            assert!(
                lists(G::KEYS, K::NAME),
                "the key is not in the key list of its group"
            )
        };
        let keyfile: &'a KeyFile = self.keyfile;
        keyfile.get_value(self.header, K::NAME)
    }

    /// Returns `true` if the section sets the key `K`.
    pub(crate) fn contains<K: Key<G>>(&self) -> bool {
        self.raw_value::<K>().is_some()
    }

    /// Returns the group header of the section, `NAME "SECTION"`.
    pub(crate) fn header(&self) -> &'a str {
        self.header
    }

    /// Returns the names of the keys of the section, in the order of the
    /// file.
    pub(crate) fn key_names(&self) -> impl Iterator<Item = &'a str> + use<'a, G> {
        let keyfile: &'a KeyFile = self.keyfile;
        keyfile.keys(self.header)
    }

    /// Returns the path of the key `K`, with the source of the section, or
    /// `None` if the key is absent.
    ///
    /// # Errors
    ///
    /// The errors of a read of `K`.
    pub(crate) fn key_path<K>(&self) -> Result<Option<KeyPath>>
    where
        K: Key<G, Value = ConfigPath>,
    {
        Ok(self
            .file_value::<K>()?
            .map(|path| self.key_path_of(path.into_string())))
    }

    /// 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.file {
                None => KeyOrigin::Config,
                Some(_) => KeyOrigin::RemotesFile,
            },
        }
    }

    /// Returns the entries of [`remote::GpgKeyPath`] as paths with the source
    /// of the section.
    ///
    /// # Errors
    ///
    /// The errors of a read of [`remote::GpgKeyPath`].
    #[cfg(feature = "verify-gpg")]
    pub(crate) fn gpgkeypath_paths(&self) -> Result<Vec<KeyPath>>
    where
        remote::GpgKeyPath: Key<G, Value = super::KeyringPaths, Output = super::KeyringPaths>,
    {
        Ok(self
            .get::<remote::GpgKeyPath>()?
            .into_entries()
            .into_iter()
            .map(|entry| self.key_path_of(entry))
            .collect())
    }

    /// Returns the inline trusted key of the sign-api engine `engine`: the
    /// key `verification-ENGINE-key`, or `None` if the key is absent or the
    /// port has no key type for the engine.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    pub(crate) fn verification_key(&self, engine: &str) -> Result<Option<String>>
    where
        remote::VerificationEd25519Key: Key<G, Output = Option<String>>,
        remote::VerificationSpkiKey: Key<G, Output = Option<String>>,
    {
        match engine {
            "ed25519" => self.get::<remote::VerificationEd25519Key>(),
            "spki" => self.get::<remote::VerificationSpkiKey>(),
            _ => Ok(None),
        }
    }

    /// Returns the path of the file of trusted keys of the sign-api engine
    /// `engine`: the key `verification-ENGINE-file`, with the source of the
    /// section, or `None` if the key is absent or the port has no key type
    /// for the engine.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    pub(crate) fn verification_file(&self, engine: &str) -> Result<Option<KeyPath>>
    where
        remote::VerificationEd25519File: Key<G, Value = ConfigPath>,
        remote::VerificationSpkiFile: Key<G, Value = ConfigPath>,
    {
        match engine {
            "ed25519" => self.key_path::<remote::VerificationEd25519File>(),
            "spki" => self.key_path::<remote::VerificationSpkiFile>(),
            _ => Ok(None),
        }
    }
}

/// The reads of a remote section.
impl<'a> Section<'a, remote::Group> {
    /// Returns the file that holds the section: `config`, or a `.conf` file
    /// of the remotes directory.
    pub fn source(&self) -> RemoteSource<'a> {
        match self.file {
            None => RemoteSource::Config,
            Some(file) => RemoteSource::File(file),
        }
    }

    /// Returns the ids of [`remote::MirroredCollectionIds`], or an empty list
    /// if the key is absent.
    ///
    /// The call also refuses an id that is the [`remote::CollectionId`] of
    /// the section. It reads `collection-id` after the list.
    ///
    /// # Errors
    ///
    /// - The errors of a read of [`remote::MirroredCollectionIds`].
    /// - [`Error::Core`] if `collection-id` holds a malformed escape
    ///   sequence.
    /// - [`Error::InvalidFormat`] if an id is the `collection-id` of the
    ///   section. The text is `[remote "NAME"] mirrored-collection-ids holds
    ///   'ID', the collection-id of the remote`.
    pub fn mirrored_collection_ids(&self) -> Result<Vec<String>> {
        let Some(ids) = self.file_value::<remote::MirroredCollectionIds>()? else {
            return Ok(Vec::new());
        };
        let ids = ids.into_ids();
        if let Some(own) = self.get::<remote::CollectionId>()?
            && let Some(id) = ids.iter().find(|id| **id == own)
        {
            return Err(Error::InvalidFormat(format!(
                "[{}] {} holds '{id}', the collection-id of the remote",
                self.header,
                <remote::MirroredCollectionIds as Key<remote::Group>>::NAME
            )));
        }
        Ok(ids)
    }

    /// Checks the value of each key of [`remote::Group`] that the section
    /// sets, in the order of the definition, then the rule of
    /// [`mirrored_collection_ids`](Section::mirrored_collection_ids).
    ///
    /// The group is open, so the call does not read a key that the group
    /// does not list.
    ///
    /// # Errors
    ///
    /// The error of the first key whose value does not parse, or the error of
    /// [`mirrored_collection_ids`](Section::mirrored_collection_ids).
    pub(crate) fn check(&self) -> Result<()> {
        remote::check_file(self.keyfile, self.header)?;
        self.mirrored_collection_ids().map(drop)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key, and the errors of
    /// [`mirrored_collection_ids`](Section::mirrored_collection_ids) for
    /// `mirrored-collection-ids`.
    pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = if key == <remote::MirroredCollectionIds as Key<remote::Group>>::NAME {
            if !self.contains::<remote::MirroredCollectionIds>() {
                return Ok(TextInEffect::NoKey);
            }
            Some(encode_string_list(&self.mirrored_collection_ids()?))
        } else {
            match remote::text_in_effect(self.keyfile, self.header, None, key) {
                Some(text) => text?,
                None => self.keyfile.get_value(self.header, key).map(str::to_owned),
            }
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// The reads of a client section.
impl Section<'_, client::Group> {
    /// Returns the value in effect of [`client::AllowUnsigned`].
    ///
    /// The value of the file applies when the section sets the key. Else the
    /// value is `true` if the section does not set [`client::Verify`], and
    /// `false` if it does. The call reads `verify` only when the section does
    /// not set `allow-unsigned`. It does not apply the rule of
    /// [`ClientAccess::from_config`](crate::access::ClientAccess::from_config)
    /// that `allow-unsigned=false` needs `verify`.
    ///
    /// # Errors
    ///
    /// The errors of a read of [`client::AllowUnsigned`], and of a read of
    /// [`client::Verify`] when the section does not set `allow-unsigned`.
    pub fn allow_unsigned(&self) -> Result<bool> {
        match self.get::<client::AllowUnsigned>()? {
            Some(value) => Ok(value),
            None => Ok(self.get::<client::Verify>()?.is_none()),
        }
    }

    /// Refuses the key `collection`, which the group does not take.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with a text that names the form
    /// `@ID:PATTERN` of an allow item and a deny item.
    pub(crate) fn refuse_removed_keys(&self) -> Result<()> {
        if self.keyfile.get_value(self.header, "collection").is_some() {
            return Err(Error::InvalidFormat(format!(
                "[{}] holds the removed key 'collection'; an allow item or a deny item \
                 names the refs of a collection as @ID:PATTERN",
                self.header
            )));
        }
        Ok(())
    }

    /// Checks the section: first the key `collection`, as
    /// [`refuse_removed_keys`](Section::refuse_removed_keys) does, then a key
    /// that [`client::Group`] does not list, then the value of each key of
    /// the group that the section sets, in the order of the definition.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    pub(crate) fn check(&self) -> Result<()> {
        self.refuse_removed_keys()?;
        client::check_file(self.keyfile, self.header)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key, and the errors of
    /// [`allow_unsigned`](Section::allow_unsigned) for `allow-unsigned`.
    pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = if key == <client::AllowUnsigned as Key<client::Group>>::NAME {
            Some(self.allow_unsigned()?.format())
        } else {
            match client::text_in_effect(self.keyfile, self.header, None, key) {
                Some(text) => text?,
                None => self.keyfile.get_value(self.header, key).map(str::to_owned),
            }
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// The sign-api engines that a trust group can name.
pub(crate) const TRUST_ENGINES: &[&str] = &["ed25519", "spki"];

/// Returns the engine that a `verification-ENGINE-key` or
/// `verification-ENGINE-file` key names, or `None` for another key.
pub(crate) fn verification_engine(key: &str) -> Option<&str> {
    let rest = key.strip_prefix("verification-")?;
    rest.strip_suffix("-key")
        .or_else(|| rest.strip_suffix("-file"))
}

/// The reads of a trust section.
impl Section<'_, trust::Group> {
    /// Refuses a key of the section that [`trust::Group`] does not list. The
    /// call names the first such key in the order of the file.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with one of these texts, where `HEADER` is the
    /// header of the section:
    ///
    /// - `[HEADER] holds 'KEY', and a trust group sets a commit policy alone`
    ///   for `gpg-verify-summary` and `sign-verify-summary`.
    /// - `[HEADER] holds 'KEY', and 'ENGINE' is not ed25519 or spki` for a key
    ///   `verification-ENGINE-key` or `verification-ENGINE-file`.
    /// - `[HEADER] holds the unknown key 'KEY'` for each other key.
    pub(crate) fn refuse_foreign_keys(&self) -> Result<()> {
        let header = self.header;
        for key in self.key_names() {
            if <trust::Group as Group>::KEYS.contains(&key) {
                continue;
            }
            let reason = match key {
                "gpg-verify-summary" | "sign-verify-summary" => {
                    "a trust group sets a commit policy alone".to_owned()
                }
                _ => match verification_engine(key) {
                    Some(engine) if !TRUST_ENGINES.contains(&engine) => {
                        format!("'{engine}' is not ed25519 or spki")
                    }
                    _ => {
                        return Err(Error::InvalidFormat(format!(
                            "[{header}] holds the unknown key '{key}'"
                        )));
                    }
                },
            };
            return Err(Error::InvalidFormat(format!(
                "[{header}] holds '{key}', and {reason}"
            )));
        }
        Ok(())
    }

    /// Checks the section: first a key that [`trust::Group`] does not list,
    /// as [`refuse_foreign_keys`](Section::refuse_foreign_keys) does, then
    /// the value of each key of the group that the section sets, in the order
    /// of the definition.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    pub(crate) fn check(&self) -> Result<()> {
        self.refuse_foreign_keys()?;
        trust::check_file(self.keyfile, self.header)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = match trust::text_in_effect(self.keyfile, self.header, None, key) {
            Some(text) => text?,
            None => self.keyfile.get_value(self.header, key).map(str::to_owned),
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// The reads of a key section.
impl Section<'_, key::Group> {
    /// Checks the section: first a key that [`key::Group`] does not list,
    /// then the value of each key of the group that the section sets, in the
    /// order of the definition.
    ///
    /// # Errors
    ///
    /// The first error that the call finds.
    pub(crate) fn check(&self) -> Result<()> {
        key::check_file(self.keyfile, self.header)
    }

    /// Returns the value in effect of the key `key` of the section, as
    /// [`RepoConfig::text_in_effect`] states.
    ///
    /// # Errors
    ///
    /// The errors of a read of the key.
    pub(crate) fn text_in_effect(&self, key: &str) -> Result<TextInEffect> {
        let text = match key::text_in_effect(self.keyfile, self.header, None, key) {
            Some(text) => text?,
            None => self.keyfile.get_value(self.header, key).map(str::to_owned),
        };
        Ok(text.map_or(TextInEffect::NoKey, TextInEffect::Value))
    }
}

/// Typed reads of the keys of `config`.
impl RepoConfig {
    /// Returns the value in effect of the key `K` of a single group.
    ///
    /// The value comes from the first source that gives one, in the order of
    /// [`Lookup`]: a forced value of the handle, the value of `config`, a
    /// fallback value of the handle, and the default of the key. A config
    /// with no handle has no override.
    ///
    /// The result type is [`Key::Output`]. It is `Option<V>` for a key with
    /// no default that is not required. The call parses the value each time
    /// that it is called. A forced value applies with no parse of the value
    /// of the file.
    ///
    /// # Errors
    ///
    /// - The error of the value type if the value does not parse.
    ///   [`ValueError`] states the text.
    /// - [`Error::InvalidFormat`] if the key is required and absent.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::{RepoConfig, repo};
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\nfsync=false\n")?;
    /// assert!(!cfg.get::<repo::Fsync>()?);
    /// assert_eq!(cfg.get::<repo::TmpExpirySecs>()?, 86400);
    /// assert_eq!(cfg.get::<repo::CollectionId>()?, None);
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn get<K>(&self) -> Result<OutputOf<K>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        read_in_effect::<K::Group, K>(
            &self.keyfile,
            <K as SingleKey>::Group::NAME,
            Some(&self.overrides),
        )
    }

    /// Returns the value of the key `K` of a single group in `config`, or
    /// `None` if `config` does not set it. The overrides of the handle and
    /// the default of the key do not apply.
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`] states the text.
    pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        read_file::<K::Group, K>(&self.keyfile, <K as SingleKey>::Group::NAME)
    }

    /// Returns the value in effect of the key `K` of a single group and its
    /// source, or `None` if no source gives a value.
    ///
    /// The call takes the sources in the order of [`Lookup`]. A config with
    /// no handle has no override, so the source is [`Lookup::File`] or
    /// [`Lookup::Default`]. A forced value applies with no parse of the value
    /// of the file.
    ///
    /// # Errors
    ///
    /// The error of the value type if the value does not parse.
    /// [`ValueError`] states the text.
    pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        lookup::<K::Group, K>(
            &self.keyfile,
            <K as SingleKey>::Group::NAME,
            Some(&self.overrides),
        )
    }

    /// Returns the section `name` of the named group `G`, or `None` if no
    /// source has such a section.
    ///
    /// A section of [`remote::Group`] comes from `config`, or else from the
    /// first `.conf` file of the remotes directory that holds it, in the
    /// order of [`sections`](RepoConfig::sections). A section of each other
    /// group comes from `config`.
    ///
    /// The call gives `None` for an empty `name` and for a `name` that
    /// holds `"`. [`sections`](RepoConfig::sections) skips the headers of
    /// such sections, so they are not sections of the group.
    pub fn section<G: Group>(&self, name: &str) -> Option<Section<'_, G>> {
        const { assert!(G::NAMED, "a single group has no section") };
        if !is_section_name(name) {
            return None;
        }
        let header = section_header::<G>(name);
        self.sources::<G>().find_map(|(keyfile, file)| {
            let header = keyfile.group_name(&header)?;
            Some(Section {
                keyfile,
                header,
                file,
                group: PhantomData,
            })
        })
    }

    /// Returns each section of the named group `G`.
    ///
    /// The sections of `config` come first, in the order of the file. For
    /// [`remote::Group`], the sections of each `.conf` file of the remotes
    /// directory follow: the files in the byte order of their names, and the
    /// sections of each file in the order of the file. The `.conf` files
    /// give no section of another group.
    ///
    /// The call skips a header of the group whose section name is empty or
    /// holds `"`, for example `[NAME ""]` or `[NAME "a" "b"]`.
    pub fn sections<G: Group>(&self) -> impl Iterator<Item = Section<'_, G>> {
        const { assert!(G::NAMED, "a single group has no section") };
        self.sources::<G>().flat_map(|(keyfile, file)| {
            keyfile.groups().filter_map(move |header| {
                section_name::<G>(header)?;
                Some(Section {
                    keyfile,
                    header,
                    file,
                    group: PhantomData,
                })
            })
        })
    }

    /// Returns the section that `reference` names.
    ///
    /// The call finds the section as [`section`](RepoConfig::section) does.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] if no source has such a section. A name that
    /// holds `"` names no section, as [`section`](RepoConfig::section)
    /// states.
    pub fn resolve<G: Group>(&self, reference: &GroupRef<G>) -> Result<Section<'_, G>> {
        self.section::<G>(reference.name()).ok_or_else(|| {
            Error::InvalidFormat(format!(
                "the config has no [{}] group",
                section_header::<G>(reference.name())
            ))
        })
    }

    /// Refuses a key of the group `G` that the closed group does not list.
    ///
    /// For a single group, the call checks the group `[NAME]` of `config`.
    /// For a named group, it checks each section of the group in `config`,
    /// in the order of the file, as [`Section::refuse_unknown_keys`] does.
    /// The call checks nothing if
    /// [`Group::CLOSED`] of `G` is `false`. It checks each key against the key
    /// list of `G` alone, and gives the unknown-key text for a key outside
    /// the list. It names the first such key in the order of the file.
    ///
    /// For the removed key `collection` of a client group, the call gives
    /// the unknown-key text. [`check`](RepoConfig::check) gives a text that
    /// starts with `[HEADER] holds the removed key 'collection'` for this
    /// key.
    ///
    /// For the keys `gpg-verify-summary`, `sign-verify-summary`, and
    /// `verification-ENGINE-key` and `verification-ENGINE-file` of an engine
    /// other than `ed25519` and `spki` in a trust group, the call also gives
    /// the unknown-key text. [`check`](RepoConfig::check) and the readers of a
    /// trust group give a text that states the reason, as [`trust`] states.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidFormat`] with the text `[HEADER] holds the unknown key
    /// 'KEY'`, where `HEADER` is the header of the group.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya::config::RepoConfig;
    ///
    /// ostrya::config_group! {
    ///     pub group tool = "ex-tool", closed {
    ///         Jobs: Option<u32> = "jobs";
    ///     }
    /// }
    ///
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n[ex-tool]\njobs=4\n")?;
    /// cfg.refuse_unknown_keys::<tool::Group>()?;
    /// let cfg = RepoConfig::parse("[core]\nrepo_version=1\nmode=bare\n[ex-tool]\nzzz=1\n")?;
    /// assert_eq!(
    ///     cfg.refuse_unknown_keys::<tool::Group>().unwrap_err().to_string(),
    ///     "invalid format: [ex-tool] holds the unknown key 'zzz'"
    /// );
    /// # Ok::<(), ostrya::Error>(())
    /// ```
    pub fn refuse_unknown_keys<G: Group>(&self) -> Result<()> {
        if !G::CLOSED {
            return Ok(());
        }
        if !G::NAMED {
            return refuse_unknown_keys::<G>(&self.keyfile, G::NAME);
        }
        self.keyfile
            .groups()
            .filter(|header| section_name::<G>(header).is_some())
            .try_for_each(|header| refuse_unknown_keys::<G>(&self.keyfile, header))
    }

    /// Returns the key files that hold the sections of the group `G`, each
    /// with the name of its `.conf` file, or `None` for `config`.
    fn sources<G: Group>(&self) -> impl Iterator<Item = (&KeyFile, Option<&str>)> {
        let is_remote = const { str_eq(G::NAME, <remote::Group as Group>::NAME) };
        let files: &[RemoteFile] = if is_remote { &self.remote_files } else { &[] };
        std::iter::once((&self.keyfile, None)).chain(
            files
                .iter()
                .map(|file| (&file.keyfile, Some(file.name.as_str()))),
        )
    }
}

/// Returns the header of the section `name` of the named group `G`.
pub(crate) fn section_header<G: Group>(name: &str) -> String {
    format!("{} \"{name}\"", G::NAME)
}

/// Returns the section name in `header`, a header of the named group `G`, or
/// `None` for the header of another group and for a section name that
/// [`is_section_name`] refuses.
pub(crate) fn section_name<G: Group>(header: &str) -> Option<&str> {
    let name = header
        .strip_prefix(G::NAME)?
        .strip_prefix(" \"")?
        .strip_suffix('"')?;
    is_section_name(name).then_some(name)
}

/// Returns `true` if `name` is the name of a section: it is not empty and
/// holds no `"`.
fn is_section_name(name: &str) -> bool {
    !name.is_empty() && !name.contains('"')
}

/// Refuses a key of the group `header` of `keyfile` that the closed group `G`
/// does not list.
///
/// The call checks nothing if [`Group::CLOSED`] of `G` is `false`. It names
/// the first such key in the order of the file.
///
/// # Errors
///
/// [`Error::InvalidFormat`] with the text `[HEADER] holds the unknown key
/// 'KEY'`.
pub(crate) fn refuse_unknown_keys<G: Group>(keyfile: &KeyFile, header: &str) -> Result<()> {
    if !G::CLOSED {
        return Ok(());
    }
    match keyfile.keys(header).find(|key| !G::KEYS.contains(key)) {
        Some(key) => Err(Error::InvalidFormat(format!(
            "[{header}] holds the unknown key '{key}'"
        ))),
        None => Ok(()),
    }
}

/// Returns the value of the key `K` in the group `header` of `keyfile`, or
/// `None` if the key is absent.
pub(crate) fn read_file<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
) -> Result<Option<K::Value>> {
    const {
        assert!(
            lists(G::KEYS, K::NAME),
            "the key is not in the key list of its group"
        )
    };
    let Some(raw) = keyfile.get_value(header, K::NAME) else {
        return Ok(None);
    };
    K::Value::parse(raw)
        .map(Some)
        .map_err(|err| value_error(header, K::NAME, raw, err))
}

/// Returns the value in effect of the key `K` in the group `header` of
/// `keyfile` and its source: the forced value of `overrides`, the value of
/// the file, the fallback value of `overrides`, or the default of the key.
///
/// A forced value applies with no read of the file.
fn lookup<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<Option<Lookup<K::Value>>> {
    if let Some(raw) = overrides.and_then(|o| o.forced(header, K::NAME)) {
        return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Forced(v)));
    }
    if let Some(value) = read_file::<G, K>(keyfile, header)? {
        return Ok(Some(Lookup::File(value)));
    }
    if let Some(raw) = overrides.and_then(|o| o.fallback_of(header, K::NAME)) {
        return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Fallback(v)));
    }
    Ok(K::default_value().map(Lookup::Default))
}

/// Returns the value in effect of the key `K` in the group `header` of
/// `keyfile`, as [`lookup`] gives it, as the text of [`Value::format`], or
/// `None` if no source gives a value.
pub(crate) fn lookup_text<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<Option<String>> {
    Ok(lookup::<G, K>(keyfile, header, overrides)?.map(|found| found.into_value().format()))
}

/// Parses `raw`, the text of an override of the key `K` in the group
/// `header`, with the value type of `K`.
fn parse_text<G: Group, K: Key<G>>(header: &str, raw: &str) -> Result<K::Value> {
    K::Value::parse(raw).map_err(|err| value_error(header, K::NAME, raw, err))
}

/// Returns the output of a read of the key `K` in the group `header` of
/// `keyfile`, with the overrides `overrides`.
fn read_in_effect<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<K::Output> {
    let value = lookup::<G, K>(keyfile, header, overrides)?.map(Lookup::into_value);
    K::output(value).ok_or_else(|| Error::InvalidFormat(format!("[{header}] has no {}", K::NAME)))
}