ostrya-core 0.19.0

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
//! One section of a named group, and the file that holds a remote.

use std::marker::PhantomData;

use super::{ConfigError, Group, Key, Lookup, read_file, read_in_effect, refuse_unknown_keys};
use crate::KeyFile;

/// One section of the named group `G`.
///
/// [`ConfigView::section`](super::ConfigView::section) and
/// [`ConfigView::sections`](super::ConfigView::sections) give a section. In
/// the `ostrya` crate, `RepoConfig::section`, `RepoConfig::sections`, and
/// `RepoConfig::resolve` also 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 the group `remote` of the `ostrya` crate 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 a section of `G` over the group `header` of `keyfile`.
    ///
    /// `file` is the name of the `.conf` file that holds the section, or
    /// `None` for `config`.
    #[doc(hidden)]
    pub fn from_parts(keyfile: &'a KeyFile, header: &'a str, file: Option<&'a str>) -> Self {
        Section {
            keyfile,
            header,
            file,
            group: PhantomData,
        }
    }

    /// Returns the key file that holds the section.
    #[doc(hidden)]
    pub fn keyfile(&self) -> &'a KeyFile {
        self.keyfile
    }

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

    /// 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 file that holds the section: `config`, or a `.conf` file
    /// of the remotes directory.
    ///
    /// Only a section of the group `remote` of the `ostrya` crate can come
    /// from a `.conf` file. A section of each other group, and each section
    /// of a [`ConfigView`](super::ConfigView), gives
    /// [`RemoteSource::Config`].
    pub fn source(&self) -> RemoteSource<'a> {
        match self.file {
            None => RemoteSource::Config,
            Some(file) => RemoteSource::File(file),
        }
    }

    /// 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`](super::ValueError) states the text.
    /// - [`ConfigError::InvalidFormat`] if the key is required and absent.
    pub fn get<K: Key<G>>(&self) -> Result<K::Output, ConfigError> {
        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`](super::ValueError) states the text.
    pub fn file_value<K: Key<G>>(&self) -> Result<Option<K::Value>, ConfigError> {
        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`](super::ValueError) states the text.
    pub fn lookup<K: Key<G>>(&self) -> Result<Option<Lookup<K::Value>>, ConfigError> {
        super::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 `ostrya` 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 of the `ostrya`
    /// crate, 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 of the `ostrya`
    /// crate, the call also gives the unknown-key text. `RepoConfig::check`
    /// and the readers of a trust group give a text that states the reason.
    ///
    /// # Errors
    ///
    /// [`ConfigError::InvalidFormat`] with the text `[HEADER] holds the
    /// unknown key 'KEY'`, where `HEADER` is the header of the section.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya_core::KeyFile;
    /// use ostrya_core::config::{ConfigError, ConfigView};
    ///
    /// ostrya_core::config_group! {
    ///     pub group image = named "ex-image", closed {
    ///         Arch: Option<String> = "arch";
    ///     }
    /// }
    ///
    /// let kf = KeyFile::parse("[ex-image \"base\"]\narch=x86\nzzz=1\n")?;
    /// let view = ConfigView::new(&kf);
    /// let base = view.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::<(), ConfigError>(())
    /// ```
    pub fn refuse_unknown_keys(&self) -> Result<(), ConfigError> {
        refuse_unknown_keys::<G>(self.keyfile, self.header)
    }
}

/// The file that holds a remote.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RemoteSource<'a> {
    /// The `config` file of the repository.
    Config,
    /// A `.conf` file of the remotes directory, by its name in that
    /// directory, for example `origin.conf`.
    File(&'a str),
}

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

    #[test]
    fn the_source_of_a_section_names_its_file() {
        let kf = KeyFile::parse(&format!("{BASE}[ex-test n \"a\"]\narch=amd64\n")).unwrap();
        let a = ConfigView::new(&kf)
            .section::<test_named::Group>("a")
            .unwrap();
        assert_eq!(a.source(), RemoteSource::Config);
        assert_eq!(a.header(), "ex-test n \"a\"");
        assert!(std::ptr::eq(a.keyfile(), &kf));

        let a = Section::<test_named::Group>::from_parts(&kf, "ex-test n \"a\"", Some("a.conf"));
        assert_eq!(a.source(), RemoteSource::File("a.conf"));
        assert_eq!(a.name(), "a");
        assert_eq!(a.get::<test_named::Arch>().unwrap(), "amd64");
        let copy = a.clone();
        assert_eq!(copy.source(), RemoteSource::File("a.conf"));
        assert_eq!(
            format!("{copy:?}"),
            "Section { header: \"ex-test n \\\"a\\\"\", file: Some(\"a.conf\") }"
        );
    }
}