mistletoe_api/v1alpha1/
mistinput.rs

1use serde::{Serialize, Deserialize, Serializer, Deserializer, de::DeserializeOwned};
2
3/// This is the input that is passed from the engine to the package for processing.
4/// There is only one field, and that is the freeform `data` field that can take
5/// any sort of map data the end-user wishes to provide to the package.
6#[derive(Clone, PartialEq, Debug)]
7pub struct MistInput {
8    /// Freeform data field.
9    pub data: serde_yaml::Mapping,
10}
11
12impl MistInput {
13    /// Tries to cast the input into any [Deserialize] types, useful for passing
14    /// the input into just about any type the package writer wishes to receive.
15    pub fn try_into_data<'a, T>(&self) -> Result<T, serde_yaml::Error>
16    where
17        T: DeserializeOwned
18    {
19        let serialized = serde_yaml::to_string(&self.data)?;
20        let value = serde_yaml::from_str(&serialized)?;
21        serde_yaml::from_value(value)
22    }
23}
24
25#[derive(Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27struct MistInputLayout {
28    api_version: String,
29    kind: String,
30    data: serde_yaml::Mapping,
31}
32
33impl From<MistInput> for MistInputLayout {
34    fn from(mhi: MistInput) -> MistInputLayout {
35        MistInputLayout {
36            api_version: "mistletoe.dev/v1alpha1".to_string(),
37            kind: "MistInput".to_string(),
38            data: mhi.data,
39        }
40    }
41}
42
43impl Into<MistInput> for MistInputLayout {
44    fn into(self) -> MistInput {
45        MistInput {
46            data: self.data,
47        }
48    }
49}
50
51impl Serialize for MistInput {
52    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
53    where
54        S: Serializer
55    {
56        MistInputLayout::from(self.clone()).serialize(serializer)
57    }
58}
59
60impl<'de> Deserialize<'de> for MistInput {
61    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62    where
63        D: Deserializer<'de>
64    {
65        let mri = MistInputLayout::deserialize(deserializer)?;
66        Ok(mri.into())
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use indoc::indoc;
74
75    #[test]
76    fn test_mistinput() {
77        let expected_yaml = indoc! {"
78            apiVersion: mistletoe.dev/v1alpha1
79            kind: MistInput
80            data:
81              name: my-nginx
82              namespace: my-namespace"};
83
84        let mut data = serde_yaml::Mapping::new();
85        data.insert("name".into(), "my-nginx".into());
86        data.insert("namespace".into(), "my-namespace".into());
87
88        let mistinput = MistInput { data };
89
90        let yaml = serde_yaml::to_string(&mistinput).unwrap();
91        assert_eq!(expected_yaml, yaml);
92
93        let mistinput_parsed = serde_yaml::from_str(&yaml).unwrap();
94        assert_eq!(mistinput, mistinput_parsed);
95    }
96}