1use std::fmt;
8use std::io;
9use std::path::{Path, PathBuf};
10
11use serde::Serialize;
12use serde::de::DeserializeOwned;
13
14use crate::App;
15
16#[derive(Debug)]
18pub enum ConfigError {
19 Io(io::Error),
21 Parse {
23 path: PathBuf,
25 source: toml::de::Error,
27 },
28 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
58pub 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
78pub 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
92pub 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 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 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 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 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}