Skip to main content

bonds_core/
config.rs

1use crate::error::BondError;
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::PathBuf;
5
6/// User-level configuration for Bonds.
7/// Stored at ~/.bonds/config.toml
8#[derive(Debug, Serialize, Deserialize, Default)]
9pub struct BondsConfig {
10    /// Where bonds are created when no target is specified.
11    /// Defaults to None (falls back to current working directory).
12    pub default_target: Option<PathBuf>,
13}
14
15impl BondsConfig {
16    /// Returns the canonical path to the config file: ~/.bonds/config.toml
17    pub fn config_path() -> PathBuf {
18        std::env::var("HOME")
19            .map(PathBuf::from)
20            .unwrap_or_else(|_| PathBuf::from("."))
21            .join(".bonds")
22            .join("config.toml")
23    }
24
25    /// Load config from disk; returns Default::default() if the file doesn't exist yet.
26    pub fn load() -> Result<Self, BondError> {
27        let path = Self::config_path();
28        if !path.exists() {
29            return Ok(Self::default());
30        }
31        let content = fs::read_to_string(&path)?;
32        // toml::from_str returns a toml::de::Error; map it via BondError
33        toml::from_str(&content).map_err(|e| BondError::Config(e.to_string()))
34    }
35
36    /// Save config to disk, creating ~/.bonds/ if needed.
37    pub fn save(&self) -> Result<(), BondError> {
38        let path = Self::config_path();
39        if let Some(parent) = path.parent() {
40            fs::create_dir_all(parent)?;
41        }
42        let content = toml::to_string_pretty(self).map_err(|e| BondError::Config(e.to_string()))?;
43        fs::write(&path, content)?;
44        Ok(())
45    }
46}