syncable_cli/config/
mod.rs

1pub mod types;
2
3use crate::error::Result;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7const CONFIG_FILE_NAME: &str = ".syncable.toml";
8
9/// Get the global config file path (~/.syncable.toml)
10pub fn global_config_path() -> Option<PathBuf> {
11    dirs::home_dir().map(|h| h.join(CONFIG_FILE_NAME))
12}
13
14/// Get the local config file path (project/.syncable.toml)
15pub fn local_config_path(project_path: &Path) -> PathBuf {
16    project_path.join(CONFIG_FILE_NAME)
17}
18
19/// Load configuration from file or use defaults
20/// Checks local config first, then global config
21pub fn load_config(project_path: Option<&Path>) -> Result<types::Config> {
22    // Try local config first
23    if let Some(path) = project_path {
24        let local = local_config_path(path);
25        if local.exists()
26            && let Ok(content) = fs::read_to_string(&local)
27            && let Ok(config) = toml::from_str(&content)
28        {
29            return Ok(config);
30        }
31    }
32
33    // Try global config
34    if let Some(global) = global_config_path()
35        && global.exists()
36        && let Ok(content) = fs::read_to_string(&global)
37        && let Ok(config) = toml::from_str(&content)
38    {
39        return Ok(config);
40    }
41
42    Ok(types::Config::default())
43}
44
45/// Save configuration to global config file
46pub fn save_global_config(config: &types::Config) -> Result<()> {
47    if let Some(path) = global_config_path() {
48        let content = toml::to_string_pretty(config)
49            .map_err(|e| crate::error::ConfigError::ParsingFailed(e.to_string()))?;
50        fs::write(&path, content)?;
51    }
52    Ok(())
53}
54
55/// Load only the agent config section (for API keys)
56pub fn load_agent_config() -> types::AgentConfig {
57    if let Some(global) = global_config_path()
58        && global.exists()
59        && let Ok(content) = fs::read_to_string(&global)
60        && let Ok(config) = toml::from_str::<types::Config>(&content)
61    {
62        return config.agent;
63    }
64    types::AgentConfig::default()
65}
66
67/// Save agent config, preserving other config sections
68pub fn save_agent_config(agent: &types::AgentConfig) -> Result<()> {
69    let mut config = load_config(None)?;
70    config.agent = agent.clone();
71    save_global_config(&config)
72}