verctl-core 0.9.2

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Packslip artifact table deserialized from YAML into TOML.

use std::fmt;

use serde::{Deserialize, de};

/// The table a target's `packslip` adds to its `[[artifact]]` entry, as the
/// TOML the release.toml carries. It is empty when the target sets none.
///
/// The load converts the YAML once, so the writer never converts it again
/// and no value TOML cannot express reaches it.
#[derive(Debug, Clone, Default)]
pub struct ArtifactTable(toml_edit::Table);

impl ArtifactTable {
    /// Each key with its value, in key order.
    pub fn entries(&self) -> impl Iterator<Item = (&str, &toml_edit::Item)> {
        self.0.iter()
    }

    /// Whether the table sets `key`.
    #[must_use]
    pub fn contains_key(&self, key: &str) -> bool {
        self.0.contains_key(key)
    }

    /// The value of `key`, when the table sets it.
    #[must_use]
    pub fn get(&self, key: &str) -> Option<&toml_edit::Item> {
        self.0.get(key)
    }
}

/// The TOML text of the table, one line per key.
impl fmt::Display for ArtifactTable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// Two tables are equal when they render the same text.
impl PartialEq for ArtifactTable {
    fn eq(&self, other: &Self) -> bool {
        self.to_string() == other.to_string()
    }
}

impl Eq for ArtifactTable {}

impl<'de> Deserialize<'de> for ArtifactTable {
    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let table = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
        toml_table(&table).map(Self).map_err(de::Error::custom)
    }
}

/// `table` as TOML, key for key, so a target's `packslip` reaches the
/// release.toml the way the file wrote it.
fn toml_table(
    table: &serde_json::Map<String, serde_json::Value>,
) -> Result<toml_edit::Table, String> {
    let mut converted = toml_edit::Table::new();
    for (key, value) in table {
        let value = toml_value(value).map_err(|reason| format!("{key}: {reason}"))?;
        converted.insert(key, toml_edit::Item::Value(value));
    }
    Ok(converted)
}

fn toml_value(value: &serde_json::Value) -> Result<toml_edit::Value, String> {
    match value {
        serde_json::Value::Null => Err("null has no TOML form: delete the key".to_owned()),
        serde_json::Value::Bool(flag) => Ok((*flag).into()),
        serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
            (Some(integer), _) => Ok(integer.into()),
            (None, Some(float)) if number.is_f64() => Ok(float.into()),
            _ => Err(format!("{number} is beyond the integers TOML supports")),
        },
        serde_json::Value::String(text) => Ok(text.as_str().into()),
        serde_json::Value::Array(items) => {
            let mut array = toml_edit::Array::new();
            for item in items {
                array.push(toml_value(item)?);
            }
            Ok(array.into())
        }
        serde_json::Value::Object(entries) => {
            let mut inline = toml_edit::InlineTable::new();
            for (key, entry) in entries {
                let entry = toml_value(entry).map_err(|reason| format!("{key}: {reason}"))?;
                inline.insert(key.as_str(), entry);
            }
            Ok(inline.into())
        }
    }
}