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 mut 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    // Drop deprecated keys that were removed from the schema.
96    if let Some(obj) = parsed_value.as_object_mut() {
97        obj.remove("opencode_commit");
98    }
99
100    // Deserialize into Config struct (deny_unknown_fields will reject unknown keys)
101    let config: Config = serde_json::from_value(parsed_value).with_context(|| {
102        format!(
103            "Invalid configuration in {}. Check for unknown fields or invalid values.",
104            config_path.display()
105        )
106    })?;
107
108    Ok(config)
109}
110
111/// Save configuration to the config file
112///
113/// Creates a backup of the existing config (config.json.bak) before overwriting.
114/// Ensures the config directory exists.
115pub fn save_config(config: &Config) -> Result<()> {
116    ensure_config_dir()?;
117
118    let config_path =
119        get_config_path().ok_or_else(|| anyhow::anyhow!("Could not determine config file path"))?;
120
121    // Create backup if file exists
122    if config_path.exists() {
123        let backup_path = config_path.with_extension("json.bak");
124        fs::copy(&config_path, &backup_path)
125            .with_context(|| format!("Failed to create backup at: {}", backup_path.display()))?;
126        tracing::debug!("Created config backup: {}", backup_path.display());
127    }
128
129    // Serialize with pretty formatting
130    let json = serde_json::to_string_pretty(config).context("Failed to serialize configuration")?;
131
132    // Write to file
133    let mut file = File::create(&config_path)
134        .with_context(|| format!("Failed to create config file: {}", config_path.display()))?;
135
136    file.write_all(json.as_bytes())
137        .with_context(|| format!("Failed to write config file: {}", config_path.display()))?;
138
139    tracing::debug!("Saved config to: {}", config_path.display());
140
141    Ok(())
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147
148    #[test]
149    fn test_path_resolution_returns_values() {
150        // Verify path functions return Some on supported platforms
151        assert!(get_config_dir().is_some());
152        assert!(get_data_dir().is_some());
153        assert!(get_config_path().is_some());
154        assert!(get_pid_path().is_some());
155    }
156
157    #[test]
158    fn test_paths_end_with_expected_names() {
159        let config_dir = get_config_dir().unwrap();
160        assert!(config_dir.ends_with("opencode-cloud"));
161
162        let data_dir = get_data_dir().unwrap();
163        assert!(data_dir.ends_with("opencode-cloud"));
164
165        let config_path = get_config_path().unwrap();
166        assert!(config_path.ends_with("config.json"));
167
168        let pid_path = get_pid_path().unwrap();
169        assert!(pid_path.ends_with("opencode-cloud.pid"));
170    }
171
172    // Note: Integration tests for load_config/save_config that modify the real
173    // filesystem are run via CLI commands rather than unit tests to avoid
174    // test isolation issues with environment variable manipulation in Rust 2024.
175}