Skip to main content

opencode_cloud_core/config/
mod.rs

1//! Configuration management for opencode-cloud
2//!
3//! Handles loading, saving, and validating the JSONC configuration file.
4//! Creates default config if missing, validates against schema.
5
6pub mod paths;
7pub mod schema;
8pub mod validation;
9
10use std::fs::{self, File};
11use std::io::{Read, Write};
12use std::path::PathBuf;
13
14use anyhow::{Context, Result};
15use jsonc_parser::parse_to_serde_value;
16
17pub use paths::{get_config_dir, get_config_path, get_data_dir, get_hosts_path, get_pid_path};
18pub use schema::{Config, validate_bind_address};
19pub use validation::{
20    ValidationError, ValidationWarning, display_validation_error, display_validation_warning,
21    validate_config,
22};
23
24/// Ensure the config directory exists
25///
26/// Creates `~/.config/opencode-cloud/` if it doesn't exist.
27/// Returns the path to the config directory.
28pub fn ensure_config_dir() -> Result<PathBuf> {
29    let config_dir =
30        get_config_dir().ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?;
31
32    if !config_dir.exists() {
33        fs::create_dir_all(&config_dir).with_context(|| {
34            format!(
35                "Failed to create config directory: {}",
36                config_dir.display()
37            )
38        })?;
39        tracing::info!("Created config directory: {}", config_dir.display());
40    }
41
42    Ok(config_dir)
43}
44
45/// Ensure the data directory exists
46///
47/// Creates `~/.local/share/opencode-cloud/` if it doesn't exist.
48/// Returns the path to the data directory.
49pub fn ensure_data_dir() -> Result<PathBuf> {
50    let data_dir =
51        get_data_dir().ok_or_else(|| anyhow::anyhow!("Could not determine data directory"))?;
52
53    if !data_dir.exists() {
54        fs::create_dir_all(&data_dir)
55            .with_context(|| format!("Failed to create data directory: {}", data_dir.display()))?;
56        tracing::info!("Created data directory: {}", data_dir.display());
57    }
58
59    Ok(data_dir)
60}
61
62/// Load configuration from the config file
63///
64/// If the config file doesn't exist, creates a new one with default values.
65/// Supports JSONC (JSON with comments).
66/// Rejects unknown fields for strict validation.
67pub fn load_config() -> Result<Config> {
68    let config_path =
69        get_config_path().ok_or_else(|| anyhow::anyhow!("Could not determine config file path"))?;
70
71    if !config_path.exists() {
72        // Create default config
73        tracing::info!(
74            "Config file not found, creating default at: {}",
75            config_path.display()
76        );
77        let config = Config::default();
78        save_config(&config)?;
79        return Ok(config);
80    }
81
82    // Read the file
83    let mut file = File::open(&config_path)
84        .with_context(|| format!("Failed to open config file: {}", config_path.display()))?;
85
86    let mut contents = String::new();
87    file.read_to_string(&mut contents)
88        .with_context(|| format!("Failed to read config file: {}", config_path.display()))?;
89
90    // Parse JSONC (JSON with comments)
91    let parsed_value = parse_to_serde_value(&contents, &Default::default())
92        .map_err(|e| anyhow::anyhow!("Invalid JSONC in config file: {e}"))?
93        .ok_or_else(|| anyhow::anyhow!("Config file is empty"))?;
94
95    // Deserialize into Config struct (deny_unknown_fields will reject unknown keys)
96    let config: Config = serde_json::from_value(parsed_value).with_context(|| {
97        format!(
98            "Invalid configuration in {}. Check for unknown fields or invalid values.",
99            config_path.display()
100        )
101    })?;
102
103    Ok(config)
104}
105
106/// Save configuration to the config file
107///
108/// Creates a backup of the existing config (config.json.bak) before overwriting.
109/// Ensures the config directory exists.
110pub fn save_config(config: &Config) -> Result<()> {
111    ensure_config_dir()?;
112
113    let config_path =
114        get_config_path().ok_or_else(|| anyhow::anyhow!("Could not determine config file path"))?;
115
116    // Create backup if file exists
117    if config_path.exists() {
118        let backup_path = config_path.with_extension("json.bak");
119        fs::copy(&config_path, &backup_path)
120            .with_context(|| format!("Failed to create backup at: {}", backup_path.display()))?;
121        tracing::debug!("Created config backup: {}", backup_path.display());
122    }
123
124    // Serialize with pretty formatting
125    let json = serde_json::to_string_pretty(config).context("Failed to serialize configuration")?;
126
127    // Write to file
128    let mut file = File::create(&config_path)
129        .with_context(|| format!("Failed to create config file: {}", config_path.display()))?;
130
131    file.write_all(json.as_bytes())
132        .with_context(|| format!("Failed to write config file: {}", config_path.display()))?;
133
134    tracing::debug!("Saved config to: {}", config_path.display());
135
136    Ok(())
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn test_path_resolution_returns_values() {
145        // Verify path functions return Some on supported platforms
146        assert!(get_config_dir().is_some());
147        assert!(get_data_dir().is_some());
148        assert!(get_config_path().is_some());
149        assert!(get_pid_path().is_some());
150    }
151
152    #[test]
153    fn test_paths_end_with_expected_names() {
154        let config_dir = get_config_dir().unwrap();
155        assert!(config_dir.ends_with("opencode-cloud"));
156
157        let data_dir = get_data_dir().unwrap();
158        assert!(data_dir.ends_with("opencode-cloud"));
159
160        let config_path = get_config_path().unwrap();
161        assert!(config_path.ends_with("config.json"));
162
163        let pid_path = get_pid_path().unwrap();
164        assert!(pid_path.ends_with("opencode-cloud.pid"));
165    }
166
167    // Note: Integration tests for load_config/save_config that modify the real
168    // filesystem are run via CLI commands rather than unit tests to avoid
169    // test isolation issues with environment variable manipulation in Rust 2024.
170}