ostrya 0.17.0

Pure-Rust async reimplementation of the ostree repository library
Documentation
//! The typed writes of the document of `config`.

use std::marker::PhantomData;

use ostrya_core::KeyFile;

use super::section::section_header;
use super::typed::{ValueOf, lists};
use super::value::Value;
use super::{Group, Key, SingleKey};
use crate::error::{Error, Result};

/// 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).
///
/// [`UpdateGuard::edit_config`](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`.
    pub(crate) 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
    ///
    /// [`Error::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<()>
    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
    ///
    /// [`Error::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>> {
        const { assert!(G::NAMED, "a single group has no section") };
        if name.is_empty() {
            return Err(Error::InvalidInput(format!(
                "the section name of a [{} \"NAME\"] group is empty",
                G::NAME
            )));
        }
        if name.contains(['[', ']', '"', '\n', '\r']) {
            return Err(Error::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
    ///
    /// [`Error::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<()> {
        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<()> {
    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)
}