1pub mod fields;
2
3pub use fields::{CONFIG_FIELDS, ConfigFieldSpec, ConfigKey, FieldKind};
4
5use serde::{Deserialize, Serialize};
6use std::fs;
7use std::path::{Path, PathBuf};
8
9use crate::error::{Result, SnipError};
10use crate::filesystem::{atomic_write, normalize_tags};
11use crate::sort::SortMode;
12
13pub const CONFIG_SCHEMA_VERSION: u32 = 1;
14
15#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum OutputSetting {
18 Human,
19 Json,
20 Jsonl,
21}
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum ColorSetting {
26 Auto,
27 Always,
28 Never,
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
32#[serde(rename_all = "lowercase")]
33pub enum PreviewRenderSetting {
34 Ansi,
35 Plain,
36 Html,
37}
38
39#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
40#[serde(rename_all = "lowercase")]
41pub enum EditorCwdSetting {
42 #[default]
43 Inherit,
44 Library,
45 Folder,
46 Snippet,
47 Fragment,
48}
49
50pub const EDITOR_CWD_VALUES: &str = "inherit, library, folder, snippet, or fragment";
51
52impl std::str::FromStr for EditorCwdSetting {
53 type Err = ();
54
55 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
56 match value.trim().to_ascii_lowercase().as_str() {
57 "inherit" => Ok(Self::Inherit),
58 "library" => Ok(Self::Library),
59 "folder" => Ok(Self::Folder),
60 "snippet" => Ok(Self::Snippet),
61 "fragment" => Ok(Self::Fragment),
62 _ => Err(()),
63 }
64 }
65}
66
67#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "lowercase")]
69pub enum TuiThemeSetting {
70 #[default]
71 Auto,
72 Light,
73 Dark,
74}
75
76#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, Deserialize)]
77#[serde(rename_all = "lowercase")]
78pub enum TuiDensitySetting {
79 #[default]
80 Comfortable,
81 Compact,
82}
83
84impl TuiDensitySetting {
85 pub const fn next(self) -> Self {
86 match self {
87 Self::Comfortable => Self::Compact,
88 Self::Compact => Self::Comfortable,
89 }
90 }
91
92 pub const fn row_height(self) -> u16 {
93 match self {
94 Self::Comfortable => 2,
95 Self::Compact => 1,
96 }
97 }
98
99 pub const fn label(self) -> &'static str {
100 match self {
101 Self::Comfortable => "comfortable",
102 Self::Compact => "compact",
103 }
104 }
105}
106
107#[derive(Clone, Debug, Serialize, Deserialize)]
108pub struct TuiConfig {
109 #[serde(default)]
110 pub theme: TuiThemeSetting,
111 #[serde(default, skip_serializing_if = "Option::is_none")]
112 pub light_theme: Option<String>,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub dark_theme: Option<String>,
115 #[serde(default)]
116 pub sort: SortMode,
117 #[serde(default)]
118 pub density: TuiDensitySetting,
119 #[serde(default = "default_line_numbers")]
122 pub line_numbers: bool,
123 #[serde(default)]
125 pub simplified_ui: bool,
126 #[serde(flatten)]
127 pub extra: toml::Table,
128}
129
130pub(crate) const fn default_line_numbers() -> bool {
131 true
132}
133
134impl Default for TuiConfig {
135 fn default() -> Self {
136 Self {
137 theme: TuiThemeSetting::default(),
138 light_theme: None,
139 dark_theme: None,
140 sort: SortMode::default(),
141 density: TuiDensitySetting::default(),
142 line_numbers: default_line_numbers(),
143 simplified_ui: false,
144 extra: toml::Table::new(),
145 }
146 }
147}
148
149#[derive(Clone, Debug, Default, Serialize, Deserialize)]
150pub struct GitConfig {
151 #[serde(default, alias = "auto_backup_interval")]
152 pub auto_commit_interval: u32,
153 #[serde(default)]
154 pub auto_push: bool,
155 #[serde(default)]
156 pub auto_pull: bool,
157 #[serde(default)]
158 pub backup_on_quit: bool,
159 #[serde(flatten)]
160 pub extra: toml::Table,
161}
162
163#[derive(Clone, Debug, Serialize, Deserialize)]
164pub struct AppConfig {
165 pub schema_version: u32,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub default_library: Option<PathBuf>,
168 #[serde(default, skip_serializing_if = "Option::is_none")]
169 pub output: Option<OutputSetting>,
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub color: Option<ColorSetting>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub preview_render: Option<PreviewRenderSetting>,
174 #[serde(default, skip_serializing_if = "Option::is_none")]
175 pub preview_pager: Option<bool>,
176 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub editor: Option<String>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub editor_cwd: Option<EditorCwdSetting>,
180 #[serde(default, skip_serializing_if = "Option::is_none")]
181 pub gui_editor: Option<String>,
182 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub vscode_cmd: Option<String>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
185 pub pager: Option<String>,
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub default_language: Option<String>,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub default_folder: Option<String>,
190 #[serde(default, skip_serializing_if = "Vec::is_empty")]
191 pub default_tags: Vec<String>,
192 #[serde(default, skip_serializing_if = "Option::is_none")]
193 pub tui: Option<TuiConfig>,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub git: Option<GitConfig>,
196 #[serde(flatten)]
197 pub extra: toml::Table,
198}
199
200impl Default for AppConfig {
201 fn default() -> Self {
202 Self {
203 schema_version: CONFIG_SCHEMA_VERSION,
204 default_library: None,
205 output: None,
206 color: None,
207 preview_render: None,
208 preview_pager: None,
209 editor: None,
210 editor_cwd: None,
211 gui_editor: None,
212 vscode_cmd: None,
213 pager: None,
214 default_language: None,
215 default_folder: None,
216 default_tags: Vec::new(),
217 tui: None,
218 git: None,
219 extra: toml::Table::new(),
220 }
221 }
222}
223
224impl AppConfig {
225 pub fn gui_editor_command(&self) -> Option<&str> {
227 self.gui_editor.as_deref().or(self.vscode_cmd.as_deref())
228 }
229
230 pub fn load() -> Result<Self> {
232 Self::load_from(&config_path()?)
233 }
234
235 pub fn load_from(path: &Path) -> Result<Self> {
236 if !path.exists() {
237 return Ok(Self::default());
238 }
239 let text = fs::read_to_string(path).map_err(|error| {
240 SnipError::io(format!("cannot read config {}: {error}", path.display()))
241 })?;
242 let mut config: Self = toml::from_str(&text).map_err(|error| {
243 SnipError::validation(format!("cannot parse config {}: {error}", path.display()))
244 })?;
245 config.validate(path)?;
246 config.default_tags = normalize_tags(&config.default_tags)?;
247 Ok(config)
248 }
249
250 pub fn save(&self) -> Result<()> {
251 self.save_to(&config_path()?)
252 }
253
254 pub fn save_to(&self, path: &Path) -> Result<()> {
255 self.validate(path)?;
256 let data = toml::to_string_pretty(self)?;
257 atomic_write(path, data.as_bytes())
258 }
259
260 fn validate(&self, path: &Path) -> Result<()> {
261 if self.schema_version > CONFIG_SCHEMA_VERSION {
262 return Err(SnipError::validation(format!(
263 "config {} uses schema version {}, but this snip supports up to {}",
264 path.display(),
265 self.schema_version,
266 CONFIG_SCHEMA_VERSION
267 )));
268 }
269 if self.schema_version == 0 {
270 return Err(SnipError::validation(format!(
271 "config {} has invalid schema version 0",
272 path.display()
273 )));
274 }
275 for (name, value) in [
276 ("editor", self.editor.as_deref()),
277 ("gui_editor", self.gui_editor.as_deref()),
278 ("vscode_cmd", self.vscode_cmd.as_deref()),
279 ("pager", self.pager.as_deref()),
280 ("default_language", self.default_language.as_deref()),
281 (
282 "tui.light_theme",
283 self.tui
284 .as_ref()
285 .and_then(|config| config.light_theme.as_deref()),
286 ),
287 (
288 "tui.dark_theme",
289 self.tui
290 .as_ref()
291 .and_then(|config| config.dark_theme.as_deref()),
292 ),
293 ] {
294 if value.is_some_and(|value| value.trim().is_empty()) {
295 return Err(SnipError::validation(format!(
296 "config value {name} cannot be empty"
297 )));
298 }
299 }
300 normalize_tags(&self.default_tags)?;
301 Ok(())
302 }
303}
304
305pub fn config_path() -> Result<PathBuf> {
306 if let Some(root) = std::env::var_os("XDG_CONFIG_HOME").filter(|value| !value.is_empty()) {
307 return Ok(PathBuf::from(root).join("snip/config.toml"));
308 }
309 let home = std::env::var_os("HOME")
310 .or_else(|| std::env::var_os("USERPROFILE"))
311 .filter(|value| !value.is_empty())
312 .ok_or_else(|| SnipError::io("cannot locate config: HOME or USERPROFILE is not set"))?;
313 Ok(PathBuf::from(home).join(".config/snip/config.toml"))
314}
315
316#[cfg(test)]
317mod tests {
318 use super::AppConfig;
319
320 #[test]
321 fn gui_editor_command_prefers_new_key_and_keeps_legacy_fallback() {
322 let config = AppConfig {
323 gui_editor: Some("zed".to_owned()),
324 vscode_cmd: Some("code-insiders".to_owned()),
325 ..AppConfig::default()
326 };
327 assert_eq!(config.gui_editor_command(), Some("zed"));
328
329 let legacy = AppConfig {
330 vscode_cmd: Some("code-insiders".to_owned()),
331 ..AppConfig::default()
332 };
333 assert_eq!(legacy.gui_editor_command(), Some("code-insiders"));
334 assert_eq!(AppConfig::default().gui_editor_command(), None);
335 }
336}