ostrya-core 0.19.1

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
//! The typed writes of the document of `config`.

use std::marker::PhantomData;

use super::{ConfigError, Group, Key, SingleKey, Value, ValueOf, lists, section_header};
use crate::KeyFile;

/// An edit of the document of `config`.
///
/// The edit changes the document in memory. It does no file I/O. Each write
/// stores the text of [`Value::format`], and the other keys and groups keep
/// their order and their text. A write takes each key of a single group,
/// also a key that is not [`Settable`](super::Settable).
///
/// [`ConfigEdit::new`] gives an edit of a key file. In the `ostrya` crate,
/// `UpdateGuard::edit_config` gives an edit of the document of `config`,
/// and writes the edited document.
pub struct ConfigEdit<'a> {
    keyfile: &'a mut KeyFile,
}

impl<'a> ConfigEdit<'a> {
    /// Returns an edit of `keyfile`.
    ///
    /// # Examples
    ///
    /// ```
    /// use ostrya_core::KeyFile;
    /// use ostrya_core::config::{ConfigEdit, ConfigError, ConfigView, repo};
    ///
    /// let mut kf = KeyFile::parse("[core]\nrepo_version=1\nmode=bare\n")?;
    /// ConfigEdit::new(&mut kf).set::<repo::Fsync>(false)?;
    /// assert_eq!(kf.get_value("core", "fsync"), Some("false"));
    /// assert!(!ConfigView::new(&kf).get::<repo::Fsync>()?);
    /// # Ok::<(), ConfigError>(())
    /// ```
    pub fn new(keyfile: &'a mut KeyFile) -> ConfigEdit<'a> {
        ConfigEdit { keyfile }
    }

    /// Sets the key `K` of a single group to `value`.
    ///
    /// If the key is present, the new value replaces the old value at the
    /// same position. If the key is absent, the call adds it at the end of
    /// its group. If the group is absent, the call adds it at the end of the
    /// document.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Core`] if the text of the value cannot be in a key
    /// file, for example a text with a line break. The document then does not
    /// change.
    pub fn set<K>(&mut self, value: ValueOf<K>) -> Result<(), ConfigError>
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        set_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME, value)
    }

    /// Removes the key `K` of a single group, and returns `true` if the key
    /// was present.
    ///
    /// The group stays, also when it loses its last key.
    pub fn remove<K>(&mut self) -> bool
    where
        K: SingleKey + Key<<K as SingleKey>::Group>,
    {
        const { assert!(!<K as SingleKey>::Group::NAMED, "a key of a named group") };
        remove_key::<K::Group, K>(self.keyfile, <K as SingleKey>::Group::NAME)
    }

    /// Returns the edit of the section `name` of the named group `G`.
    ///
    /// The call does not add the section. The first
    /// [`set`](SectionMut::set) adds it at the end of the document.
    ///
    /// # Errors
    ///
    /// [`ConfigError::InvalidInput`] if `name` is empty, or holds `[`, `]`,
    /// `"`, or a line break. A key file cannot hold such a group header, and
    /// a read of a section does not take such a name.
    pub fn section_mut<G: Group>(&mut self, name: &str) -> Result<SectionMut<'_, G>, ConfigError> {
        const { assert!(G::NAMED, "a single group has no section") };
        if name.is_empty() {
            return Err(ConfigError::InvalidInput(format!(
                "the section name of a [{} \"NAME\"] group is empty",
                G::NAME
            )));
        }
        if name.contains(['[', ']', '"', '\n', '\r']) {
            return Err(ConfigError::InvalidInput(format!(
                "the section name {name:?} of a [{} \"NAME\"] group holds '[', ']', '\"', or a \
                 line break",
                G::NAME
            )));
        }
        Ok(SectionMut {
            keyfile: self.keyfile,
            header: section_header::<G>(name),
            group: PhantomData,
        })
    }

    /// Removes the section `name` of the named group `G` with its keys, and
    /// returns `true` if the section was present.
    pub fn remove_section<G: Group>(&mut self, name: &str) -> bool {
        const { assert!(G::NAMED, "a single group has no section") };
        self.keyfile.remove_group(&section_header::<G>(name))
    }

    /// Returns the document, for an edit that the typed writes do not cover.
    pub fn keyfile_mut(&mut self) -> &mut KeyFile {
        self.keyfile
    }
}

