1use std::collections::HashMap;
8use std::fs;
9use std::path::{Path, PathBuf};
10use serde_json;
11use toml;
12
13use super::ConfigProvider;
14use super::ConfigError;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum FileFormat {
19 Json,
21 Toml,
23 Yaml,
25}
26
27impl FileFormat {
28 pub fn from_extension(path: &Path) -> Option<Self> {
30 path.extension().and_then(|ext| {
31 let ext_str = ext.to_string_lossy().to_lowercase();
32 match ext_str.as_str() {
33 "json" => Some(FileFormat::Json),
34 "toml" => Some(FileFormat::Toml),
35 "yaml" | "yml" => Some(FileFormat::Yaml),
36 _ => None,
37 }
38 })
39 }
40}
41
42#[derive(Debug)]
44pub struct FileConfigProvider {
45 #[allow(dead_code)]
46 path: PathBuf,
47 #[allow(dead_code)]
48 format: FileFormat,
49 data: HashMap<String, serde_json::Value>,
50}
51
52impl FileConfigProvider {
53 pub fn new(path: &str) -> Result<Self, ConfigError> {
55 let path_buf = PathBuf::from(path);
56 let format = FileFormat::from_extension(&path_buf)
57 .ok_or_else(|| ConfigError::provider_error("file", "unsupported file format"))?;
58
59 let data = Self::read_file(&path_buf, format)?;
60
61 Ok(Self {
62 path: path_buf,
63 format,
64 data,
65 })
66 }
67
68 fn read_file(path: &Path, format: FileFormat) -> Result<HashMap<String, serde_json::Value>, ConfigError> {
70 let content = fs::read_to_string(path)
71 .map_err(|e| ConfigError::provider_error("file", format!("failed to read file: {}", e)))?;
72
73 match format {
74 FileFormat::Json => {
75 serde_json::from_str(&content)
76 .map_err(|e| ConfigError::provider_error("file", format!("invalid JSON: {}", e)))
77 },
78 FileFormat::Toml => {
79 let toml_value: toml::Value = toml::from_str(&content)
80 .map_err(|e| ConfigError::provider_error("file", format!("invalid TOML: {}", e)))?;
81
82 let json_value = serde_json::to_value(toml_value)
84 .map_err(|e| ConfigError::provider_error("file", format!("failed to convert TOML: {}", e)))?;
85
86 match json_value {
87 serde_json::Value::Object(map) => {
88 Ok(map.into_iter().collect())
90 },
91 _ => Err(ConfigError::provider_error("file", "root configuration must be an object")),
92 }
93 },
94 FileFormat::Yaml => {
95 let yaml_value: serde_yaml::Value = serde_yaml::from_str(&content)
96 .map_err(|e| ConfigError::provider_error("file", format!("invalid YAML: {}", e)))?;
97
98 let json_value = serde_json::to_value(yaml_value)
99 .map_err(|e| ConfigError::provider_error("file", format!("failed to convert YAML: {}", e)))?;
100
101 match json_value {
102 serde_json::Value::Object(map) => {
103 Ok(map.into_iter().collect())
104 },
105 _ => Err(ConfigError::provider_error("file", "root configuration must be an object")),
106 }
107 },
108 }
109 }
110
111 fn get_nested_value(&self, key_path: &str) -> Option<&serde_json::Value> {
113 let parts: Vec<&str> = key_path.split('.').collect();
114
115 let mut current = self.data.get(parts[0])?;
116
117 for part in parts.iter().skip(1) {
118 current = current.get(part)?;
119 }
120
121 Some(current)
122 }
123}
124
125impl ConfigProvider for FileConfigProvider {
126 fn get_raw(&self, key: &str) -> Result<Option<serde_json::Value>, ConfigError> {
127 match self.get_nested_value(key) {
128 Some(value) => Ok(Some(value.clone())),
129 None => Ok(None),
130 }
131 }
132
133 fn has(&self, key: &str) -> bool {
134 self.get_nested_value(key).is_some()
135 }
136
137 fn provider_name(&self) -> &str {
138 "file"
139 }
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145 use std::fs::File;
146 use std::io::Write;
147 use tempfile::tempdir;
148 use crate::config::ConfigProviderExt;
149
150 #[test]
151 fn test_file_format_detection() {
152 assert_eq!(FileFormat::from_extension(Path::new("config.json")), Some(FileFormat::Json));
153 assert_eq!(FileFormat::from_extension(Path::new("config.toml")), Some(FileFormat::Toml));
154 assert_eq!(FileFormat::from_extension(Path::new("config.yaml")), Some(FileFormat::Yaml));
155 assert_eq!(FileFormat::from_extension(Path::new("config.yml")), Some(FileFormat::Yaml));
156 assert_eq!(FileFormat::from_extension(Path::new("config.txt")), None);
157 }
158
159 #[test]
160 fn test_json_config() {
161 let dir = tempdir().unwrap();
162 let file_path = dir.path().join("config.json");
163
164 let content = r#"{
165 "server": {
166 "host": "127.0.0.1",
167 "port": 8080
168 },
169 "timeout": 30
170 }"#;
171
172 let mut file = File::create(&file_path).unwrap();
173 file.write_all(content.as_bytes()).unwrap();
174
175 let provider = FileConfigProvider::new(file_path.to_str().unwrap()).unwrap();
176
177 assert_eq!(provider.has("server.host"), true);
178 assert_eq!(provider.has("server.nonexistent"), false);
179
180 let host: String = provider.get("server.host").unwrap().unwrap();
181 assert_eq!(host, "127.0.0.1");
182
183 let port: u16 = provider.get("server.port").unwrap().unwrap();
184 assert_eq!(port, 8080);
185
186 let timeout: u32 = provider.get("timeout").unwrap().unwrap();
187 assert_eq!(timeout, 30);
188 }
189
190 #[test]
191 fn test_toml_config() {
192 let dir = tempdir().unwrap();
193 let file_path = dir.path().join("config.toml");
194
195 let content = r#"
196 [server]
197 host = "127.0.0.1"
198 port = 8080
199
200 timeout = 30
201 "#;
202
203 let mut file = File::create(&file_path).unwrap();
204 file.write_all(content.as_bytes()).unwrap();
205
206 let provider = FileConfigProvider::new(file_path.to_str().unwrap()).unwrap();
207
208 assert_eq!(provider.has("server.host"), true);
209 let host: String = provider.get("server.host").unwrap().unwrap();
210 assert_eq!(host, "127.0.0.1");
211
212 let port: u16 = provider.get("server.port").unwrap().unwrap();
213 assert_eq!(port, 8080);
214 }
215}