Skip to main content

ostrya_core/config/
section.rs

1//! One section of a named group, and the file that holds a remote.
2
3use std::marker::PhantomData;
4
5use super::{ConfigError, Group, Key, Lookup, read_file, read_in_effect, refuse_unknown_keys};
6use crate::KeyFile;
7
8/// One section of the named group `G`.
9///
10/// [`ConfigView::section`](super::ConfigView::section) and
11/// [`ConfigView::sections`](super::ConfigView::sections) give a section. In
12/// the `ostrya` crate, `RepoConfig::section`, `RepoConfig::sections`, and
13/// `RepoConfig::resolve` also give a section. A read takes a key of the
14/// group `G` alone, and parses the value of the file each time that it is
15/// called.
16///
17/// A section of the group `remote` of the `ostrya` crate comes from
18/// `config` or from a `.conf` file of the remotes directory, and
19/// [`source`](Section::source) names the file. A section of each other group
20/// comes from `config`.
21pub struct Section<'a, G: Group> {
22    keyfile: &'a KeyFile,
23    /// The group header, `NAME "SECTION"`.
24    header: &'a str,
25    /// The name of the `.conf` file that holds the section, or `None` for
26    /// `config`.
27    file: Option<&'a str>,
28    group: PhantomData<fn() -> G>,
29}
30
31impl<G: Group> Clone for Section<'_, G> {
32    fn clone(&self) -> Self {
33        Section {
34            keyfile: self.keyfile,
35            header: self.header,
36            file: self.file,
37            group: PhantomData,
38        }
39    }
40}
41
42impl<G: Group> std::fmt::Debug for Section<'_, G> {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("Section")
45            .field("header", &self.header)
46            .field("file", &self.file)
47            .finish()
48    }
49}
50
51impl<'a, G: Group> Section<'a, G> {
52    /// Returns a section of `G` over the group `header` of `keyfile`.
53    ///
54    /// `file` is the name of the `.conf` file that holds the section, or
55    /// `None` for `config`.
56    #[doc(hidden)]
57    pub fn from_parts(keyfile: &'a KeyFile, header: &'a str, file: Option<&'a str>) -> Self {
58        Section {
59            keyfile,
60            header,
61            file,
62            group: PhantomData,
63        }
64    }
65
66    /// Returns the key file that holds the section.
67    #[doc(hidden)]
68    pub fn keyfile(&self) -> &'a KeyFile {
69        self.keyfile
70    }
71
72    /// Returns the group header of the section, `NAME "SECTION"`.
73    #[doc(hidden)]
74    pub fn header(&self) -> &'a str {
75        self.header
76    }
77
78    /// Returns the name of the section: `SECTION` of the header
79    /// `NAME "SECTION"`.
80    pub fn name(&self) -> &'a str {
81        let header: &'a str = self.header;
82        header
83            .split_once('"')
84            .and_then(|(_, rest)| rest.strip_suffix('"'))
85            .unwrap_or_default()
86    }
87
88    /// Returns the file that holds the section: `config`, or a `.conf` file
89    /// of the remotes directory.
90    ///
91    /// Only a section of the group `remote` of the `ostrya` crate can come
92    /// from a `.conf` file. A section of each other group, and each section
93    /// of a [`ConfigView`](super::ConfigView), gives
94    /// [`RemoteSource::Config`].
95    pub fn source(&self) -> RemoteSource<'a> {
96        match self.file {
97            None => RemoteSource::Config,
98            Some(file) => RemoteSource::File(file),
99        }
100    }
101
102    /// Returns the value in effect of the key `K`: the value of the file, or
103    /// the default of the key if the file does not set it.
104    ///
105    /// The result type is [`Key::Output`]. It is `Option<V>` for a key with
106    /// no default that is not required.
107    ///
108    /// # Errors
109    ///
110    /// - The error of the value type if the value does not parse.
111    ///   [`ValueError`](super::ValueError) states the text.
112    /// - [`ConfigError::InvalidFormat`] if the key is required and absent.
113    pub fn get<K: Key<G>>(&self) -> Result<K::Output, ConfigError> {
114        read_in_effect::<G, K>(self.keyfile, self.header, None)
115    }
116
117    /// Returns the value of the key `K` in the file, or `None` if the file
118    /// does not set it. The default of the key does not apply.
119    ///
120    /// # Errors
121    ///
122    /// The error of the value type if the value does not parse.
123    /// [`ValueError`](super::ValueError) states the text.
124    pub fn file_value<K: Key<G>>(&self) -> Result<Option<K::Value>, ConfigError> {
125        read_file::<G, K>(self.keyfile, self.header)
126    }
127
128    /// Returns the value in effect of the key `K` and its source, or `None`
129    /// if the file does not set the key and the key has no default.
130    ///
131    /// A section has no override, so the source is [`Lookup::File`] or
132    /// [`Lookup::Default`].
133    ///
134    /// # Errors
135    ///
136    /// The error of the value type if the value does not parse.
137    /// [`ValueError`](super::ValueError) states the text.
138    pub fn lookup<K: Key<G>>(&self) -> Result<Option<Lookup<K::Value>>, ConfigError> {
139        super::lookup::<G, K>(self.keyfile, self.header, None)
140    }
141
142    /// Refuses a key of the section that the closed group `G` does not list.
143    ///
144    /// The call checks nothing if [`Group::CLOSED`] of `G` is `false`. It
145    /// checks each key against the key list of `G` alone, and gives the
146    /// unknown-key text for a key outside the list. It names the first such
147    /// key in the order of the file. The `ostrya` crate applies this check to
148    /// its own closed groups. A library user calls it for a closed group of
149    /// its own.
150    ///
151    /// For the removed key `collection` of a client group of the `ostrya`
152    /// crate, the call gives the unknown-key text. `RepoConfig::check` gives
153    /// a text that starts with `[HEADER] holds the removed key 'collection'`
154    /// for this key.
155    ///
156    /// For the keys `gpg-verify-summary`, `sign-verify-summary`, and
157    /// `verification-ENGINE-key` and `verification-ENGINE-file` of an engine
158    /// other than `ed25519` and `spki` in a trust group of the `ostrya`
159    /// crate, the call also gives the unknown-key text. `RepoConfig::check`
160    /// and the readers of a trust group give a text that states the reason.
161    ///
162    /// # Errors
163    ///
164    /// [`ConfigError::InvalidFormat`] with the text `[HEADER] holds the
165    /// unknown key 'KEY'`, where `HEADER` is the header of the section.
166    ///
167    /// # Examples
168    ///
169    /// ```
170    /// use ostrya_core::KeyFile;
171    /// use ostrya_core::config::{ConfigError, ConfigView};
172    ///
173    /// ostrya_core::config_group! {
174    ///     pub group image = named "ex-image", closed {
175    ///         Arch: Option<String> = "arch";
176    ///     }
177    /// }
178    ///
179    /// let kf = KeyFile::parse("[ex-image \"base\"]\narch=x86\nzzz=1\n")?;
180    /// let view = ConfigView::new(&kf);
181    /// let base = view.section::<image::Group>("base").unwrap();
182    /// assert_eq!(
183    ///     base.refuse_unknown_keys().unwrap_err().to_string(),
184    ///     "invalid format: [ex-image \"base\"] holds the unknown key 'zzz'"
185    /// );
186    /// # Ok::<(), ConfigError>(())
187    /// ```
188    pub fn refuse_unknown_keys(&self) -> Result<(), ConfigError> {
189        refuse_unknown_keys::<G>(self.keyfile, self.header)
190    }
191}
192
193/// The file that holds a remote.
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195pub enum RemoteSource<'a> {
196    /// The `config` file of the repository.
197    Config,
198    /// A `.conf` file of the remotes directory, by its name in that
199    /// directory, for example `origin.conf`.
200    File(&'a str),
201}
202
203#[cfg(test)]
204mod tests {
205    use super::*;
206    use crate::config::ConfigView;
207    use crate::config::test_groups::{BASE, test_named};
208
209    #[test]
210    fn the_source_of_a_section_names_its_file() {
211        let kf = KeyFile::parse(&format!("{BASE}[ex-test n \"a\"]\narch=amd64\n")).unwrap();
212        let a = ConfigView::new(&kf)
213            .section::<test_named::Group>("a")
214            .unwrap();
215        assert_eq!(a.source(), RemoteSource::Config);
216        assert_eq!(a.header(), "ex-test n \"a\"");
217        assert!(std::ptr::eq(a.keyfile(), &kf));
218
219        let a = Section::<test_named::Group>::from_parts(&kf, "ex-test n \"a\"", Some("a.conf"));
220        assert_eq!(a.source(), RemoteSource::File("a.conf"));
221        assert_eq!(a.name(), "a");
222        assert_eq!(a.get::<test_named::Arch>().unwrap(), "amd64");
223        let copy = a.clone();
224        assert_eq!(copy.source(), RemoteSource::File("a.conf"));
225        assert_eq!(
226            format!("{copy:?}"),
227            "Section { header: \"ex-test n \\\"a\\\"\", file: Some(\"a.conf\") }"
228        );
229    }
230}