ostrya-core 0.19.0

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
//! The overrides of a repository handle, and the key values of a create.

use super::{Group, Key, Overridable, Settable, SingleKey, Value, ValueOf, lists};

/// The value of one key of a single group, as the text of [`Value::format`].
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    /// The name of the group.
    pub group: &'static str,
    /// The name of the key.
    pub key: &'static str,
    /// The raw text of the value, as a key file holds it.
    pub text: String,
}

/// Sets `text` as the value of the key `key` of `group` in `entries`.
///
/// A value of a key that `entries` holds replaces the old value at the same
/// position. A new key goes at the end.
#[doc(hidden)]
pub fn put(entries: &mut Vec<Entry>, group: &'static str, key: &'static str, text: String) {
    match entries
        .iter_mut()
        .find(|entry| entry.group == group && entry.key == key)
    {
        Some(entry) => entry.text = text,
        None => entries.push(Entry { group, key, text }),
    }
}

/// Returns the text of the key `key` of `group` in `entries`, or `None` if
/// `entries` holds no value of the key.
#[doc(hidden)]
pub fn find<'a>(entries: &'a [Entry], group: &str, key: &str) -> Option<&'a str> {
    entries
        .iter()
        .find(|entry| entry.group == group && entry.key == key)
        .map(|entry| entry.text.as_str())
}

/// Stores the value of the key `K` of a single group in `entries`, as
/// [`put`] does. `K` must be in the list [`Group::SETTABLE`] of its group.
#[doc(hidden)]
pub fn put_settable<K>(entries: &mut Vec<Entry>, value: ValueOf<K>)
where
    K: Settable + Key<<K as SingleKey>::Group>,
{
    const {
        assert!(
            lists(<<K as SingleKey>::Group as Group>::SETTABLE, K::NAME),
            "the key is not in the list `SETTABLE` of its group"
        )
    };
    put(entries, K::Group::NAME, K::NAME, value.format());
}

/// The overrides of a repository handle: the forced values and the fallback
/// values of the keys of the single groups.
///
/// Each value is the text of [`Value::format`], keyed by the group name and
/// the key name. A read parses the text with the value type of the key.
#[doc(hidden)]
#[derive(Debug, Clone, Default)]
pub struct Overrides {
    /// The values that apply whether the file sets the key or not.
    forced: Vec<Entry>,
    /// The values that apply when the file does not set the key.
    fallback: Vec<Entry>,
}

impl Overrides {
    /// Sets the forced value of the key `K`. A later value of the key
    /// replaces it.
    pub fn force<K>(&mut self, value: ValueOf<K>)
    where
        K: Overridable + Key<<K as SingleKey>::Group>,
    {
        check_overridable::<K>();
        put(&mut self.forced, K::Group::NAME, K::NAME, value.format());
    }

    /// Sets the fallback value of the key `K`. A later value of the key
    /// replaces it.
    pub fn fallback<K>(&mut self, value: ValueOf<K>)
    where
        K: Overridable + Key<<K as SingleKey>::Group>,
    {
        check_overridable::<K>();
        put(&mut self.fallback, K::Group::NAME, K::NAME, value.format());
    }

    /// Returns the text of the forced value of the key `key` of `group`.
    pub fn forced(&self, group: &str, key: &str) -> Option<&str> {
        find(&self.forced, group, key)
    }

    /// Returns the text of the fallback value of the key `key` of `group`.
    pub fn fallback_of(&self, group: &str, key: &str) -> Option<&str> {
        find(&self.fallback, group, key)
    }
}

/// Checks at compile time that the list [`Group::OVERRIDABLE`] of the group
/// of `K` holds the name of `K`.
fn check_overridable<K>()
where
    K: Overridable + Key<<K as SingleKey>::Group>,
{
    const {
        assert!(
            lists(<<K as SingleKey>::Group as Group>::OVERRIDABLE, K::NAME),
            "the key is not in the list `OVERRIDABLE` of its group"
        )
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::repo;

    #[test]
    fn a_repeated_key_replaces_its_value_in_place() {
        let mut entries = Vec::new();
        put(&mut entries, "core", "a", "1".into());
        put(&mut entries, "x", "a", "2".into());
        put(&mut entries, "core", "b", "3".into());
        put(&mut entries, "core", "a", "4".into());
        let keys: Vec<_> = entries
            .iter()
            .map(|e| (e.group, e.key, e.text.as_str()))
            .collect();
        assert_eq!(
            keys,
            [("core", "a", "4"), ("x", "a", "2"), ("core", "b", "3")]
        );
        assert_eq!(find(&entries, "x", "a"), Some("2"));
        assert_eq!(find(&entries, "x", "b"), None);
    }

    #[test]
    fn the_overrides_store_the_formatted_text() {
        let mut overrides = Overrides::default();
        overrides.force::<repo::Fsync>(false);
        overrides.fallback::<repo::DefaultRepoFinders>(vec!["a b".into(), "c".into()]);
        assert_eq!(overrides.forced("core", "fsync"), Some("false"));
        assert_eq!(overrides.fallback_of("core", "fsync"), None);
        assert_eq!(
            overrides.fallback_of("core", "default-repo-finders"),
            Some("a b;c;")
        );
    }
}