Skip to main content

ostrya_core/config/
view.rs

1//! The typed reads of a key file.
2
3use super::{
4    ConfigError, Group, Key, Lookup, OutputOf, Section, SingleKey, ValueOf, is_section_name,
5    lookup, read_file, read_in_effect, refuse_unknown_keys, section_header, section_name,
6};
7use crate::KeyFile;
8
9/// The typed reads of a key file in the form of `config`.
10///
11/// The view borrows the key file and holds nothing else. It has no
12/// override, so the value in effect of a key is the value of the file or
13/// the default of the key, and a lookup gives [`Lookup::File`] or
14/// [`Lookup::Default`]. Each read parses the value of the file each time
15/// that it is called.
16///
17/// In the `ostrya` crate, `RepoConfig` gives the same reads of the
18/// repository `config`, with the overrides of the repository handle and the
19/// remotes directory.
20///
21/// # Examples
22///
23/// ```
24/// use ostrya_core::KeyFile;
25/// use ostrya_core::config::{ConfigError, ConfigView, Lookup, repo};
26///
27/// ostrya_core::config_group! {
28///     pub group image = named "ex-image" {
29///         Arch: String = "arch", required;
30///     }
31/// }
32///
33/// let kf = KeyFile::parse(
34///     "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\
35///      [ex-image \"base\"]\narch=x86\n",
36/// )?;
37/// let view = ConfigView::new(&kf);
38/// assert!(!view.get::<repo::Fsync>()?);
39/// assert_eq!(view.lookup::<repo::Locking>()?, Some(Lookup::Default(true)));
40/// let base = view.section::<image::Group>("base").unwrap();
41/// assert_eq!(base.get::<image::Arch>()?, "x86");
42/// # Ok::<(), ConfigError>(())
43/// ```
44#[derive(Debug, Clone, Copy)]
45pub struct ConfigView<'a> {
46    keyfile: &'a KeyFile,
47}
48
49impl<'a> ConfigView<'a> {
50    /// Returns the typed reads of `keyfile`.
51    pub fn new(keyfile: &'a KeyFile) -> ConfigView<'a> {
52        ConfigView { keyfile }
53    }
54
55    /// Returns the value in effect of the key `K` of a single group: the
56    /// value of the file, or the default of the key if the file does not set
57    /// it.
58    ///
59    /// The result type is [`Key::Output`]. It is `Option<V>` for a key with
60    /// no default that is not required.
61    ///
62    /// # Errors
63    ///
64    /// - The error of the value type if the value does not parse.
65    ///   [`ValueError`](super::ValueError) states the text.
66    /// - [`ConfigError::InvalidFormat`] if the key is required and absent.
67    pub fn get<K>(&self) -> Result<OutputOf<K>, ConfigError>
68    where
69        K: SingleKey + Key<<K as SingleKey>::Group>,
70    {
71        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
72        read_in_effect::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, None)
73    }
74
75    /// Returns the value of the key `K` of a single group in the file, or
76    /// `None` if the file does not set it. The default of the key does not
77    /// apply.
78    ///
79    /// # Errors
80    ///
81    /// The error of the value type if the value does not parse.
82    /// [`ValueError`](super::ValueError) states the text.
83    pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>, ConfigError>
84    where
85        K: SingleKey + Key<<K as SingleKey>::Group>,
86    {
87        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
88        read_file::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME)
89    }
90
91    /// Returns the value in effect of the key `K` of a single group and its
92    /// source, or `None` if the file does not set the key and the key has no
93    /// default.
94    ///
95    /// The view has no override, so the source is [`Lookup::File`] or
96    /// [`Lookup::Default`].
97    ///
98    /// # Errors
99    ///
100    /// The error of the value type if the value does not parse.
101    /// [`ValueError`](super::ValueError) states the text.
102    pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>, ConfigError>
103    where
104        K: SingleKey + Key<<K as SingleKey>::Group>,
105    {
106        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
107        lookup::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, None)
108    }
109
110    /// Returns the section `name` of the named group `G`, or `None` if the
111    /// file has no such section.
112    ///
113    /// The call gives `None` for an empty `name` and for a `name` that holds
114    /// `"`. [`sections`](ConfigView::sections) skips the headers of such
115    /// sections, so they are not sections of the group.
116    pub fn section<G: Group>(&self, name: &str) -> Option<Section<'a, G>> {
117        const { assert!(G::NAMED, "a single group has no section") };
118        if !is_section_name(name) {
119            return None;
120        }
121        let keyfile: &'a KeyFile = self.keyfile;
122        let header = keyfile.group_name(&section_header::<G>(name))?;
123        Some(Section::from_parts(keyfile, header, None))
124    }
125
126    /// Returns each section of the named group `G`, in the order of the
127    /// file.
128    ///
129    /// The call skips a header of the group whose section name is empty or
130    /// holds `"`, for example `[NAME ""]` or `[NAME "a" "b"]`.
131    pub fn sections<G: Group>(&self) -> impl Iterator<Item = Section<'a, G>> + use<'a, G> {
132        const { assert!(G::NAMED, "a single group has no section") };
133        let keyfile: &'a KeyFile = self.keyfile;
134        keyfile.groups().filter_map(move |header| {
135            section_name::<G>(header)?;
136            Some(Section::from_parts(keyfile, header, None))
137        })
138    }
139
140    /// Refuses a key of the group `G` that the closed group does not list.
141    ///
142    /// For a single group, the call checks the group `[NAME]`. For a named
143    /// group, it checks each section of the group, in the order of the file,
144    /// as [`Section::refuse_unknown_keys`] does. The call checks nothing if
145    /// [`Group::CLOSED`] of `G` is `false`. It checks each key against the
146    /// key list of `G` alone, and gives the unknown-key text for a key
147    /// outside the list. It names the first such key in the order of the
148    /// file.
149    ///
150    /// # Errors
151    ///
152    /// [`ConfigError::InvalidFormat`] with the text `[HEADER] holds the
153    /// unknown key 'KEY'`, where `HEADER` is the header of the group.
154    ///
155    /// # Examples
156    ///
157    /// ```
158    /// use ostrya_core::KeyFile;
159    /// use ostrya_core::config::{ConfigError, ConfigView};
160    ///
161    /// ostrya_core::config_group! {
162    ///     pub group tool = "ex-tool", closed {
163    ///         Jobs: Option<u32> = "jobs";
164    ///     }
165    /// }
166    ///
167    /// let kf = KeyFile::parse("[ex-tool]\njobs=4\n")?;
168    /// ConfigView::new(&kf).refuse_unknown_keys::<tool::Group>()?;
169    /// let kf = KeyFile::parse("[ex-tool]\nzzz=1\n")?;
170    /// assert_eq!(
171    ///     ConfigView::new(&kf)
172    ///         .refuse_unknown_keys::<tool::Group>()
173    ///         .unwrap_err()
174    ///         .to_string(),
175    ///     "invalid format: [ex-tool] holds the unknown key 'zzz'"
176    /// );
177    /// # Ok::<(), ConfigError>(())
178    /// ```
179    pub fn refuse_unknown_keys<G: Group>(&self) -> Result<(), ConfigError> {
180        if !G::CLOSED {
181            return Ok(());
182        }
183        if !G::NAMED {
184            return refuse_unknown_keys::<G>(self.keyfile, G::NAME);
185        }
186        self.keyfile
187            .groups()
188            .filter(|header| section_name::<G>(header).is_some())
189            .try_for_each(|header| refuse_unknown_keys::<G>(self.keyfile, header))
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::config::test_groups::{BASE, test_named, test_single};
197    use crate::config::{GroupRef, repo};
198
199    #[test]
200    fn a_view_reads_single_keys_with_their_source() {
201        let kf = KeyFile::parse(&format!("{BASE}fsync=false\n[ex-test]\njobs=8\n")).unwrap();
202        let view = ConfigView::new(&kf);
203        assert!(!view.get::<repo::Fsync>().unwrap());
204        assert_eq!(view.file_value::<repo::Fsync>().unwrap(), Some(false));
205        assert_eq!(
206            view.lookup::<repo::Fsync>().unwrap(),
207            Some(Lookup::File(false))
208        );
209        assert!(view.get::<repo::Locking>().unwrap());
210        assert_eq!(view.file_value::<repo::Locking>().unwrap(), None);
211        assert_eq!(
212            view.lookup::<repo::Locking>().unwrap(),
213            Some(Lookup::Default(true))
214        );
215        assert_eq!(view.get::<repo::CollectionId>().unwrap(), None);
216        assert_eq!(view.lookup::<repo::CollectionId>().unwrap(), None);
217        assert_eq!(view.get::<test_single::Jobs>().unwrap(), 8);
218        assert_eq!(view.get::<test_single::Name>().unwrap(), None);
219    }
220
221    #[test]
222    fn a_view_gives_the_sections_of_a_named_group_in_the_order_of_the_file() {
223        let kf = KeyFile::parse(&format!(
224            "{BASE}[ex-test n \"b\"]\narch=arm64\nnext=a\n\
225             [remote \"o\"]\nurl=http://o/\n\
226             [ex-test n \"a\"]\narch=amd64\ntags=x;y;\n\
227             [ex-test n \"\"]\narch=amd64\n\
228             [ex-test n \"x\" \"y\"]\narch=amd64\n\
229             [ex-test n \"c\"]\ntags=z\n\
230             [ex-test nx \"d\"]\narch=amd64\n"
231        ))
232        .unwrap();
233        let view = ConfigView::new(&kf);
234        let names: Vec<_> = view
235            .sections::<test_named::Group>()
236            .map(|s| s.name())
237            .collect();
238        assert_eq!(names, ["b", "a", "c"]);
239        assert!(view.section::<test_named::Group>("absent").is_none());
240        assert!(view.section::<test_named::Group>("").is_none());
241        assert!(view.section::<test_named::Group>("x\" \"y").is_none());
242
243        let b = view.section::<test_named::Group>("b").unwrap();
244        assert_eq!(b.name(), "b");
245        assert_eq!(b.get::<test_named::Arch>().unwrap(), "arm64");
246        assert_eq!(b.get::<test_named::Tags>().unwrap(), Vec::<String>::new());
247        assert_eq!(
248            b.lookup::<test_named::Tags>().unwrap(),
249            Some(Lookup::Default(Vec::new()))
250        );
251        assert_eq!(b.file_value::<test_named::Tags>().unwrap(), None);
252        assert_eq!(
253            b.get::<test_named::Next>().unwrap(),
254            Some(GroupRef::new("a").unwrap())
255        );
256        let a = view.section::<test_named::Group>("a").unwrap();
257        assert_eq!(a.get::<test_named::Tags>().unwrap(), ["x", "y"]);
258        assert_eq!(
259            a.lookup::<test_named::Tags>().unwrap(),
260            Some(Lookup::File(vec!["x".to_owned(), "y".to_owned()]))
261        );
262
263        let c = view.section::<test_named::Group>("c").unwrap();
264        let err = c.get::<test_named::Arch>().unwrap_err();
265        assert!(matches!(err, ConfigError::InvalidFormat(_)));
266        assert_eq!(
267            err.to_string(),
268            "invalid format: [ex-test n \"c\"] has no arch"
269        );
270        assert_eq!(c.lookup::<test_named::Arch>().unwrap(), None);
271    }
272
273    #[test]
274    fn a_view_read_names_the_group_header_in_an_error() {
275        let kf = KeyFile::parse(&format!(
276            "{BASE}[ex-test]\njobs=-1\n[ex-test n \"a\"]\narch=amd64\nnext=\n\
277             [ex-test n \"b\"]\narch=\\q\n"
278        ))
279        .unwrap();
280        let view = ConfigView::new(&kf);
281        assert_eq!(
282            view.get::<test_single::Jobs>().unwrap_err().to_string(),
283            "invalid format: [ex-test] jobs -1 is out of the range 0-4294967295"
284        );
285        let a = view.section::<test_named::Group>("a").unwrap();
286        assert_eq!(
287            a.get::<test_named::Next>().unwrap_err().to_string(),
288            "invalid format: [ex-test n \"a\"] next is empty"
289        );
290        let b = view.section::<test_named::Group>("b").unwrap();
291        assert_eq!(
292            b.get::<test_named::Arch>().unwrap_err().to_string(),
293            r"keyfile: invalid escape '\q'"
294        );
295        crate::config_group! {
296            pub group flags = named "ex-flags" {
297                On: Option<bool> = "on";
298            }
299        }
300        let kf = KeyFile::parse(&format!("{BASE}[ex-flags \"s\"]\non=x\n")).unwrap();
301        let err = ConfigView::new(&kf)
302            .section::<flags::Group>("s")
303            .unwrap()
304            .get::<flags::On>()
305            .unwrap_err();
306        assert!(matches!(err, ConfigError::Core(_)));
307        assert_eq!(
308            err.to_string(),
309            "keyfile: value 'x' for ex-flags \"s\".on is not a boolean"
310        );
311    }
312
313    #[test]
314    fn a_view_refuses_an_unknown_key_of_a_closed_group() {
315        let kf = KeyFile::parse(&format!(
316            "{BASE}zzz=1\n[ex-test]\njobs=1\n\
317             [ex-test n \"a\"]\narch=amd64\n[ex-test n \"\"]\nyyy=1\n"
318        ))
319        .unwrap();
320        let view = ConfigView::new(&kf);
321        view.refuse_unknown_keys::<test_single::Group>().unwrap();
322        view.refuse_unknown_keys::<test_named::Group>().unwrap();
323        // `[core]` is open, so the call checks nothing.
324        view.refuse_unknown_keys::<repo::Group>().unwrap();
325
326        let kf = KeyFile::parse(&format!(
327            "{BASE}[ex-test]\njobs=1\nzzz=1\n\
328             [ex-test n \"a\"]\narch=amd64\n[ex-test n \"b\"]\nyyy=1\nxxx=1\n"
329        ))
330        .unwrap();
331        let view = ConfigView::new(&kf);
332        let err = view
333            .refuse_unknown_keys::<test_single::Group>()
334            .unwrap_err();
335        assert!(matches!(err, ConfigError::InvalidFormat(_)));
336        assert_eq!(
337            err.to_string(),
338            "invalid format: [ex-test] holds the unknown key 'zzz'"
339        );
340        assert_eq!(
341            view.refuse_unknown_keys::<test_named::Group>()
342                .unwrap_err()
343                .to_string(),
344            "invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
345        );
346        let a = view.section::<test_named::Group>("a").unwrap();
347        a.refuse_unknown_keys().unwrap();
348        let b = view.section::<test_named::Group>("b").unwrap();
349        assert_eq!(
350            b.refuse_unknown_keys().unwrap_err().to_string(),
351            "invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
352        );
353    }
354}