Skip to main content

option_sdk/
config.rs

1//! Typed TOML config persistence for Option family apps.
2//!
3//! `~/.option/<dir>/config.toml` is the canonical per-app config file.
4//! [`load_toml`] / [`save_toml`] work on explicit paths; [`App::load_config`]
5//! / [`App::save_config`] wrap them for the app directory.
6
7use std::fmt;
8use std::io;
9use std::path::{Path, PathBuf};
10
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13
14use crate::App;
15
16/// Errors from TOML config load/save.
17#[derive(Debug)]
18pub enum ConfigError {
19    /// Filesystem error (already carries the path via [`crate::atomic_write`]).
20    Io(io::Error),
21    /// The file exists but is not valid TOML for `T`.
22    Parse {
23        /// Path of the offending file.
24        path: PathBuf,
25        /// TOML deserialization error.
26        source: toml::de::Error,
27    },
28    /// `T` failed to serialize to TOML.
29    Serialize(toml::ser::Error),
30}
31
32impl fmt::Display for ConfigError {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        match self {
35            Self::Io(error) => write!(f, "{error}"),
36            Self::Parse { path, source } => write!(f, "{}: {source}", path.display()),
37            Self::Serialize(source) => write!(f, "{source}"),
38        }
39    }
40}
41
42impl std::error::Error for ConfigError {
43    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
44        match self {
45            Self::Io(error) => Some(error),
46            Self::Parse { source, .. } => Some(source),
47            Self::Serialize(source) => Some(source),
48        }
49    }
50}
51
52impl From<io::Error> for ConfigError {
53    fn from(error: io::Error) -> Self {
54        Self::Io(error)
55    }
56}
57
58/// Load a TOML file as `T`.
59///
60/// Returns `Ok(None)` when the file does not exist; a file that exists but
61/// fails to parse is a [`ConfigError::Parse`].
62pub fn load_toml<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, ConfigError> {
63    if !path.exists() {
64        return Ok(None);
65    }
66    let text = match std::fs::read_to_string(path) {
67        Ok(text) => text,
68        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
69        Err(error) => return Err(error.into()),
70    };
71    let value = toml::from_str(&text).map_err(|source| ConfigError::Parse {
72        path: path.to_path_buf(),
73        source,
74    })?;
75    Ok(Some(value))
76}
77
78/// Load the first existing file from `paths`, returning the winning path too.
79///
80/// Useful for legacy config locations: order `paths` from newest to oldest.
81pub fn load_toml_chain<T: DeserializeOwned>(
82    paths: &[PathBuf],
83) -> Result<Option<(T, PathBuf)>, ConfigError> {
84    for path in paths {
85        if path.exists() {
86            return load_toml(path).map(|value| value.map(|v| (v, path.clone())));
87        }
88    }
89    Ok(None)
90}
91
92/// Serialize `value` as pretty TOML and persist it via [`crate::atomic_write`].
93pub fn save_toml<T: Serialize>(path: &Path, value: &T) -> Result<(), ConfigError> {
94    let text = toml::to_string_pretty(value).map_err(ConfigError::Serialize)?;
95    crate::atomic_write(path, text.as_bytes())?;
96    Ok(())
97}
98
99impl App {
100    /// Load `config.toml`, writing `T::default()` when the file is missing.
101    ///
102    /// Runs [`App::ensure`] first, so the app directory and legacy migration
103    /// are handled before the file is touched.
104    pub fn load_config<T: DeserializeOwned + Serialize + Default>(&self) -> Result<T, ConfigError> {
105        self.ensure()?;
106        let path = self.config_toml();
107        match load_toml(&path)? {
108            Some(value) => Ok(value),
109            None => {
110                let value = T::default();
111                save_toml(&path, &value)?;
112                Ok(value)
113            }
114        }
115    }
116
117    /// Persist `value` to `config.toml` (via [`crate::atomic_write`]).
118    pub fn save_config<T: Serialize>(&self, value: &T) -> Result<(), ConfigError> {
119        self.ensure()?;
120        save_toml(&self.config_toml(), value)
121    }
122}
123
124#[cfg(test)]
125mod tests {
126    use super::*;
127    use crate::test_env;
128    use serde::Deserialize;
129
130    #[derive(Serialize, Deserialize, Default, PartialEq, Debug)]
131    struct Settings {
132        name: String,
133        count: u32,
134        enabled: bool,
135    }
136
137    fn sample() -> Settings {
138        Settings {
139            name: "option".to_string(),
140            count: 3,
141            enabled: true,
142        }
143    }
144
145    #[test]
146    fn roundtrip() {
147        let root = tempfile::tempdir().unwrap();
148        let path = root.path().join("config.toml");
149        save_toml(&path, &sample()).unwrap();
150        assert_eq!(load_toml::<Settings>(&path).unwrap(), Some(sample()));
151    }
152
153    #[test]
154    fn missing_file_is_none() {
155        let root = tempfile::tempdir().unwrap();
156        let path = root.path().join("nope.toml");
157        assert_eq!(load_toml::<Settings>(&path).unwrap(), None);
158    }
159
160    #[test]
161    fn invalid_toml_reports_path() {
162        let root = tempfile::tempdir().unwrap();
163        let path = root.path().join("broken.toml");
164        std::fs::write(&path, "this is = [not toml").unwrap();
165        match load_toml::<Settings>(&path) {
166            Err(ConfigError::Parse { path: p, .. }) => {
167                assert_eq!(p, path);
168            }
169            other => panic!("expected Parse error, got {other:?}"),
170        }
171        let err = load_toml::<Settings>(&path).unwrap_err();
172        assert!(err.to_string().contains(path.to_str().unwrap()));
173    }
174
175    #[test]
176    fn chain_picks_first_existing() {
177        let root = tempfile::tempdir().unwrap();
178        let first = root.path().join("a.toml");
179        let second = root.path().join("b.toml");
180        let third = root.path().join("c.toml");
181        save_toml(&second, &sample()).unwrap();
182        save_toml(&third, &Settings::default()).unwrap();
183        let (value, winner) =
184            load_toml_chain::<Settings>(&[first.clone(), second.clone(), third.clone()])
185                .unwrap()
186                .unwrap();
187        assert_eq!(value, sample());
188        assert_eq!(winner, second);
189        assert_eq!(load_toml_chain::<Settings>(&[first]).unwrap(), None);
190    }
191
192    #[test]
193    fn load_config_writes_defaults() {
194        let _guard = test_env::lock();
195        let root = tempfile::tempdir().unwrap();
196        // SAFETY: tests serialize env mutation via ENV_LOCK.
197        unsafe {
198            std::env::set_var("OPTION_HOME", root.path());
199        }
200        let app = App::OPSH;
201        let path = app.config_toml();
202        assert!(!path.exists());
203        let settings = app.load_config::<Settings>().unwrap();
204        assert_eq!(settings, Settings::default());
205        assert!(path.is_file());
206        // Second call reads the file back instead of rewriting.
207        assert_eq!(app.load_config::<Settings>().unwrap(), Settings::default());
208        app.save_config(&sample()).unwrap();
209        assert_eq!(app.load_config::<Settings>().unwrap(), sample());
210        unsafe {
211            std::env::remove_var("OPTION_HOME");
212        }
213    }
214}