etcetera/base_strategy.rs
1//! These strategies simply provide the user’s configuration, data, and cache directories, without knowing about the application specifically.
2
3use crate::HomeDirError;
4use std::path::{Path, PathBuf};
5
6/// Provides configuration, data, and cache directories of the current user.
7pub trait BaseStrategy {
8 /// Gets the home directory of the current user.
9 fn home_dir(&self) -> &Path;
10
11 /// Gets the user’s configuration directory.
12 fn config_dir(&self) -> PathBuf;
13
14 /// Gets the user’s data directory.
15 fn data_dir(&self) -> PathBuf;
16
17 /// Gets the user’s cache directory.
18 fn cache_dir(&self) -> PathBuf;
19
20 /// Gets the user’s state directory.
21 /// Currently, only the [`Xdg`](struct.Xdg.html) strategy supports this.
22 fn state_dir(&self) -> Option<PathBuf>;
23
24 /// Gets the user’s runtime directory.
25 /// Currently, only the [`Xdg`](struct.Xdg.html) strategy supports this.
26 ///
27 /// Note: The [XDG Base Directory Specification](spec) places additional requirements on this
28 /// directory related to ownership, permissions, and persistence. This library does not check
29 /// these requirements.
30 ///
31 /// [spec]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
32 fn runtime_dir(&self) -> Option<PathBuf>;
33}
34
35macro_rules! create_strategies {
36 ($native: ty, $base: ty) => {
37 /// Returns the current OS’s native [`BaseStrategy`](trait.BaseStrategy.html).
38 /// This uses the [`Windows`](struct.Windows.html) strategy on Windows, [`Apple`](struct.Apple.html) on macOS & iOS, and [`Xdg`](struct.Xdg.html) everywhere else.
39 /// This is the convention used by most GUI applications.
40 pub fn choose_native_strategy() -> Result<$native, HomeDirError> {
41 <$native>::new()
42 }
43
44 /// Returns the current OS’s default [`BaseStrategy`](trait.BaseStrategy.html).
45 /// This uses the [`Windows`](struct.Windows.html) strategy on Windows, and [`Xdg`](struct.Xdg.html) everywhere else.
46 /// This is the convention used by most CLI applications.
47 pub fn choose_base_strategy() -> Result<$base, HomeDirError> {
48 <$base>::new()
49 }
50 };
51}
52
53cfg_if::cfg_if! {
54 if #[cfg(target_os = "windows")] {
55 create_strategies!(Windows, Windows);
56 } else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
57 create_strategies!(Apple, Xdg);
58 } else {
59 create_strategies!(Xdg, Xdg);
60 }
61}
62
63mod apple;
64mod windows;
65mod xdg;
66
67pub use apple::Apple;
68pub use windows::Windows;
69pub use xdg::Xdg;