ostrya-core 0.18.0

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
//! The typed reads of a key file.

use super::{
    ConfigError, Group, Key, Lookup, OutputOf, Section, SingleKey, ValueOf, is_section_name,
    lookup, read_file, read_in_effect, refuse_unknown_keys, section_header, section_name,
};
use crate::KeyFile;

/// The typed reads of a key file in the form of `config`.
///
/// The view borrows the key file and holds nothing else. It has no
/// override, so the value in effect of a key is the value of the file or
/// the default of the key, and a lookup gives [`Lookup::File`] or
/// [`Lookup::Default`]. Each read parses the value of the file each time
/// that it is called.
///
/// In the `ostrya` crate, `RepoConfig` gives the same reads of the
/// repository `config`, with the overrides of the repository handle and the
/// remotes directory.
///
/// # Examples
///
/// ```
/// use ostrya_core::KeyFile;
/// use ostrya_core::config::{ConfigError, ConfigView, Lookup, repo};
///
/// ostrya_core::config_group! {
///     pub group image = named "ex-image" {
///         Arch: String = "arch", required;
///     }
/// }
///
/// let kf = KeyFile::parse(
///     "[core]\nrepo_version=1\nmode=bare\nfsync=false\n\
///      [ex-image \"base\"]\narch=x86\n",
/// )?;
/// let view = ConfigView::new(&kf);
/// assert!(!view.get::<repo::Fsync>()?);
/// assert_eq!(view.lookup::<repo::Locking>()?, Some(Lookup::Default(true)));
/// let base = view.section::<image::Group>("base").unwrap();
/// assert_eq!(base.get::<image::Arch>()?, "x86");
/// # Ok::<(), ConfigError>(())
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ConfigView<'a> {
    keyfile: &'a KeyFile,
}