/// The edit of one section of the named group `G`.
///
/// [`ConfigEdit::section_mut`] gives it.
pub struct SectionMut<'e, G: Group> {
    keyfile: &'e mut KeyFile,
    /// The group header, `NAME "SECTION"`.
    header: String,
    group: PhantomData<fn() -> G>,
}

impl<G: Group> SectionMut<'_, G> {
    /// Returns the name of the section.
    pub fn name(&self) -> &str {
        &self.header[G::NAME.len() + 2..self.header.len() - 1]
    }

    /// Sets the key `K` of the section to `value`.
    ///
    /// If the section is absent, the call adds it at the end of the
    /// document. The key takes its position as
    /// [`ConfigEdit::set`] states.
    ///
    /// # Errors
    ///
    /// [`ConfigError::Core`] if the text of the value cannot be in a key
    /// file, for example a text with a line break. The document then does not
    /// change.
    pub fn set<K: Key<G>>(&mut self, value: K::Value) -> Result<(), ConfigError> {
        set_key::<G, K>(self.keyfile, &self.header, value)
    }

    /// Removes the key `K` of the section, and returns `true` if the key was
    /// present.
    pub fn remove<K: Key<G>>(&mut self) -> bool {
        remove_key::<G, K>(self.keyfile, &self.header)
    }
}

/// Sets the key `K` in the group `header` of `keyfile` to `value`.
fn set_key<G: Group, K: Key<G>>(
    keyfile: &mut KeyFile,
    header: &str,
    value: K::Value,
) -> Result<(), ConfigError> {
    const {
        assert!(
            lists(G::KEYS, K::NAME),
            "the key is not in the key list of its group"
        )
    };
    keyfile.set_value(header, K::NAME, &value.format())?;
    Ok(())
}

/// Removes the key `K` from the group `header` of `keyfile`.
fn remove_key<G: Group, K: Key<G>>(keyfile: &mut KeyFile, header: &str) -> bool {
    const {
        assert!(
            lists(G::KEYS, K::NAME),
            "the key is not in the key list of its group"
        )
    };
    keyfile.remove_key(header, K::NAME)
}

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

    #[test]
    fn config_edit_writes_sections() {
        let mut kf = KeyFile::parse(BASE).unwrap();
        let mut edit = ConfigEdit::new(&mut kf);
        let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
        assert_eq!(section.name(), "n");
        section.set::<test_named::Arch>("amd64".to_owned()).unwrap();
        section
            .set::<test_named::Next>(GroupRef::new("m").unwrap())
            .unwrap();
        assert!(section.remove::<test_named::Next>());
        assert!(!section.remove::<test_named::Next>());
        assert!(edit.section_mut::<test_named::Group>("unused").is_ok());
        for bad in ["", "a]b", "a[b", "a\"b", "a\nb"] {
            assert!(
                matches!(
                    edit.section_mut::<test_named::Group>(bad),
                    Err(ConfigError::InvalidInput(_))
                ),
                "{bad:?}"
            );
        }
        assert_eq!(
            kf.to_string(),
            "[core]\nrepo_version=1\nmode=bare\n\n[ex-test n \"n\"]\narch=amd64\n"
        );
        let mut edit = ConfigEdit::new(&mut kf);
        assert!(edit.remove_section::<test_named::Group>("n"));
        assert!(!edit.remove_section::<test_named::Group>("n"));
        assert_eq!(kf.to_string(), BASE);
    }

    #[test]
    fn config_edit_escapes_a_value_and_refuses_a_quote_in_a_section_name() {
        let mut kf = KeyFile::parse(BASE).unwrap();
        let before = kf.clone();
        let mut edit = ConfigEdit::new(&mut kf);
        let mut section = edit.section_mut::<test_named::Group>("n").unwrap();
        // `format` of a `String` escapes a line break, so a value with one
        // is written.
        section.set::<test_named::Arch>("a\nb".to_owned()).unwrap();
        assert_eq!(kf.get_value("ex-test n \"n\"", "arch"), Some("a\\nb"));
        let mut kf = before.clone();
        let mut edit = ConfigEdit::new(&mut kf);
        let err = edit.section_mut::<test_named::Group>("x\"y").err().unwrap();
        assert_eq!(
            err.to_string(),
            "invalid input: the section name \"x\\\"y\" of a [ex-test n \"NAME\"] group holds \
             '[', ']', '\"', or a line break"
        );
        assert_eq!(kf.to_string(), before.to_string());
    }
}