Skip to main content

pxh/
config.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result, bail};
5use serde::{Deserialize, Serialize};
6use toml_edit::DocumentMut;
7
8/// Embedded default config template (repo root `config.toml`). Every key,
9/// commented out, at its default value. `pxh config` writes it when no
10/// config exists; `template_parses_to_defaults` keeps it honest.
11pub const DEFAULT_CONFIG: &str = include_str!("../config.toml");
12
13/// The strict answer to "what does pxh think of the config file?", for
14/// diagnostics. `Config::load()` collapses all three into a usable `Config`
15/// (falling back to defaults); doctor needs to tell them apart.
16#[derive(Debug)]
17pub enum ConfigStatus {
18    NotFound,
19    Valid(Box<Config>),
20    Invalid(String),
21}
22
23/// Strictly parse the config file at `path` -- the same parser `Config::load`
24/// uses, so doctor can never call "valid" a file that load would reject.
25pub fn config_status(path: &Path) -> ConfigStatus {
26    let content = match fs::read_to_string(path) {
27        Ok(c) => c,
28        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return ConfigStatus::NotFound,
29        Err(e) => return ConfigStatus::Invalid(format!("cannot read config: {e}")),
30    };
31    match toml::from_str(&content) {
32        Ok(cfg) => ConfigStatus::Valid(Box::new(cfg)),
33        Err(e) => ConfigStatus::Invalid(e.to_string()),
34    }
35}
36
37/// Configuration for history recording
38#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
39#[serde(default, deny_unknown_fields)]
40pub struct HistoryConfig {
41    /// Regex patterns for commands to ignore (not record).
42    /// Set to [] to disable.
43    pub ignore_patterns: Vec<String>,
44}
45
46fn default_ignore_patterns() -> Vec<String> {
47    vec![
48        "^ls$".into(),
49        "^cd( .)?$".into(),
50        "^pwd$".into(),
51        "^exit$".into(),
52        "^clear$".into(),
53        "^fg$".into(),
54        "^bg$".into(),
55        "^jobs$".into(),
56        "^history$".into(),
57        "^true$".into(),
58        "^false$".into(),
59    ]
60}
61
62impl Default for HistoryConfig {
63    fn default() -> Self {
64        HistoryConfig { ignore_patterns: default_ignore_patterns() }
65    }
66}
67
68/// Main configuration struct
69#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
70#[serde(deny_unknown_fields)]
71pub struct Config {
72    #[serde(default)]
73    pub host: HostConfig,
74    #[serde(default)]
75    pub recall: RecallConfig,
76    #[serde(default)]
77    pub shell: ShellConfig,
78    #[serde(default)]
79    pub history: HistoryConfig,
80}
81
82/// Configuration for host identity
83#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
84#[serde(default, deny_unknown_fields)]
85pub struct HostConfig {
86    pub hostname: Option<String>,
87    pub machine_id: Option<u64>,
88    pub aliases: Vec<String>,
89}
90
91/// Configuration for shell integration
92#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, Default)]
93#[serde(default, deny_unknown_fields)]
94pub struct ShellConfig {
95    /// Disable Ctrl-R binding (keep shell's default behavior)
96    pub disable_ctrl_r: bool,
97}
98
99/// Configuration for the recall TUI
100#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
101#[serde(default, deny_unknown_fields)]
102pub struct RecallConfig {
103    /// Keymap mode: "emacs" or "vim"
104    pub keymap: String,
105    /// Whether to show the preview pane
106    pub show_preview: bool,
107    /// Maximum number of results to load
108    pub result_limit: usize,
109    /// Preview pane configuration
110    pub preview: PreviewConfig,
111}
112
113impl Default for RecallConfig {
114    fn default() -> Self {
115        RecallConfig {
116            keymap: "emacs".to_string(),
117            show_preview: true,
118            result_limit: 5000,
119            preview: PreviewConfig::default(),
120        }
121    }
122}
123
124/// Configuration for what to show in the preview pane
125#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
126#[serde(default, deny_unknown_fields)]
127pub struct PreviewConfig {
128    pub show_directory: bool,
129    pub show_timestamp: bool,
130    pub show_exit_status: bool,
131    pub show_hostname: bool,
132    pub show_duration: bool,
133}
134
135impl Default for PreviewConfig {
136    fn default() -> Self {
137        PreviewConfig {
138            show_directory: true,
139            show_timestamp: true,
140            show_exit_status: true,
141            show_hostname: false,
142            show_duration: true,
143        }
144    }
145}
146
147/// Keymap mode for navigation
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub enum KeymapMode {
150    #[default]
151    Emacs,
152    VimInsert,
153    VimNormal,
154}
155
156impl RecallConfig {
157    /// Get the initial keymap mode from config
158    pub fn initial_keymap_mode(&self) -> KeymapMode {
159        match self.keymap.to_lowercase().as_str() {
160            "vim" => KeymapMode::VimInsert,
161            _ => KeymapMode::Emacs,
162        }
163    }
164}
165
166impl Config {
167    /// Load configuration from the default path, warning about a file that
168    /// cannot be parsed.
169    pub fn load() -> Self {
170        Self::load_from_default_path(true).unwrap_or_default()
171    }
172
173    /// Load configuration from the default path without printing anything.
174    /// The shell hooks run on every prompt with stderr on the terminal; a
175    /// config they cannot parse must not warn once per command.
176    pub fn load_quiet() -> Self {
177        Self::load_from_default_path(false).unwrap_or_default()
178    }
179
180    fn load_from_default_path(warn: bool) -> Option<Self> {
181        let config_path = Self::default_config_path()?;
182        Self::read_from_path(&config_path, warn)
183    }
184
185    /// Returns true if the config file exists but fails to parse.
186    /// Used to prevent migrate_host_settings from overwriting a corrupt config.
187    pub fn has_parse_error() -> bool {
188        let Some(path) = Self::default_config_path() else {
189            return false;
190        };
191        let Ok(content) = fs::read_to_string(&path) else {
192            return false; // file doesn't exist -- not a parse error
193        };
194        toml::from_str::<Config>(&content).is_err()
195    }
196
197    pub fn default_config_path() -> Option<PathBuf> {
198        Some(crate::pxh_config_dir()?.join("config.toml"))
199    }
200
201    pub fn load_from_path(path: &Path) -> Option<Self> {
202        Self::read_from_path(path, true)
203    }
204
205    fn read_from_path(path: &Path, warn: bool) -> Option<Self> {
206        let content = fs::read_to_string(path).ok()?;
207        match toml::from_str(&content) {
208            Ok(config) => Some(config),
209            Err(e) => {
210                if warn {
211                    // `e.message()` and not `{e}`: the full Display is a
212                    // multi-line snippet, which belongs in `pxh doctor`.
213                    crate::ui::warn(&format!(
214                        "failed to parse {}: {}; using defaults (see 'pxh doctor')",
215                        path.display(),
216                        e.message()
217                    ));
218                }
219                None
220            }
221        }
222    }
223
224    /// Update the config file at the default path, preserving existing content.
225    /// Each update is a (dotted_key, value) pair, e.g. ("host.hostname", value).
226    pub fn update_default_config(updates: &[(&str, toml_edit::Item)]) -> Result<()> {
227        let path = Self::default_config_path().context("Could not determine config path")?;
228        Self::update_config_at_path(&path, updates)
229    }
230
231    pub fn update_config_at_path(
232        path: &PathBuf,
233        updates: &[(&str, toml_edit::Item)],
234    ) -> Result<()> {
235        // A config file born here starts from the commented template, so the
236        // file the user later opens explains every key it does not set.
237        let content = match fs::read_to_string(path) {
238            Ok(c) => c,
239            Err(e) if e.kind() == std::io::ErrorKind::NotFound => DEFAULT_CONFIG.to_string(),
240            Err(e) => return Err(e.into()),
241        };
242        let mut doc: DocumentMut = content.parse()?;
243
244        for (dotted_key, item) in updates {
245            let parts: Vec<&str> = dotted_key.split('.').collect();
246            match parts.as_slice() {
247                [section, key] => {
248                    if !doc.contains_table(section) {
249                        doc[section] = toml_edit::Item::Table(toml_edit::Table::new());
250                    }
251                    doc[section][key] = item.clone();
252                }
253                [key] => {
254                    doc[key] = item.clone();
255                }
256                _ => bail!("Unsupported key depth: {dotted_key}"),
257            }
258        }
259
260        if let Some(parent) = path.parent() {
261            fs::create_dir_all(parent)?;
262        }
263        fs::write(path, doc.to_string())?;
264        Ok(())
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::*;
271
272    #[test]
273    fn test_default_config() {
274        let config = Config::default();
275        assert_eq!(config.recall.keymap, "emacs");
276        assert!(config.recall.show_preview);
277        assert_eq!(config.recall.result_limit, 5000);
278        assert!(config.recall.preview.show_directory);
279        assert!(config.recall.preview.show_timestamp);
280        assert!(config.recall.preview.show_exit_status);
281        assert!(!config.recall.preview.show_hostname);
282        assert!(config.recall.preview.show_duration);
283        assert!(!config.history.ignore_patterns.is_empty());
284        assert!(config.history.ignore_patterns.contains(&"^ls$".to_string()));
285    }
286
287    #[test]
288    fn test_parse_config() {
289        let toml = r#"
290[recall]
291keymap = "vim"
292show_preview = false
293result_limit = 1000
294
295[recall.preview]
296show_directory = false
297show_hostname = true
298"#;
299        let config: Config = toml::from_str(toml).unwrap();
300        assert_eq!(config.recall.keymap, "vim");
301        assert!(!config.recall.show_preview);
302        assert_eq!(config.recall.result_limit, 1000);
303        assert!(!config.recall.preview.show_directory);
304        assert!(config.recall.preview.show_hostname);
305        // Defaults should be preserved for unspecified fields
306        assert!(config.recall.preview.show_timestamp);
307        assert!(config.recall.preview.show_exit_status);
308    }
309
310    #[test]
311    fn test_default_host_config() {
312        let config = Config::default();
313        assert!(config.host.hostname.is_none());
314        assert!(config.host.machine_id.is_none());
315        assert!(config.host.aliases.is_empty());
316    }
317
318    #[test]
319    fn test_parse_host_config() {
320        let toml = r#"
321[host]
322hostname = "my-old-mac"
323machine_id = 12345678901234567
324aliases = ["old-mac", "work-laptop"]
325"#;
326        let config: Config = toml::from_str(toml).unwrap();
327        assert_eq!(config.host.hostname.as_deref(), Some("my-old-mac"));
328        assert_eq!(config.host.machine_id, Some(12345678901234567));
329        assert_eq!(config.host.aliases, vec!["old-mac", "work-laptop"]);
330    }
331
332    #[test]
333    fn test_parse_partial_host_config() {
334        let toml = r#"
335[host]
336aliases = ["other-host"]
337"#;
338        let config: Config = toml::from_str(toml).unwrap();
339        assert!(config.host.hostname.is_none());
340        assert!(config.host.machine_id.is_none());
341        assert_eq!(config.host.aliases, vec!["other-host"]);
342    }
343
344    #[test]
345    fn test_update_config_preserves_existing() {
346        let dir = tempfile::tempdir().unwrap();
347        let path = dir.path().join("config.toml");
348        fs::write(
349            &path,
350            r#"# my comment
351[recall]
352keymap = "vim"
353"#,
354        )
355        .unwrap();
356
357        Config::update_config_at_path(
358            &path,
359            &[
360                ("host.hostname", toml_edit::value("my-host")),
361                ("host.machine_id", toml_edit::value(42_i64)),
362            ],
363        )
364        .unwrap();
365
366        let content = fs::read_to_string(&path).unwrap();
367        assert!(content.contains("# my comment"), "comment preserved");
368        assert!(content.contains("keymap = \"vim\""), "existing config preserved");
369        assert!(content.contains("hostname = \"my-host\""));
370        assert!(content.contains("machine_id = 42"));
371
372        let config = Config::load_from_path(&path).unwrap();
373        assert_eq!(config.host.hostname.as_deref(), Some("my-host"));
374        assert_eq!(config.recall.keymap, "vim");
375    }
376
377    #[test]
378    fn test_update_config_creates_file() {
379        let dir = tempfile::tempdir().unwrap();
380        let path = dir.path().join("subdir").join("config.toml");
381
382        Config::update_config_at_path(
383            &path,
384            &[("host.aliases", toml_edit::value(toml_edit::Array::from_iter(["a", "b"])))],
385        )
386        .unwrap();
387
388        let config = Config::load_from_path(&path).unwrap();
389        assert_eq!(config.host.aliases, vec!["a", "b"]);
390    }
391
392    #[test]
393    fn test_existing_config_without_host_section() {
394        let toml = r#"
395[recall]
396keymap = "vim"
397"#;
398        let config: Config = toml::from_str(toml).unwrap();
399        assert!(config.host.hostname.is_none());
400        assert!(config.host.aliases.is_empty());
401        assert_eq!(config.recall.keymap, "vim");
402    }
403
404    #[test]
405    fn test_parse_history_config() {
406        let toml = r#"
407[history]
408ignore_patterns = ["^secret$", "^rm -rf"]
409"#;
410        let config: Config = toml::from_str(toml).unwrap();
411        assert_eq!(config.history.ignore_patterns, vec!["^secret$", "^rm -rf"]);
412    }
413
414    #[test]
415    fn test_parse_empty_history_ignore_patterns() {
416        let toml = r#"
417[history]
418ignore_patterns = []
419"#;
420        let config: Config = toml::from_str(toml).unwrap();
421        assert!(config.history.ignore_patterns.is_empty());
422    }
423
424    #[test]
425    fn test_missing_history_section_uses_defaults() {
426        let toml = r#"
427[recall]
428keymap = "vim"
429"#;
430        let config: Config = toml::from_str(toml).unwrap();
431        assert!(!config.history.ignore_patterns.is_empty());
432        assert!(config.history.ignore_patterns.contains(&"^ls$".to_string()));
433    }
434
435    #[test]
436    fn test_default_ignore_patterns_are_valid_regexes() {
437        let config = HistoryConfig::default();
438        let set = regex::RegexSet::new(&config.ignore_patterns);
439        assert!(set.is_ok(), "default patterns should all be valid regexes");
440    }
441
442    #[test]
443    fn test_invalid_toml_returns_none() {
444        let dir = tempfile::TempDir::new().unwrap();
445        let path = dir.path().join("bad.toml");
446        fs::write(&path, "this is not valid [[ toml").unwrap();
447        assert!(Config::load_from_path(&path).is_none());
448    }
449
450    #[test]
451    fn test_wrong_type_returns_none() {
452        let dir = tempfile::TempDir::new().unwrap();
453        let path = dir.path().join("bad_type.toml");
454        fs::write(&path, "[recall]\nresult_limit = \"not a number\"\n").unwrap();
455        assert!(Config::load_from_path(&path).is_none());
456    }
457
458    #[test]
459    fn test_initial_keymap_mode() {
460        let mut config = RecallConfig::default();
461        assert_eq!(config.initial_keymap_mode(), KeymapMode::Emacs);
462
463        config.keymap = "vim".to_string();
464        assert_eq!(config.initial_keymap_mode(), KeymapMode::VimInsert);
465
466        config.keymap = "VIM".to_string();
467        assert_eq!(config.initial_keymap_mode(), KeymapMode::VimInsert);
468
469        config.keymap = "unknown".to_string();
470        assert_eq!(config.initial_keymap_mode(), KeymapMode::Emacs);
471    }
472
473    #[test]
474    fn unknown_keys_are_rejected() {
475        let err = toml::from_str::<Config>("[recall]\nkeymap = \"vim\"\nshow_previeww = true\n")
476            .unwrap_err()
477            .to_string();
478        assert!(err.contains("unknown field `show_previeww`"), "{err}");
479    }
480
481    #[test]
482    fn unknown_sections_are_rejected() {
483        let err = toml::from_str::<Config>("[recal]\nkeymap = \"vim\"\n").unwrap_err().to_string();
484        assert!(err.contains("unknown field `recal`"), "{err}");
485    }
486
487    /// The template ships every key, commented, at its default value. If a
488    /// default changes and the template does not, this fails.
489    #[test]
490    fn template_parses_to_defaults() {
491        let parsed: Config = toml::from_str(DEFAULT_CONFIG).expect("template is valid");
492        assert_eq!(parsed, Config::default());
493    }
494
495    #[test]
496    fn template_uncommented_parses_to_defaults() {
497        // Strip exactly one leading `# ` from commented key lines so the
498        // documented values are exercised, not just the comments.
499        let uncommented: String = DEFAULT_CONFIG
500            .lines()
501            .map(|l| l.strip_prefix("# ").filter(|r| r.contains(" = ")).unwrap_or(l))
502            .collect::<Vec<_>>()
503            .join("\n");
504        let parsed: Config = toml::from_str(&uncommented).expect("uncommented template is valid");
505        assert_eq!(parsed, Config::default());
506    }
507
508    #[test]
509    fn config_status_distinguishes_missing_invalid_and_valid() {
510        let dir = tempfile::tempdir().unwrap();
511        let path = dir.path().join("config.toml");
512        assert!(matches!(config_status(&path), ConfigStatus::NotFound));
513
514        fs::write(&path, "[recall]\nkeymap = ").unwrap();
515        assert!(matches!(config_status(&path), ConfigStatus::Invalid(_)));
516
517        fs::write(&path, "[recall]\nnope = 1\n").unwrap();
518        match config_status(&path) {
519            ConfigStatus::Invalid(msg) => assert!(msg.contains("unknown field `nope`"), "{msg}"),
520            other => panic!("expected Invalid, got {other:?}"),
521        }
522
523        fs::write(&path, "[recall]\nkeymap = \"vim\"\n").unwrap();
524        match config_status(&path) {
525            ConfigStatus::Valid(cfg) => assert_eq!(cfg.recall.keymap, "vim"),
526            other => panic!("expected Valid, got {other:?}"),
527        }
528    }
529}