vika_cli/config/
loader.rs1use crate::config::model::Config;
2use crate::error::{ConfigError, Result, VikaError};
3use std::path::PathBuf;
4
5const CONFIG_FILE: &str = ".vika.json";
6
7pub fn load_config() -> Result<Config> {
8 let config_path = PathBuf::from(CONFIG_FILE);
9
10 if !config_path.exists() {
11 return Ok(Config::default());
12 }
13
14 let content = std::fs::read_to_string(&config_path)
15 .map_err(|e| VikaError::from(ConfigError::ReadError(e)))?;
16
17 let config: Config =
18 serde_json::from_str(&content).map_err(|e| VikaError::from(ConfigError::ParseError(e)))?;
19
20 Ok(config)
21}
22
23pub fn save_config(config: &Config) -> Result<()> {
24 let config_path = PathBuf::from(CONFIG_FILE);
25
26 let mut config_to_save = config.clone();
28 if config_to_save.schema.is_empty() {
29 config_to_save.schema = crate::config::model::default_schema();
30 }
31
32 let content = serde_json::to_string_pretty(&config_to_save)
33 .map_err(|e| VikaError::from(ConfigError::ParseError(e)))?;
34
35 std::fs::write(&config_path, content)
36 .map_err(|e| VikaError::from(ConfigError::ReadError(e)))?;
37
38 Ok(())
39}
40
41#[cfg(test)]
42mod tests {
43 use super::*;
44 use std::env;
45
46 #[test]
47 fn test_save_and_load_config() {
48 let temp_dir = tempfile::tempdir().unwrap();
49 let original_dir = env::current_dir().ok();
50
51 let _ = env::set_current_dir(&temp_dir);
52
53 let config = Config::default();
54
55 if save_config(&config).is_ok() {
57 if let Ok(loaded) = load_config() {
59 assert_eq!(loaded.root_dir, config.root_dir);
60 assert_eq!(loaded.schemas.output, config.schemas.output);
61 }
62 }
63
64 if let Some(orig) = original_dir {
65 let _ = env::set_current_dir(orig);
66 }
67 }
68
69 #[test]
70 fn test_load_config_not_exists() {
71 let temp_dir = tempfile::tempdir().unwrap();
72 let original_dir = env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
73
74 env::set_current_dir(&temp_dir).unwrap();
75
76 let config = load_config().unwrap();
77 assert_eq!(config.root_dir, "src");
79
80 env::set_current_dir(original_dir).unwrap();
81 }
82
83 #[test]
84 fn test_save_config_with_empty_schema() {
85 let temp_dir = tempfile::tempdir().unwrap();
86 let original_dir = env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."));
87
88 env::set_current_dir(&temp_dir).unwrap();
89
90 let mut config = Config::default();
91 config.schema = String::new();
92 save_config(&config).unwrap();
93
94 let loaded = load_config().unwrap();
95 assert!(!loaded.schema.is_empty());
97
98 env::set_current_dir(original_dir).unwrap();
99 }
100}