From 2f671f196e245ac1a791c001286e401a2fab9d3a Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Mon, 20 Jul 2026 23:00:06 +0200 Subject: chore: Commit --- crates/daemon/src/aclient/settings/meta.rs | 2 +- crates/daemon/src/aclient/settings/mod.rs | 279 +++++++++++++------------- crates/daemon/src/aclient/settings/watcher.rs | 260 ------------------------ 3 files changed, 140 insertions(+), 401 deletions(-) delete mode 100644 crates/daemon/src/aclient/settings/watcher.rs (limited to 'crates/daemon/src/aclient/settings') diff --git a/crates/daemon/src/aclient/settings/meta.rs b/crates/daemon/src/aclient/settings/meta.rs index 7993ef6d..1c9b9cd1 100644 --- a/crates/daemon/src/aclient/settings/meta.rs +++ b/crates/daemon/src/aclient/settings/meta.rs @@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize, Deserialize, Clone)] pub(crate) struct Settings { - pub(crate) db_path: String, + pub(super) db_path: String, } impl Default for Settings { diff --git a/crates/daemon/src/aclient/settings/mod.rs b/crates/daemon/src/aclient/settings/mod.rs index 58afd17c..10c84f50 100644 --- a/crates/daemon/src/aclient/settings/mod.rs +++ b/crates/daemon/src/aclient/settings/mod.rs @@ -24,8 +24,7 @@ static DATA_DIR: OnceLock = OnceLock::new(); static META_CONFIG: OnceLock<(String, f64)> = OnceLock::new(); static META_STORE: OnceCell = OnceCell::const_new(); -pub(crate) mod meta; -pub(crate) mod watcher; +mod meta; #[derive(Clone, Debug, Deserialize, Copy, ValueEnum, PartialEq, Serialize)] pub(crate) enum SearchMode { @@ -48,7 +47,7 @@ pub(crate) enum SearchMode { } impl SearchMode { - pub(crate) fn as_str(self) -> &'static str { + fn as_str(self) -> &'static str { match self { Self::Prefix => "PREFIX", Self::FullText => "FULLTXT", @@ -57,7 +56,7 @@ impl SearchMode { Self::DaemonFuzzy => "DAEMON", } } - pub(crate) fn next(self, settings: &Settings) -> Self { + fn next(self, settings: &Settings) -> Self { match self { Self::Prefix => Self::FullText, // if the user is using skim, we go to skim @@ -93,7 +92,7 @@ pub(crate) enum FilterMode { } impl FilterMode { - pub(crate) fn as_str(self) -> &'static str { + fn as_str(self) -> &'static str { match self { Self::Global => "GLOBAL", Self::Host => "HOST", @@ -106,7 +105,7 @@ impl FilterMode { } #[derive(Clone, Debug, Deserialize, Copy, Serialize)] -pub(crate) enum ExitMode { +enum ExitMode { #[serde(rename = "return-original")] ReturnOriginal, @@ -117,7 +116,7 @@ pub(crate) enum ExitMode { // FIXME: Can use upstream Dialect enum if https://github.com/stevedonovan/chrono-english/pull/16 is merged // FIXME: Above PR was merged, but dependency was changed to interim (fork of chrono-english) in the ... interim #[derive(Clone, Debug, Deserialize, Copy, Serialize)] -pub(crate) enum Dialect { +enum Dialect { #[serde(rename = "us")] Us, @@ -141,7 +140,7 @@ impl From for interim::Dialect { /// /// See: #[derive(Clone, Copy, Debug, Eq, PartialEq, DeserializeFromStr, Serialize)] -pub(crate) struct Timezone(pub(crate) UtcOffset); +struct Timezone(UtcOffset); impl fmt::Display for Timezone { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) @@ -185,7 +184,7 @@ impl FromStr for Timezone { } #[derive(Clone, Debug, Deserialize, Copy, Serialize)] -pub(crate) enum Style { +enum Style { #[serde(rename = "auto")] Auto, @@ -197,7 +196,7 @@ pub(crate) enum Style { } #[derive(Clone, Debug, Deserialize, Copy, Serialize)] -pub(crate) enum WordJumpMode { +enum WordJumpMode { #[serde(rename = "emacs")] Emacs, @@ -206,7 +205,7 @@ pub(crate) enum WordJumpMode { } #[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)] -pub(crate) enum KeymapMode { +enum KeymapMode { #[serde(rename = "emacs")] Emacs, @@ -226,7 +225,7 @@ pub(crate) enum KeymapMode { // used in HashMap (https://stackoverflow.com/questions/67142663). We instead // define an adapter type. #[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)] -pub(crate) enum CursorStyle { +enum CursorStyle { #[serde(rename = "default")] DefaultUserShape, @@ -250,13 +249,13 @@ pub(crate) enum CursorStyle { } #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Stats { +struct Stats { #[serde(default = "Stats::common_prefix_default")] - pub(crate) common_prefix: Vec, // sudo, etc. commands we want to strip off + common_prefix: Vec, // sudo, etc. commands we want to strip off #[serde(default = "Stats::common_subcommands_default")] - pub(crate) common_subcommands: Vec, // kubectl, commands we should consider subcommands for + common_subcommands: Vec, // kubectl, commands we should consider subcommands for #[serde(default = "Stats::ignored_commands_default")] - pub(crate) ignored_commands: Vec, // cd, ls, etc. commands we want to completely hide from stats + ignored_commands: Vec, // cd, ls, etc. commands we want to completely hide from stats } impl Stats { @@ -310,19 +309,19 @@ impl Default for Stats { #[derive(Clone, Debug, Deserialize, Default, Serialize)] #[expect(clippy::struct_excessive_bools)] -pub(crate) struct Keys { - pub(crate) scroll_exits: bool, - pub(crate) exit_past_line_start: bool, - pub(crate) accept_past_line_end: bool, - pub(crate) accept_past_line_start: bool, - pub(crate) accept_with_backspace: bool, - pub(crate) prefix: String, +struct Keys { + scroll_exits: bool, + exit_past_line_start: bool, + accept_past_line_end: bool, + accept_past_line_start: bool, + accept_with_backspace: bool, + prefix: String, } impl Keys { /// The standard default values for all `[keys]` options. /// These match the config defaults set in `builder_with_data_dir()`. - pub(crate) fn standard_defaults() -> Self { + fn standard_defaults() -> Self { Self { scroll_exits: true, exit_past_line_start: true, @@ -336,19 +335,19 @@ impl Keys { /// A single rule within a conditional keybinding config. #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct KeyRuleConfig { +struct KeyRuleConfig { /// Optional condition expression (e.g. "cursor-at-start", "input-empty && no-results"). /// If absent, the rule always matches. #[serde(default)] - pub(crate) when: Option, + when: Option, /// The action to perform (e.g. "exit", "cursor-left", "accept"). - pub(crate) action: String, + action: String, } /// A keybinding config value: either a simple action string or an ordered list of conditional rules. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(untagged)] -pub(crate) enum KeyBindingConfig { +enum KeyBindingConfig { /// Simple unconditional binding: `"ctrl-c" = "return-original"` Simple(String), /// Conditional binding: `"left" = [{ when = "cursor-at-start", action = "exit" }, { action = "cursor-left" }]` @@ -358,22 +357,22 @@ pub(crate) enum KeyBindingConfig { /// User-facing keymap configuration. Each mode maps key strings to bindings. /// Keys present here override the defaults for that key; unmentioned keys keep defaults. #[derive(Clone, Debug, Deserialize, Serialize, Default)] -pub(crate) struct KeymapConfig { +struct KeymapConfig { #[serde(default)] - pub(crate) emacs: HashMap, + emacs: HashMap, #[serde(default, rename = "vim-normal")] - pub(crate) vim_normal: HashMap, + vim_normal: HashMap, #[serde(default, rename = "vim-insert")] - pub(crate) vim_insert: HashMap, + vim_insert: HashMap, #[serde(default)] - pub(crate) inspector: HashMap, + inspector: HashMap, #[serde(default)] - pub(crate) prefix: HashMap, + prefix: HashMap, } impl KeymapConfig { /// Returns true if no keybinding overrides are configured in any mode. - pub(crate) fn is_empty(&self) -> bool { + fn is_empty(&self) -> bool { self.emacs.is_empty() && self.vim_normal.is_empty() && self.vim_insert.is_empty() @@ -383,50 +382,50 @@ impl KeymapConfig { } #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Preview { - pub(crate) strategy: PreviewStrategy, +struct Preview { + strategy: PreviewStrategy, } #[derive(Clone, Debug, Deserialize, Serialize)] -pub struct Daemon { +pub(crate) struct Daemon { /// The daemon will handle sync on an interval. How often to sync, in seconds. - pub sync_frequency: u64, + pub(crate) sync_frequency: u64, /// The path to the unix socket used by the daemon - pub socket_path: String, + pub(crate) socket_path: String, /// Path to the daemon pidfile used for process coordination. - pub pidfile_path: String, + pub(crate) pidfile_path: String, /// Use a socket passed via systemd's socket activation protocol, instead of the path - pub systemd_socket: bool, + pub(crate) systemd_socket: bool, /// The port that should be used for TCP on non unix systems - pub tcp_port: u64, + tcp_port: u64, } #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Search { +struct Search { /// The list of enabled filter modes, in order of priority. - pub(crate) filters: Vec, + filters: Vec, /// The recency score multiplier for the search index (default: 1.0). /// Values < 1.0 reduce weight, > 1.0 increase weight, 0.0 disables. - pub(crate) recency_score_multiplier: f64, + recency_score_multiplier: f64, /// The frequency score multiplier for the search index (default: 1.0). /// Values < 1.0 reduce weight, > 1.0 increase weight, 0.0 disables. - pub(crate) frequency_score_multiplier: f64, + frequency_score_multiplier: f64, /// The overall frecency score multiplier for the search index (default: 1.0). /// Applied after combining recency and frequency scores. - pub(crate) frecency_score_multiplier: f64, + frecency_score_multiplier: f64, } /// Log level for file logging. Maps to tracing's [`LevelFilter`]. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] #[serde(rename_all = "lowercase")] -pub(crate) enum LogLevel { +enum LogLevel { Trace, Debug, #[default] @@ -437,7 +436,7 @@ pub(crate) enum LogLevel { impl LogLevel { /// Convert to a tracing directive string for use with [`EnvFilter`]. - pub(crate) fn as_directive(self) -> &'static str { + fn as_directive(self) -> &'static str { match self { Self::Trace => "trace", Self::Debug => "debug", @@ -450,45 +449,45 @@ impl LogLevel { /// Configuration for a specific log type (search or daemon). #[derive(Clone, Debug, Default, Deserialize, Serialize)] -pub(crate) struct LogConfig { +struct LogConfig { /// Log file name (relative to dir) or absolute path. - pub(crate) file: String, + file: String, /// Override global enabled setting for this log type. - pub(crate) enabled: Option, + enabled: Option, /// Override global level setting for this log type. - pub(crate) level: Option, + level: Option, /// Override global retention days setting for this log type. - pub(crate) retention: Option, + retention: Option, } #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Logs { +struct Logs { /// Enable file logging globally. Defaults to true. #[serde(default = "Logs::default_enabled")] - pub(crate) enabled: bool, + enabled: bool, /// Directory for log files. Defaults to ~/.atuin/logs - pub(crate) dir: String, + dir: String, /// Default log level for file logging. Defaults to "info". /// Note: [`ATUIN_LOG`] environment variable overrides this. #[serde(default)] - pub(crate) level: LogLevel, + level: LogLevel, /// Default retention days for log files. Defaults to 4. #[serde(default = "Logs::default_retention")] - pub(crate) retention: u64, + retention: u64, /// Search log settings #[serde(default)] - pub(crate) search: LogConfig, + search: LogConfig, /// Daemon log settings #[serde(default)] - pub(crate) daemon: LogConfig, + daemon: LogConfig, } impl Default for Preview { @@ -541,37 +540,37 @@ impl Logs { /// Returns whether search logging is enabled. /// Uses search-specific setting if set, otherwise falls back to global. - pub(crate) fn search_enabled(&self) -> bool { + fn search_enabled(&self) -> bool { self.search.enabled.unwrap_or(self.enabled) } /// Returns whether daemon logging is enabled. /// Uses daemon-specific setting if set, otherwise falls back to global. - pub(crate) fn daemon_enabled(&self) -> bool { + fn daemon_enabled(&self) -> bool { self.daemon.enabled.unwrap_or(self.enabled) } /// Returns the log level for search logging. /// Uses search-specific setting if set, otherwise falls back to global. - pub(crate) fn search_level(&self) -> LogLevel { + fn search_level(&self) -> LogLevel { self.search.level.unwrap_or(self.level) } /// Returns the log level for daemon logging. /// Uses daemon-specific setting if set, otherwise falls back to global. - pub(crate) fn daemon_level(&self) -> LogLevel { + fn daemon_level(&self) -> LogLevel { self.daemon.level.unwrap_or(self.level) } /// Returns the retention days for search logging. /// Uses search-specific setting if set, otherwise falls back to global. - pub(crate) fn search_retention(&self) -> u64 { + fn search_retention(&self) -> u64 { self.search.retention.unwrap_or(self.retention) } /// Returns the retention days for daemon logging. /// Uses daemon-specific setting if set, otherwise falls back to global. - pub(crate) fn daemon_retention(&self) -> u64 { + fn daemon_retention(&self) -> u64 { self.daemon.retention.unwrap_or(self.retention) } } @@ -597,7 +596,7 @@ impl Default for Search { // The preview height strategy also takes max_preview_height into account. #[derive(Clone, Debug, Deserialize, Copy, PartialEq, Eq, ValueEnum, Serialize)] -pub(crate) enum PreviewStrategy { +enum PreviewStrategy { // Preview height is calculated for the length of the selected command. #[serde(rename = "auto")] Auto, @@ -614,7 +613,7 @@ pub(crate) enum PreviewStrategy { /// Column types available for the interactive search UI. #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Serialize)] #[serde(rename_all = "lowercase")] -pub(crate) enum UiColumnType { +enum UiColumnType { /// Command execution duration (e.g., "123ms") Duration, /// Relative time since execution (e.g., "59s ago") @@ -636,7 +635,7 @@ pub(crate) enum UiColumnType { impl UiColumnType { /// Returns the default width for this column type (in characters). /// The Command column returns 0 as it expands to fill remaining space. - pub(crate) fn default_width(self) -> u16 { + fn default_width(self) -> u16 { match self { Self::Duration => 5, // "814ms" Self::Time => 9, // "459ms ago" @@ -659,15 +658,15 @@ impl UiColumnType { /// A column configuration with type and optional custom width. /// Can be specified as just a string (uses default width) or as an object with type and width. #[derive(Clone, Debug, Serialize)] -pub(crate) struct UiColumn { - pub(crate) column_type: UiColumnType, - pub(crate) width: u16, +struct UiColumn { + column_type: UiColumnType, + width: u16, /// If true, this column expands to fill remaining space. Only one column should expand. - pub(crate) expand: bool, + expand: bool, } impl UiColumn { - pub(crate) fn new(column_type: UiColumnType) -> Self { + fn new(column_type: UiColumnType) -> Self { Self { width: column_type.default_width(), expand: column_type == UiColumnType::Command, @@ -747,13 +746,13 @@ impl<'de> Deserialize<'de> for UiColumn { /// UI-specific settings for the interactive search. #[derive(Clone, Debug, Deserialize, Serialize)] -pub(crate) struct Ui { +struct Ui { /// Columns to display in interactive search, from left to right. /// The indicator column (" > ") is always shown first implicitly. /// The "command" column should be last as it expands to fill remaining space. /// Can be simple strings or objects with type and width. #[serde(default = "Ui::default_columns")] - pub(crate) columns: Vec, + columns: Vec, } impl Ui { @@ -767,7 +766,7 @@ impl Ui { /// Validate the UI configuration. /// Returns an error if more than one column has expand = true. - pub(crate) fn validate(&self) -> Result<()> { + fn validate(&self) -> Result<()> { let expand_count = self.columns.iter().filter(|c| c.expand).count(); if expand_count > 1 { bail!( @@ -794,13 +793,13 @@ pub(crate) struct Sync { pub(crate) address: String, #[serde(default)] - pub(crate) frequency: String, + frequency: String, #[serde(default)] pub(crate) auto: bool, #[serde(default)] - pub(crate) user_id_path: Option, + user_id_path: Option, #[serde(default)] pub(crate) encryption_key_path: Option, @@ -853,93 +852,93 @@ impl Sync { #[derive(Clone, Debug, Deserialize, Serialize)] #[expect(clippy::struct_excessive_bools)] -pub struct Settings { - pub(crate) data_dir: Option, - pub(crate) dialect: Dialect, - pub(crate) timezone: Timezone, - pub(crate) style: Style, - - pub db_path: String, - pub record_store_path: String, - pub(crate) search_mode: SearchMode, - pub(crate) filter_mode: Option, - pub(crate) filter_mode_shell_up_key_binding: Option, - pub(crate) search_mode_shell_up_key_binding: Option, - pub(crate) shell_up_key_binding: bool, - pub(crate) inline_height: u16, - pub(crate) inline_height_shell_up_key_binding: Option, - pub(crate) invert: bool, - pub(crate) show_preview: bool, - pub(crate) max_preview_height: u16, - pub(crate) show_help: bool, - pub(crate) show_tabs: bool, - pub(crate) show_numeric_shortcuts: bool, - pub(crate) auto_hide_height: u16, - pub(crate) exit_mode: ExitMode, - pub(crate) keymap_mode: KeymapMode, - pub(crate) keymap_mode_shell: KeymapMode, - pub(crate) keymap_cursor: HashMap, - pub(crate) word_jump_mode: WordJumpMode, - pub(crate) word_chars: String, - pub(crate) scroll_context_lines: usize, - pub(crate) history_format: String, - pub(crate) strip_trailing_whitespace: bool, - pub(crate) prefers_reduced_motion: bool, - pub(crate) store_failed: bool, - pub(crate) no_mouse: bool, +pub(crate) struct Settings { + data_dir: Option, + dialect: Dialect, + timezone: Timezone, + style: Style, + + pub(crate) db_path: String, + pub(crate) record_store_path: String, + search_mode: SearchMode, + filter_mode: Option, + filter_mode_shell_up_key_binding: Option, + search_mode_shell_up_key_binding: Option, + shell_up_key_binding: bool, + inline_height: u16, + inline_height_shell_up_key_binding: Option, + invert: bool, + show_preview: bool, + max_preview_height: u16, + show_help: bool, + show_tabs: bool, + show_numeric_shortcuts: bool, + auto_hide_height: u16, + exit_mode: ExitMode, + keymap_mode: KeymapMode, + keymap_mode_shell: KeymapMode, + keymap_cursor: HashMap, + word_jump_mode: WordJumpMode, + word_chars: String, + scroll_context_lines: usize, + history_format: String, + strip_trailing_whitespace: bool, + prefers_reduced_motion: bool, + store_failed: bool, + no_mouse: bool, #[serde(with = "serde_regex", default = "RegexSet::empty", skip_serializing)] - pub(crate) history_filter: RegexSet, + history_filter: RegexSet, #[serde(with = "serde_regex", default = "RegexSet::empty", skip_serializing)] - pub(crate) cwd_filter: RegexSet, + cwd_filter: RegexSet, - pub(crate) secrets_filter: bool, - pub(crate) workspaces: bool, - pub(crate) ctrl_n_shortcuts: bool, + secrets_filter: bool, + workspaces: bool, + ctrl_n_shortcuts: bool, pub(crate) network_connect_timeout: u64, pub(crate) network_timeout: u64, - pub local_timeout: f64, - pub(crate) enter_accept: bool, - pub(crate) smart_sort: bool, - pub(crate) command_chaining: bool, + pub(crate) local_timeout: f64, + enter_accept: bool, + smart_sort: bool, + command_chaining: bool, #[serde(default)] pub(crate) sync: Sync, #[serde(default)] - pub(crate) stats: Stats, + stats: Stats, #[serde(default)] - pub(crate) keys: Keys, + keys: Keys, #[serde(default)] - pub(crate) keymap: KeymapConfig, + keymap: KeymapConfig, #[serde(default)] - pub(crate) preview: Preview, + preview: Preview, #[serde(default)] - pub daemon: Daemon, + pub(crate) daemon: Daemon, #[serde(default)] - pub(crate) search: Search, + search: Search, #[serde(default)] - pub(crate) ui: Ui, + ui: Ui, #[serde(default)] - pub(crate) logs: Logs, + logs: Logs, #[serde(default)] - pub(crate) meta: meta::Settings, + meta: meta::Settings, } impl Settings { // -- Meta store: lazily initialized on first access -- - pub(crate) async fn meta_store() -> Result<&'static crate::aclient::meta::MetaStore> { + async fn meta_store() -> Result<&'static crate::aclient::meta::MetaStore> { META_STORE .get_or_try_init(|| async { let (db_path, timeout) = META_CONFIG.get().ok_or_else(|| { @@ -954,7 +953,7 @@ impl Settings { Self::meta_store().await?.host_id().await } - pub(crate) async fn last_sync() -> Result { + async fn last_sync() -> Result { Self::meta_store().await?.last_sync().await } @@ -962,7 +961,7 @@ impl Settings { Self::meta_store().await?.save_sync_time().await } - pub(crate) fn default_filter_mode(&self, git_root: bool) -> FilterMode { + fn default_filter_mode(&self, git_root: bool) -> FilterMode { self.filter_mode .filter(|x| self.search.filters.contains(x)) .or_else(|| { @@ -979,7 +978,7 @@ impl Settings { .unwrap_or(FilterMode::Global) } - pub(crate) fn builder() -> Result> { + fn builder() -> Result> { Self::builder_with_data_dir(&utils::data_dir()) } @@ -1230,7 +1229,7 @@ impl Settings { /// Returns the effective value after merging defaults, config file, and /// environment — without the side-effects of full `Settings` construction /// (meta store init, path expansion, etc.). - pub(crate) fn get_config_value(key: &str) -> Result { + fn get_config_value(key: &str) -> Result { let config = Self::build_config()?; let value: config::Value = config .get(key) @@ -1289,7 +1288,7 @@ impl Settings { } } - pub fn new() -> Result { + pub(crate) fn new() -> Result { let config = Self::build_config()?; let settings: Self = config .try_deserialize() @@ -1312,7 +1311,7 @@ impl Settings { .map_err(|e| eyre!("failed to expand path: {}", e)) } - pub(crate) fn paths_ok(&self) -> bool { + fn paths_ok(&self) -> bool { // TODO(@bpeetz): Add the `sync.*` paths <2026-06-11> let paths = [&self.db_path, &self.record_store_path, &self.meta.db_path]; paths.iter().all(|p| !utils::broken_symlink(p)) diff --git a/crates/daemon/src/aclient/settings/watcher.rs b/crates/daemon/src/aclient/settings/watcher.rs deleted file mode 100644 index 01d20855..00000000 --- a/crates/daemon/src/aclient/settings/watcher.rs +++ /dev/null @@ -1,260 +0,0 @@ -//! Config file watching for automatic settings reload. -//! -//! This module provides a `SettingsWatcher` that monitors the config file -//! for changes and broadcasts updated settings via a `tokio::sync::watch` channel. -//! -//! # Example -//! -//! ```no_run -//! use crate::aclient::settings::watcher::global_settings_watcher; -//! -//! async fn example() -> eyre::Result<()> { -//! let watcher = global_settings_watcher()?; -//! let mut rx = watcher.subscribe(); -//! -//! // React to settings changes -//! while rx.changed().await.is_ok() { -//! let settings = rx.borrow(); -//! println!("Settings updated!"); -//! } -//! Ok(()) -//! } -//! ``` - -use std::{ - path::{Path, PathBuf}, - sync::{Arc, OnceLock}, - time::Duration, -}; - -use eyre::{Result, WrapErr}; -use log::{debug, error, info, warn}; -use notify::{ - Config as NotifyConfig, RecommendedWatcher, RecursiveMode, Watcher, - event::{EventKind, ModifyKind}, -}; -use tokio::sync::watch; - -use super::Settings; - -/// Global singleton for the settings watcher. -static SETTINGS_WATCHER: OnceLock> = OnceLock::new(); - -/// Get the global settings watcher singleton. -/// -/// Initializes the watcher on first call. Subsequent calls return the same instance. -/// The watcher monitors the config file for changes and broadcasts updates. -pub(crate) fn global_settings_watcher() -> Result<&'static SettingsWatcher> { - let result = SETTINGS_WATCHER.get_or_init(|| SettingsWatcher::new().map_err(|e| e.to_string())); - - match result { - Ok(watcher) => Ok(watcher), - Err(e) => Err(eyre::eyre!("{}", e)), - } -} - -/// Watches the config file for changes and broadcasts updated settings. -/// -/// Uses `notify` for cross-platform file watching and `tokio::sync::watch` -/// for efficient broadcast to multiple subscribers. -pub(crate) struct SettingsWatcher { - /// Receiver for settings updates. Clone this to subscribe. - rx: watch::Receiver>, - /// Keeps the file watcher alive for the lifetime of this struct. - _watcher: RecommendedWatcher, -} - -impl SettingsWatcher { - /// Create a new settings watcher. - /// - /// Loads initial settings and starts watching the config file for changes. - /// Changes are debounced (500ms) to avoid multiple reloads during saves. - pub(crate) fn new() -> Result { - let initial_settings = Arc::new(Settings::new()?); - let (tx, rx) = watch::channel(initial_settings); - - let config_path = Self::config_path(); - info!("starting config file watcher: {}", config_path.display()); - - let watcher = Self::create_watcher(tx, &config_path)?; - - Ok(Self { - rx, - _watcher: watcher, - }) - } - - /// Subscribe to settings updates. - /// - /// Returns a receiver that will be notified when settings change. - /// Use `changed().await` to wait for the next update, then `borrow()` - /// to access the current settings. - pub(crate) fn subscribe(&self) -> watch::Receiver> { - self.rx.clone() - } - - /// Get the config file path. - fn config_path() -> PathBuf { - let config_dir = std::env::var("ATUIN_CONFIG_DIR") - .map_or_else(|_| turtle_common::utils::config_dir(), PathBuf::from); - config_dir.join("config.toml") - } - - /// Create the file watcher with debouncing. - fn create_watcher( - tx: watch::Sender>, - config_path: &Path, - ) -> Result { - // Channel for debouncing file events - let (debounce_tx, debounce_rx) = std::sync::mpsc::channel::<()>(); - - // Spawn debounce thread - let config_path_clone = config_path.to_owned(); - std::thread::spawn(move || { - Self::debounce_loop(&debounce_rx, &tx, &config_path_clone); - }); - - // Clone config_path for use in the watcher callback - let config_path_for_watcher = config_path.to_owned(); - - // Canonicalize config path for reliable comparison on macOS - // (handles symlinks like /var -> /private/var) - let canonical_config_path = config_path_for_watcher - .canonicalize() - .unwrap_or_else(|_| config_path_for_watcher.clone()); - - // Create file watcher - let mut watcher = RecommendedWatcher::new( - move |res: Result| { - match res { - Ok(event) => { - // Defensive: if paths is empty, we can't filter, so assume - // it might be our config file and trigger a reload to be safe - if event.paths.is_empty() { - warn!( - "config watcher: event has no paths, triggering reload to be safe" - ); - debounce_tx.send(()).expect("should still be active"); - return; - } - - // Only react to events for our specific config file - // (filter out editor temp files, backups, etc.) - let is_config_file = event.paths.iter().any(|path| { - // Canonicalize for reliable comparison (handles macOS symlinks) - let canonical_event_path = - path.canonicalize().unwrap_or_else(|_| path.clone()); - - // Check if this event is for our config file - // (either exact match or the file was renamed to our config) - canonical_event_path == canonical_config_path - || path.file_name() == config_path_for_watcher.file_name() - }); - - if !is_config_file { - return; - } - - // Only react to modify events (content changes) or creates - if matches!( - event.kind, - EventKind::Modify(ModifyKind::Data(_) | ModifyKind::Any) - | EventKind::Create(_) - ) { - debug!("config file event detected: {event:?}"); - // Send to debounce channel (ignore send errors - receiver might be gone) - debounce_tx.send(()).ok(); - } - } - Err(e) => { - error!("file watcher error: {e}"); - } - } - }, - NotifyConfig::default(), - ) - .wrap_err("failed to create file watcher")?; - - // Watch the config file's parent directory (some editors create new files) - let watch_path = config_path.parent().unwrap_or(config_path); - - // Defensive: ensure watch path exists before trying to watch - if !watch_path.exists() { - warn!( - "config directory does not exist, creating it: {}", - watch_path.display() - ); - std::fs::create_dir_all(watch_path).wrap_err_with(|| { - format!( - "failed to create config directory: {}", - watch_path.display() - ) - })?; - } - - watcher - .watch(watch_path, RecursiveMode::NonRecursive) - .wrap_err_with(|| { - format!("failed to watch config directory: {}", watch_path.display()) - })?; - - info!( - "config file watcher initialized for: {}", - watch_path.display() - ); - Ok(watcher) - } - - /// Debounce loop that batches file events and reloads settings. - fn debounce_loop( - rx: &std::sync::mpsc::Receiver<()>, - tx: &watch::Sender>, - config_path: &Path, - ) { - const DEBOUNCE_DURATION: Duration = Duration::from_millis(500); - - loop { - // Wait for first event - if rx.recv().is_err() { - // Channel closed, watcher was dropped - debug!("config watcher debounce loop exiting"); - return; - } - - // Drain any additional events within debounce window - while rx.recv_timeout(DEBOUNCE_DURATION).is_ok() { - // Keep draining - } - - // Defensive: check if config file exists before reloading - // (handles case where file was deleted - we'll get notified when it's recreated) - if !config_path.exists() { - debug!( - "config file does not exist, skipping reload: {}", - config_path.display() - ); - continue; - } - - // Now reload settings - info!( - "config file changed, reloading settings: {}", - config_path.display() - ); - match Settings::new() { - Ok(settings) => { - if tx.send(Arc::new(settings)).is_err() { - // All receivers dropped - debug!("all settings subscribers dropped, exiting"); - return; - } - info!("settings reloaded successfully"); - } - Err(e) => { - warn!("failed to reload settings: {e}"); - // Keep the old settings, don't broadcast the error - } - } - } - } -} -- cgit v1.3.1