Skip to main content

journey/
config_manager.rs

1use crate::config::Config;
2use crate::errors::JourneyError;
3use dirs::config_dir;
4use std::fs;
5use std::path::PathBuf;
6use std::env;
7
8pub struct ConfigManager {
9    pub config_path: PathBuf,
10}
11
12impl ConfigManager {
13    pub fn new() -> Result<Self, JourneyError> {
14        // Check if a custom config path is specified via environment variable
15        let config_path = if let Ok(custom_path) = env::var("JOURNEY_CONFIG") {
16            PathBuf::from(custom_path)
17        } else {
18            let config_dir = config_dir()
19                .ok_or_else(|| JourneyError::Config("Could not find config directory".to_string()))?;
20            
21            let journey_config_dir = config_dir.join("journey");
22            fs::create_dir_all(&journey_config_dir)?;
23            
24            journey_config_dir.join("journey.yaml")
25        };
26        
27        Ok(Self { config_path })
28    }
29
30    pub fn load_config(&self) -> Result<Config, JourneyError> {
31        if !self.config_path.exists() {
32            return Ok(Config::new());
33        }
34
35        let content = fs::read_to_string(&self.config_path)?;
36        let config: Config = serde_yaml_ng::from_str(&content)?;
37        Ok(config)
38    }
39
40    pub fn save_config(&self, config: &Config) -> Result<(), JourneyError> {
41        let mut content = serde_yaml_ng::to_string(config)?;
42        // Ensure default_vault is present if set
43        if let Some(default_name) = &config.default_vault {
44            if !content.contains("default_vault:") {
45                content.push_str(&format!("default_vault: {}\n", default_name));
46            }
47        }
48        fs::write(&self.config_path, content)?;
49        Ok(())
50    }
51
52    pub fn config_exists(&self) -> bool {
53        self.config_path.is_file()
54    }
55}
56