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    /// Errors if the file exists but can't be read or parsed.
27    pub fn load() -> Result<Self, BondError> {
28        let path = Self::config_path();
29        if !path.exists() {
30            return Ok(Self::default());
31        }
32        let content = fs::read_to_string(&path)?;
33        // toml::from_str returns a toml::de::Error; map it via BondError
34        toml::from_str(&content).map_err(|e| BondError::Config(e.to_string()))
35    }
36
37    /// Save config to disk, creating ~/.bonds/ if needed.
38    /// Errors if the file can't be written.
39    pub fn save(&self) -> Result<(), BondError> {
40        let path = Self::config_path();
41        if let Some(parent) = path.parent() {
42            fs::create_dir_all(parent)?;
43        }
44        let content = toml::to_string_pretty(self).map_err(|e| BondError::Config(e.to_string()))?;
45        fs::write(&path, content)?;
46        Ok(())
47    }
48}