Skip to main content

verctl_core/config/
artifact_table.rs

1//! Packslip artifact table deserialized from YAML into TOML.
2
3use std::fmt;
4
5use serde::{Deserialize, de};
6
7/// The table a target's `packslip` adds to its `[[artifact]]` entry, as the
8/// TOML the release.toml carries. It is empty when the target sets none.
9///
10/// The load converts the YAML once, so the writer never converts it again
11/// and no value TOML cannot express reaches it.
12#[derive(Debug, Clone, Default)]
13pub struct ArtifactTable(toml_edit::Table);
14
15impl ArtifactTable {
16    /// Each key with its value, in key order.
17    pub fn entries(&self) -> impl Iterator<Item = (&str, &toml_edit::Item)> {
18        self.0.iter()
19    }
20
21    /// Whether the table sets `key`.
22    #[must_use]
23    pub fn contains_key(&self, key: &str) -> bool {
24        self.0.contains_key(key)
25    }
26
27    /// The value of `key`, when the table sets it.
28    #[must_use]
29    pub fn get(&self, key: &str) -> Option<&toml_edit::Item> {
30        self.0.get(key)
31    }
32}
33
34/// The TOML text of the table, one line per key.
35impl fmt::Display for ArtifactTable {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        fmt::Display::fmt(&self.0, f)
38    }
39}
40
41/// Two tables are equal when they render the same text.
42impl PartialEq for ArtifactTable {
43    fn eq(&self, other: &Self) -> bool {
44        self.to_string() == other.to_string()
45    }
46}
47
48impl Eq for ArtifactTable {}
49
50impl<'de> Deserialize<'de> for ArtifactTable {
51    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
52        let table = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
53        toml_table(&table).map(Self).map_err(de::Error::custom)
54    }
55}
56
57/// `table` as TOML, key for key, so a target's `packslip` reaches the
58/// release.toml the way the file wrote it.
59fn toml_table(
60    table: &serde_json::Map<String, serde_json::Value>,
61) -> Result<toml_edit::Table, String> {
62    let mut converted = toml_edit::Table::new();
63    for (key, value) in table {
64        let value = to_toml_scalar(value).map_err(|reason| format!("{key}: {reason}"))?;
65        converted.insert(key, toml_edit::Item::Value(value));
66    }
67    Ok(converted)
68}
69
70fn to_toml_scalar(value: &serde_json::Value) -> Result<toml_edit::Value, String> {
71    match value {
72        serde_json::Value::Null => Err("null has no TOML form: delete the key".to_owned()),
73        serde_json::Value::Bool(flag) => Ok((*flag).into()),
74        serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
75            (Some(integer), _) => Ok(integer.into()),
76            (None, Some(float)) if number.is_f64() => Ok(float.into()),
77            _ => Err(format!("{number} is beyond the integers TOML supports")),
78        },
79        serde_json::Value::String(text) => Ok(text.as_str().into()),
80        serde_json::Value::Array(items) => {
81            let mut array = toml_edit::Array::new();
82            for item in items {
83                array.push(to_toml_scalar(item)?);
84            }
85            Ok(array.into())
86        }
87        serde_json::Value::Object(entries) => {
88            let mut inline = toml_edit::InlineTable::new();
89            for (key, entry) in entries {
90                let entry = to_toml_scalar(entry).map_err(|reason| format!("{key}: {reason}"))?;
91                inline.insert(key.as_str(), entry);
92            }
93            Ok(inline.into())
94        }
95    }
96}