ostrya-core 0.18.0

ostree object model, checksums, on-disk format primitives, and typed config
Documentation
//! The read helpers of the typed config API: the headers of a named group,
//! the check of a closed group, and the reads of one key with its overrides.

use super::{ConfigError, Group, Key, Lookup, Overrides, Value, lists, value_error};
use crate::KeyFile;

/// Returns the header of the section `name` of the named group `G`.
#[doc(hidden)]
pub fn section_header<G: Group>(name: &str) -> String {
    format!("{} \"{name}\"", G::NAME)
}

/// Returns the section name in `header`, a header of the named group `G`, or
/// `None` for the header of another group and for a section name that
/// [`is_section_name`] refuses.
#[doc(hidden)]
pub fn section_name<G: Group>(header: &str) -> Option<&str> {
    let name = header
        .strip_prefix(G::NAME)?
        .strip_prefix(" \"")?
        .strip_suffix('"')?;
    is_section_name(name).then_some(name)
}

/// Returns `true` if `name` is the name of a section: it is not empty and
/// holds no `"`.
#[doc(hidden)]
pub fn is_section_name(name: &str) -> bool {
    !name.is_empty() && !name.contains('"')
}

/// Refuses a key of the group `header` of `keyfile` that the closed group `G`
/// does not list.
///
/// The call checks nothing if [`Group::CLOSED`] of `G` is `false`. It names
/// the first such key in the order of the file.
///
/// # Errors
///
/// [`ConfigError::InvalidFormat`] with the text `[HEADER] holds the unknown
/// key 'KEY'`.
#[doc(hidden)]
pub fn refuse_unknown_keys<G: Group>(keyfile: &KeyFile, header: &str) -> Result<(), ConfigError> {
    if !G::CLOSED {
        return Ok(());
    }
    match keyfile.keys(header).find(|key| !G::KEYS.contains(key)) {
        Some(key) => Err(ConfigError::InvalidFormat(format!(
            "[{header}] holds the unknown key '{key}'"
        ))),
        None => Ok(()),
    }
}

/// Returns the value of the key `K` in the group `header` of `keyfile`, or
/// `None` if the key is absent.
#[doc(hidden)]
pub fn read_file<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
) -> Result<Option<K::Value>, ConfigError> {
    const {
        assert!(
            lists(G::KEYS, K::NAME),
            "the key is not in the key list of its group"
        )
    };
    let Some(raw) = keyfile.get_value(header, K::NAME) else {
        return Ok(None);
    };
    K::Value::parse(raw)
        .map(Some)
        .map_err(|err| value_error(header, K::NAME, raw, err))
}

/// Returns the value in effect of the key `K` in the group `header` of
/// `keyfile` and its source: the forced value of `overrides`, the value of
/// the file, the fallback value of `overrides`, or the default of the key.
///
/// A forced value applies with no read of the file.
#[doc(hidden)]
pub fn lookup<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<Option<Lookup<K::Value>>, ConfigError> {
    if let Some(raw) = overrides.and_then(|o| o.forced(header, K::NAME)) {
        return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Forced(v)));
    }
    if let Some(value) = read_file::<G, K>(keyfile, header)? {
        return Ok(Some(Lookup::File(value)));
    }
    if let Some(raw) = overrides.and_then(|o| o.fallback_of(header, K::NAME)) {
        return parse_text::<G, K>(header, raw).map(|v| Some(Lookup::Fallback(v)));
    }
    Ok(K::default_value().map(Lookup::Default))
}

/// Returns the value in effect of the key `K` in the group `header` of
/// `keyfile`, as [`lookup`] gives it, as the text of [`Value::format`], or
/// `None` if no source gives a value.
#[doc(hidden)]
pub fn lookup_text<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<Option<String>, ConfigError> {
    Ok(lookup::<G, K>(keyfile, header, overrides)?.map(|found| found.into_value().format()))
}

/// Returns the output of a read of the key `K` in the group `header` of
/// `keyfile`, with the overrides `overrides`: the value that [`lookup`]
/// gives, made into [`Key::Output`].
///
/// # Errors
///
/// - The errors of [`lookup`].
/// - [`ConfigError::InvalidFormat`] with the text `[HEADER] has no KEY` if
///   the key is required and no source gives a value.
#[doc(hidden)]
pub fn read_in_effect<G: Group, K: Key<G>>(
    keyfile: &KeyFile,
    header: &str,
    overrides: Option<&Overrides>,
) -> Result<K::Output, ConfigError> {
    let value = lookup::<G, K>(keyfile, header, overrides)?.map(Lookup::into_value);
    K::output(value)
        .ok_or_else(|| ConfigError::InvalidFormat(format!("[{header}] has no {}", K::NAME)))
}

/// Parses `raw`, the text of an override of the key `K` in the group
/// `header`, with the value type of `K`.
fn parse_text<G: Group, K: Key<G>>(header: &str, raw: &str) -> Result<K::Value, ConfigError> {
    K::Value::parse(raw).map_err(|err| value_error(header, K::NAME, raw, err))
}