1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
use super::copy::Copy;
use super::vault::Vault;
use anyhow::{anyhow, Context, Result};

enum ParseableType {
    Copyable(Copy),
    Vaultable(Vault),
    None(serde_json::Value),
}

impl ParseableType {
    fn get_value(&self) -> Result<serde_json::Value> {
        match self {
            ParseableType::Copyable(v) => v.get_value(),
            ParseableType::Vaultable(v) => v.get_value(),
            ParseableType::None(v) => Ok(v.to_owned()),
        }
    }
}
impl TryFrom<serde_json::Map<std::string::String, serde_json::Value>> for ParseableType {
    type Error = anyhow::Error;
    fn try_from(
        value: serde_json::Map<std::string::String, serde_json::Value>,
    ) -> std::result::Result<Self, Self::Error> {
        match value {
            v if v.contains_key("@copy") => {
                return Ok(ParseableType::Copyable(v.get("@copy").unwrap().try_into()?));
            }
            v if v.contains_key("@vault") => {
                return Ok(ParseableType::Vaultable(
                    v.get("@vault").unwrap().try_into()?,
                ));
            }
            _ => {
                return Ok(ParseableType::None(serde_json::Value::Object(value)));
            }
        }
    }
}

impl TryFrom<serde_json::Value> for ParseableType {
    type Error = anyhow::Error;
    fn try_from(value: serde_json::Value) -> Result<Self> {
        match value {
            serde_json::Value::Object(v) => {
                return Ok(ParseableType::try_from(v)?);
            }
            _ => {
                return Ok(ParseableType::None(value));
            }
        }
    }
}

#[cfg(test)]
mod parse_tests {
    use crate::parse;

    fn test_transformation(input: &str, expect: &str) {
        let mut obj: serde_json::Value = serde_yaml::from_str(input).unwrap();
        let obj = parse::parse_value(obj).unwrap();

        let expect: serde_json::Value = serde_yaml::from_str(expect).unwrap();
        assert_eq!(obj, expect);
    }

    #[test]
    fn test_copy() {
        let input = r#"
            base:
              "@copy":
                value: a
        "#;
        let expect = r#"
            base: a
        "#;
        test_transformation(input, expect)
    }

    #[test]
    fn test_nested() {
        let input = r#"
            base:
              should-be-a:
                "@copy":
                  value: a
        "#;
        let expect = r#"
            base:
                should-be-a: a
        "#;

        test_transformation(input, expect)
    }

    #[test]
    fn test_array_parse() {
        let input = r#"
            base:
            - "@copy":
                value: a
            - "@copy":
                value: b
        "#;
        let expect = r#"
            base:
            - a
            - b
        "#;
        test_transformation(input, expect)
    }

    #[test]
    fn test_nested_array() {
        let input = r#"
            base:
             - first_array:
               - "@copy":
                    value: a
               - value: b
             - second_array:
               - "@copy":
                   value: c
        "#;
        let expect = r#"
            base:
            - first_array:
              - a
              - value: b
            - second_array:
                - c  
        "#;
        test_transformation(input, expect)
    }

    #[test]
    fn test_copy_errors() {
        let mut obj: serde_json::Value =
            serde_json::from_str(r#"{ "base": { "@copy": "bob" } }"#).unwrap();
        assert!(parse::parse_value(obj).is_err());
    }
}

pub fn parse_value(input: serde_json::Value) -> Result<serde_json::Value> {
    match input {
        serde_json::Value::Array(a) => {
            let mut result: Vec<serde_json::Value> = vec![];
            for i in a {
                result.push(parse_value(i)?);
            }
            return Ok(result.into());
        }
        serde_json::Value::Object(o) => {
            match ParseableType::try_from(o.to_owned())? {
                ParseableType::None(o) => {
                    let o = o.as_object().unwrap(); // we konw this is an object because of the line above
                    let mut ret = serde_json::Map::new();
                    for (k, v) in o.iter() {
                        ret.insert(k.to_string(), parse_value(v.to_owned())?);
                    }
                    return Ok(ret.into());
                }
                _ => return Ok(ParseableType::try_from(o.to_owned())?.get_value()?),
            }
        }
        _ => return Ok(input),
    }
}