Skip to main content

naru_core/core/
json_format.rs

1use crate::core::config_model::ConfigFile;
2use crate::core::format_trait::ConfigFormat;
3use anyhow::Result;
4
5pub struct JsonFormat;
6
7impl JsonFormat {
8    pub fn new() -> Self {
9        JsonFormat
10    }
11}
12
13impl Default for JsonFormat {
14    fn default() -> Self {
15        Self::new()
16    }
17}
18
19impl ConfigFormat for JsonFormat {
20    fn name(&self) -> &str {
21        "JSON"
22    }
23
24    fn extension(&self) -> &str {
25        "json"
26    }
27
28    fn serialize(&self, config: &ConfigFile) -> Result<String> {
29        serde_json::to_string_pretty(config)
30            .map_err(|e| anyhow::anyhow!("JSON serialization error: {}", e))
31    }
32
33    fn deserialize(&self, data: &str) -> Result<ConfigFile> {
34        serde_json::from_str(data).map_err(|e| anyhow::anyhow!("JSON deserialization error: {}", e))
35    }
36}
37
38pub fn serialize_json(config: &ConfigFile) -> Result<String> {
39    JsonFormat::new().serialize(config)
40}
41
42pub fn deserialize_json(data: &str) -> Result<ConfigFile> {
43    JsonFormat::new().deserialize(data)
44}
45
46pub fn serialize_json_pretty(config: &ConfigFile) -> Result<String> {
47    serde_json::to_string_pretty(config)
48        .map_err(|e| anyhow::anyhow!("JSON pretty print error: {}", e))
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use std::collections::HashMap;
55
56    #[test]
57    fn test_json_format_new() {
58        let format = JsonFormat::new();
59        assert_eq!(format.name(), "JSON");
60        assert_eq!(format.extension(), "json");
61    }
62
63    #[test]
64    fn test_serialize_json() {
65        let config = ConfigFile::new("TestProject");
66        let json = serialize_json(&config).unwrap();
67        assert!(json.contains("TestProject"));
68    }
69
70    #[test]
71    fn test_deserialize_json() {
72        let data = r#"{
73            "project_name": "TestProject",
74            "version": "1.0.0",
75            "environments": {}
76        }"#;
77
78        let config = deserialize_json(data).unwrap();
79        assert_eq!(config.project_name, "TestProject");
80    }
81
82    #[test]
83    fn test_roundtrip_json() {
84        let mut config = ConfigFile::new("RoundTripTest");
85        let env = config.add_environment("production");
86        env.set_value(
87            "HOST",
88            crate::core::config_model::ConfigValueEntry::new("localhost", "string", false),
89        );
90
91        let json = serialize_json(&config).unwrap();
92        let restored = deserialize_json(&json).unwrap();
93
94        assert_eq!(restored.project_name, config.project_name);
95        assert!(restored.environments.contains_key("production"));
96    }
97}