|
| 1 | +//! Platform user directories. |
| 2 | +//! |
| 3 | +//! Exposes the operating system's per-user directory roots. Application- |
| 4 | +//! agnostic: it knows nothing of Harmont's own `hm/` subdirectory — callers |
| 5 | +//! join that (and any file name) onto these roots. |
| 6 | +//! |
| 7 | +//! On non-Windows the roots are `~/.config` and `~/.cache`; the `$XDG_*` env |
| 8 | +//! vars are intentionally not honored, keeping paths predictable. |
| 9 | +
|
| 10 | +use std::path::{Path, PathBuf}; |
| 11 | + |
| 12 | +/// The platform per-user directory roots, resolved once at construction and |
| 13 | +/// read as borrowed paths. |
| 14 | +/// |
| 15 | +/// Build with [`DirProvider::new`], then read the `&Path` accessors. Attach a |
| 16 | +/// process-wide instance to the system runtime and reach it via its `dirs()` |
| 17 | +/// accessor instead of reconstructing one per call. |
| 18 | +#[derive(Debug, Clone)] |
| 19 | +pub struct DirProvider { |
| 20 | + config: PathBuf, |
| 21 | + cache: PathBuf, |
| 22 | +} |
| 23 | + |
| 24 | +impl DirProvider { |
| 25 | + /// Resolve the platform directory roots, once. |
| 26 | + /// |
| 27 | + /// Returns `None` if a root cannot be determined — e.g. there is no home |
| 28 | + /// directory. |
| 29 | + #[must_use] |
| 30 | + pub fn new() -> Option<Self> { |
| 31 | + #[cfg(windows)] |
| 32 | + let (config, cache) = (dirs::config_dir()?, dirs::cache_dir()?); |
| 33 | + #[cfg(not(windows))] |
| 34 | + let (config, cache) = { |
| 35 | + let home = dirs::home_dir()?; |
| 36 | + (home.join(".config"), home.join(".cache")) |
| 37 | + }; |
| 38 | + |
| 39 | + Some(Self { config, cache }) |
| 40 | + } |
| 41 | + |
| 42 | + /// The user configuration root (`~/.config` on non-Windows). |
| 43 | + #[must_use] |
| 44 | + pub fn config(&self) -> &Path { |
| 45 | + &self.config |
| 46 | + } |
| 47 | + |
| 48 | + /// The user cache root (`~/.cache` on non-Windows). |
| 49 | + #[must_use] |
| 50 | + pub fn cache(&self) -> &Path { |
| 51 | + &self.cache |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +#[cfg(test)] |
| 56 | +#[allow(clippy::unwrap_used, reason = "test setup and assertions")] |
| 57 | +mod tests { |
| 58 | + use super::*; |
| 59 | + use rstest::rstest; |
| 60 | + |
| 61 | + #[rstest] |
| 62 | + fn config_is_the_platform_config_root() { |
| 63 | + let dirs = DirProvider::new().unwrap(); |
| 64 | + assert!(dirs.config().is_absolute(), "got {:?}", dirs.config()); |
| 65 | + #[cfg(not(windows))] |
| 66 | + assert!(dirs.config().ends_with(".config"), "got {:?}", dirs.config()); |
| 67 | + } |
| 68 | + |
| 69 | + #[rstest] |
| 70 | + fn cache_is_the_platform_cache_root() { |
| 71 | + let dirs = DirProvider::new().unwrap(); |
| 72 | + assert!(dirs.cache().is_absolute(), "got {:?}", dirs.cache()); |
| 73 | + #[cfg(not(windows))] |
| 74 | + assert!(dirs.cache().ends_with(".cache"), "got {:?}", dirs.cache()); |
| 75 | + } |
| 76 | +} |
0 commit comments