Skip to main content

waratah/
config_dir.rs

1//! Config directory resolution for the waratah CLI (XDG conventions).
2//!
3//! Configuration that outlives a single command invocation — the cluster
4//! address table, the notebook service, a future licence file — lives as
5//! named files in a config *directory*, decoupled from `--data-dir` (which
6//! holds state, not configuration). Lookups walk candidates in priority
7//! order and take the first file that exists:
8//!
9//! 1. `--config-dir PATH` when given (exactly that directory, no fallback);
10//! 2. the platform **user** config dir + `waratah`:
11//!    Linux `${XDG_CONFIG_HOME:-~/.config}/waratah`,
12//!    macOS `~/Library/Application Support/waratah`,
13//!    Windows `%APPDATA%\waratah` (RoamingAppData, per the `dirs` crate
14//!    convention);
15//! 3. the platform **system** config dir + `waratah`:
16//!    Linux `/etc/waratah`,
17//!    macOS `/Library/Application Support/waratah`,
18//!    Windows `%PROGRAMDATA%\waratah` (`C:\ProgramData\waratah`).
19//!
20//! File names are fixed per consumer (`cluster.toml`, `notebooks.toml`);
21//! [`find`] is generic so later consumers (licence file, …) reuse it.
22
23use std::path::{Path, PathBuf};
24
25/// Config file names owned by current consumers.
26pub(crate) mod files {
27    /// Five-process address table (`waratah_router::ClusterConfig`).
28    pub(crate) const CLUSTER: &str = "cluster.toml";
29    /// Notebook service options (`waratah_notebook::NotebooksToml`).
30    pub(crate) const NOTEBOOKS: &str = "notebooks.toml";
31    /// AI services options (`waratah_api::AiToml`).
32    pub(crate) const AI: &str = "ai.toml";
33    /// Text plugin options (`waratah_text::TextPluginConfig`).
34    pub(crate) const TEXT: &str = "text.toml";
35}
36
37/// Directories to search for a config file, highest priority first.
38pub(crate) fn candidate_dirs(explicit: Option<&Path>) -> Vec<PathBuf> {
39    if let Some(dir) = explicit {
40        return vec![dir.to_path_buf()];
41    }
42    // Env vars are read once here; the platform branches are pure so tests
43    // can inject values (std::env::set_var is unsafe and racy in 2024
44    // edition test runs).
45    user_config_dir_from(
46        platform(),
47        &std::env::var("XDG_CONFIG_HOME").ok(),
48        &std::env::var("HOME").ok(),
49        &std::env::var("APPDATA").ok(),
50    )
51    .into_iter()
52    .chain(system_config_dir())
53    .collect()
54}
55
56/// First existing `file_name` in the config search path, if any.
57pub(crate) fn find(explicit: Option<&Path>, file_name: &str) -> Option<PathBuf> {
58    candidate_dirs(explicit)
59        .into_iter()
60        .map(|dir| dir.join(file_name))
61        .find(|path| path.is_file())
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65enum Platform {
66    Linux,
67    MacOs,
68    Windows,
69}
70
71fn platform() -> Platform {
72    if cfg!(target_os = "macos") {
73        Platform::MacOs
74    } else if cfg!(windows) {
75        Platform::Windows
76    } else {
77        Platform::Linux
78    }
79}
80
81fn system_config_dir() -> Option<PathBuf> {
82    system_config_dir_from(platform(), &std::env::var("PROGRAMDATA").ok())
83}
84
85/// Pure core of [`user_config_dir`]: `None` inputs model unset env vars.
86fn user_config_dir_from(
87    platform: Platform,
88    xdg_config_home: &Option<String>,
89    home: &Option<String>,
90    appdata: &Option<String>,
91) -> Option<PathBuf> {
92    let dir = match platform {
93        Platform::Linux => xdg_config_home
94            .clone()
95            .map(PathBuf::from)
96            .or_else(|| home.clone().map(|home| Path::new(&home).join(".config")))?,
97        // macOS conventions: per-user application support.
98        Platform::MacOs => PathBuf::from(home.clone()?).join("Library/Application Support"),
99        // Windows conventions: per-user roaming application data.
100        Platform::Windows => PathBuf::from(appdata.clone()?),
101    };
102    Some(dir.join("waratah"))
103}
104
105/// Pure core of [`system_config_dir`].
106fn system_config_dir_from(platform: Platform, program_data: &Option<String>) -> Option<PathBuf> {
107    let dir = match platform {
108        // XDG has no system config dir; /etc is the convention this
109        // deployment targets (the machine-wide fallback).
110        Platform::Linux => PathBuf::from("/etc"),
111        Platform::MacOs => PathBuf::from("/Library/Application Support"),
112        Platform::Windows => PathBuf::from(
113            program_data
114                .clone()
115                .unwrap_or_else(|| "C:\\ProgramData".to_owned()),
116        ),
117    };
118    Some(dir.join("waratah"))
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    fn some(value: &str) -> Option<String> {
126        Some(value.to_owned())
127    }
128
129    #[test]
130    fn explicit_config_dir_is_the_only_candidate() {
131        let dirs = candidate_dirs(Some(Path::new("/opt/waratah-conf")));
132        assert_eq!(dirs, vec![PathBuf::from("/opt/waratah-conf")]);
133    }
134
135    #[test]
136    fn linux_user_dir_honors_xdg_then_home() {
137        assert_eq!(
138            user_config_dir_from(Platform::Linux, &some("/xdg"), &some("/home/u"), &None),
139            Some(PathBuf::from("/xdg/waratah"))
140        );
141        assert_eq!(
142            user_config_dir_from(Platform::Linux, &None, &some("/home/u"), &None),
143            Some(PathBuf::from("/home/u/.config/waratah"))
144        );
145        // No XDG and no HOME: nothing sensible to use.
146        assert_eq!(
147            user_config_dir_from(Platform::Linux, &None, &None, &None),
148            None
149        );
150    }
151
152    /// Cross-platform assertion helper: `Path::join` always uses the
153    /// RUNNING platform's separator, so Windows prefixes built on a Linux
154    /// test host come out with mixed separators. Compare with separators
155    /// normalized instead — the directory prefix is what the code controls.
156    fn assert_dir(platform_dir: Option<PathBuf>, expected_prefix: &str) {
157        let rendered = platform_dir
158            .map(|dir| dir.to_string_lossy().replace('\\', "/"))
159            .unwrap_or_default();
160        assert_eq!(rendered, format!("{expected_prefix}/waratah"));
161    }
162
163    #[test]
164    fn macos_and_windows_user_dirs_follow_platform_conventions() {
165        assert_dir(
166            user_config_dir_from(Platform::MacOs, &None, &some("/Users/u"), &None),
167            "/Users/u/Library/Application Support",
168        );
169        assert_dir(
170            user_config_dir_from(
171                Platform::Windows,
172                &None,
173                &None,
174                &some("C:\\Users\\u\\AppData\\Roaming"),
175            ),
176            "C:/Users/u/AppData/Roaming",
177        );
178    }
179
180    #[test]
181    fn system_dirs_are_machine_wide() {
182        assert_eq!(
183            system_config_dir_from(Platform::Linux, &None),
184            Some(PathBuf::from("/etc/waratah"))
185        );
186        assert_dir(
187            system_config_dir_from(Platform::MacOs, &None),
188            "/Library/Application Support",
189        );
190        // Windows falls back to the well-known ProgramData path.
191        assert_dir(
192            system_config_dir_from(Platform::Windows, &None),
193            "C:/ProgramData",
194        );
195        assert_dir(
196            system_config_dir_from(Platform::Windows, &some("D:\\ProgramData")),
197            "D:/ProgramData",
198        );
199    }
200
201    #[test]
202    fn find_prefers_user_dir_over_system_dir() {
203        let user = tempfile::tempdir().unwrap();
204        let system = tempfile::tempdir().unwrap();
205        std::fs::write(user.path().join("notebooks.toml"), "enabled = true").unwrap();
206
207        // Simulate the search by hand: user first, system second.
208        let found = [user.path(), system.path()]
209            .into_iter()
210            .map(|dir| dir.join(files::NOTEBOOKS))
211            .find(|path| path.is_file())
212            .unwrap();
213        assert_eq!(found, user.path().join("notebooks.toml"));
214
215        // Only the system copy present: still found.
216        std::fs::remove_file(user.path().join("notebooks.toml")).unwrap();
217        std::fs::write(system.path().join("notebooks.toml"), "enabled = true").unwrap();
218        let found = [user.path(), system.path()]
219            .into_iter()
220            .map(|dir| dir.join(files::NOTEBOOKS))
221            .find(|path| path.is_file())
222            .unwrap();
223        assert_eq!(found, system.path().join("notebooks.toml"));
224    }
225
226    #[test]
227    fn find_returns_none_when_no_candidate_exists() {
228        let nowhere = tempfile::tempdir().unwrap();
229        assert_eq!(find(Some(nowhere.path()), files::CLUSTER), None);
230    }
231}