impl<'a> ConfigView<'a> {
    /// Returns the typed reads of `keyfile`.
    pub fn new(keyfile: &'a KeyFile) -> ConfigView<'a> {
        ConfigView { keyfile }
    }

    /// Returns the value in effect of the key `K` of a single group: 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`](super::ValueError) states the text.
    /// - [`ConfigError::InvalidFormat`] if the key is required and absent.
    pub fn get<K>(&self) -> Result<OutputOf<K>, ConfigError>
    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, None)
    }

    /// Returns the value of the key `K` of a single group 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`](super::ValueError) states the text.
    pub fn file_value<K>(&self) -> Result<Option<ValueOf<K>>, ConfigError>
    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 the file does not set the key and the key has no
    /// default.
    ///
    /// The view 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`](super::ValueError) states the text.
    pub fn lookup<K>(&self) -> Result<Option<Lookup<ValueOf<K>>>, ConfigError>
    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, None)
    }

    /// Returns the section `name` of the named group `G`, or `None` if the
    /// file has no such section.
    ///
    /// The call gives `None` for an empty `name` and for a `name` that holds
    /// `"`. [`sections`](ConfigView::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<'a, G>> {
        const { assert!(G::NAMED, "a single group has no section") };
        if !is_section_name(name) {
            return None;
        }
        let keyfile: &'a KeyFile = self.keyfile;
        let header = keyfile.group_name(&section_header::<G>(name))?;
        Some(Section::from_parts(keyfile, header, None))
    }

    /// Returns each section of the named group `G`, in the order of the
    /// file.
    ///
    /// 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<'a, G>> + use<'a, G> {
        const { assert!(G::NAMED, "a single group has no section") };
        let keyfile: &'a KeyFile = self.keyfile;
        keyfile.groups().filter_map(move |header| {
            section_name::<G>(header)?;
            Some(Section::from_parts(keyfile, header, None))
        })
    }

    /// Refuses a key of the group `G` that the closed group does not list.
    ///
    /// For a single group, the call checks the group `[NAME]`. For a named
    /// group, it checks each section of the group, 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.
    ///
    /// # Errors
    ///
    /// [`ConfigError::InvalidFormat`] with the text `[HEADER] holds the
    /// unknown key 'KEY'`, where `HEADER` is the header of the group.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya_core::KeyFile;
    /// use ostrya_core::config::{ConfigError, ConfigView};
    ///
    /// ostrya_core::config_group! {
    ///     pub group tool = "ex-tool", closed {
    ///         Jobs: Option<u32> = "jobs";
    ///     }
    /// }
    ///
    /// let kf = KeyFile::parse("[ex-tool]\njobs=4\n")?;
    /// ConfigView::new(&kf).refuse_unknown_keys::<tool::Group>()?;
    /// let kf = KeyFile::parse("[ex-tool]\nzzz=1\n")?;
    /// assert_eq!(
    ///     ConfigView::new(&kf)
    ///         .refuse_unknown_keys::<tool::Group>()
    ///         .unwrap_err()
    ///         .to_string(),
    ///     "invalid format: [ex-tool] holds the unknown key 'zzz'"
    /// );
    /// # Ok::<(), ConfigError>(())
    /// ```
    pub fn refuse_unknown_keys<G: Group>(&self) -> Result<(), ConfigError> {
        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))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::test_groups::{BASE, test_named, test_single};
    use crate::config::{GroupRef, repo};

    #[test]
    fn a_view_reads_single_keys_with_their_source() {
        let kf = KeyFile::parse(&format!("{BASE}fsync=false\n[ex-test]\njobs=8\n")).unwrap();
        let view = ConfigView::new(&kf);
        assert!(!view.get::<repo::Fsync>().unwrap());
        assert_eq!(view.file_value::<repo::Fsync>().unwrap(), Some(false));
        assert_eq!(
            view.lookup::<repo::Fsync>().unwrap(),
            Some(Lookup::File(false))
        );
        assert!(view.get::<repo::Locking>().unwrap());
        assert_eq!(view.file_value::<repo::Locking>().unwrap(), None);
        assert_eq!(
            view.lookup::<repo::Locking>().unwrap(),
            Some(Lookup::Default(true))
        );
        assert_eq!(view.get::<repo::CollectionId>().unwrap(), None);
        assert_eq!(view.lookup::<repo::CollectionId>().unwrap(), None);
        assert_eq!(view.get::<test_single::Jobs>().unwrap(), 8);
        assert_eq!(view.get::<test_single::Name>().unwrap(), None);
    }

    #[test]
    fn a_view_gives_the_sections_of_a_named_group_in_the_order_of_the_file() {
        let kf = KeyFile::parse(&format!(
            "{BASE}[ex-test n \"b\"]\narch=arm64\nnext=a\n\
             [remote \"o\"]\nurl=http://o/\n\
             [ex-test n \"a\"]\narch=amd64\ntags=x;y;\n\
             [ex-test n \"\"]\narch=amd64\n\
             [ex-test n \"x\" \"y\"]\narch=amd64\n\
             [ex-test n \"c\"]\ntags=z\n\
             [ex-test nx \"d\"]\narch=amd64\n"
        ))
        .unwrap();
        let view = ConfigView::new(&kf);
        let names: Vec<_> = view
            .sections::<test_named::Group>()
            .map(|s| s.name())
            .collect();
        assert_eq!(names, ["b", "a", "c"]);
        assert!(view.section::<test_named::Group>("absent").is_none());
        assert!(view.section::<test_named::Group>("").is_none());
        assert!(view.section::<test_named::Group>("x\" \"y").is_none());

        let b = view.section::<test_named::Group>("b").unwrap();
        assert_eq!(b.name(), "b");
        assert_eq!(b.get::<test_named::Arch>().unwrap(), "arm64");
        assert_eq!(b.get::<test_named::Tags>().unwrap(), Vec::<String>::new());
        assert_eq!(
            b.lookup::<test_named::Tags>().unwrap(),
            Some(Lookup::Default(Vec::new()))
        );
        assert_eq!(b.file_value::<test_named::Tags>().unwrap(), None);
        assert_eq!(
            b.get::<test_named::Next>().unwrap(),
            Some(GroupRef::new("a").unwrap())
        );
        let a = view.section::<test_named::Group>("a").unwrap();
        assert_eq!(a.get::<test_named::Tags>().unwrap(), ["x", "y"]);
        assert_eq!(
            a.lookup::<test_named::Tags>().unwrap(),
            Some(Lookup::File(vec!["x".to_owned(), "y".to_owned()]))
        );

        let c = view.section::<test_named::Group>("c").unwrap();
        let err = c.get::<test_named::Arch>().unwrap_err();
        assert!(matches!(err, ConfigError::InvalidFormat(_)));
        assert_eq!(
            err.to_string(),
            "invalid format: [ex-test n \"c\"] has no arch"
        );
        assert_eq!(c.lookup::<test_named::Arch>().unwrap(), None);
    }

    #[test]
    fn a_view_read_names_the_group_header_in_an_error() {
        let kf = KeyFile::parse(&format!(
            "{BASE}[ex-test]\njobs=-1\n[ex-test n \"a\"]\narch=amd64\nnext=\n\
             [ex-test n \"b\"]\narch=\\q\n"
        ))
        .unwrap();
        let view = ConfigView::new(&kf);
        assert_eq!(
            view.get::<test_single::Jobs>().unwrap_err().to_string(),
            "invalid format: [ex-test] jobs -1 is out of the range 0-4294967295"
        );
        let a = view.section::<test_named::Group>("a").unwrap();
        assert_eq!(
            a.get::<test_named::Next>().unwrap_err().to_string(),
            "invalid format: [ex-test n \"a\"] next is empty"
        );
        let b = view.section::<test_named::Group>("b").unwrap();
        assert_eq!(
            b.get::<test_named::Arch>().unwrap_err().to_string(),
            r"keyfile: invalid escape '\q'"
        );
        crate::config_group! {
            pub group flags = named "ex-flags" {
                On: Option<bool> = "on";
            }
        }
        let kf = KeyFile::parse(&format!("{BASE}[ex-flags \"s\"]\non=x\n")).unwrap();
        let err = ConfigView::new(&kf)
            .section::<flags::Group>("s")
            .unwrap()
            .get::<flags::On>()
            .unwrap_err();
        assert!(matches!(err, ConfigError::Core(_)));
        assert_eq!(
            err.to_string(),
            "keyfile: value 'x' for ex-flags \"s\".on is not a boolean"
        );
    }

    #[test]
    fn a_view_refuses_an_unknown_key_of_a_closed_group() {
        let kf = KeyFile::parse(&format!(
            "{BASE}zzz=1\n[ex-test]\njobs=1\n\
             [ex-test n \"a\"]\narch=amd64\n[ex-test n \"\"]\nyyy=1\n"
        ))
        .unwrap();
        let view = ConfigView::new(&kf);
        view.refuse_unknown_keys::<test_single::Group>().unwrap();
        view.refuse_unknown_keys::<test_named::Group>().unwrap();
        // `[core]` is open, so the call checks nothing.
        view.refuse_unknown_keys::<repo::Group>().unwrap();

        let kf = KeyFile::parse(&format!(
            "{BASE}[ex-test]\njobs=1\nzzz=1\n\
             [ex-test n \"a\"]\narch=amd64\n[ex-test n \"b\"]\nyyy=1\nxxx=1\n"
        ))
        .unwrap();
        let view = ConfigView::new(&kf);
        let err = view
            .refuse_unknown_keys::<test_single::Group>()
            .unwrap_err();
        assert!(matches!(err, ConfigError::InvalidFormat(_)));
        assert_eq!(
            err.to_string(),
            "invalid format: [ex-test] holds the unknown key 'zzz'"
        );
        assert_eq!(
            view.refuse_unknown_keys::<test_named::Group>()
                .unwrap_err()
                .to_string(),
            "invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
        );
        let a = view.section::<test_named::Group>("a").unwrap();
        a.refuse_unknown_keys().unwrap();
        let b = view.section::<test_named::Group>("b").unwrap();
        assert_eq!(
            b.refuse_unknown_keys().unwrap_err().to_string(),
            "invalid format: [ex-test n \"b\"] holds the unknown key 'yyy'"
        );
    }
}