etcetera/
app_strategy.rs

1//! These strategies require you to provide some information on your application, and they will in turn locate the configuration/data/cache directory specifically for your application.
2
3use std::ffi::OsStr;
4use std::path::Path;
5use std::path::PathBuf;
6
7use crate::HomeDirError;
8
9/// The arguments to the creator method of an [`AppStrategy`](trait.AppStrategy.html).
10#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
11pub struct AppStrategyArgs {
12    /// The top level domain of the application, e.g. `com`, `org`, or `io.github`.
13    pub top_level_domain: String,
14    /// The name of the author of the application.
15    pub author: String,
16    /// The application’s name. This should be capitalised if appropriate.
17    pub app_name: String,
18}
19
20impl AppStrategyArgs {
21    /// Constructs a bunde identifier from an `AppStrategyArgs`.
22    ///
23    /// ```
24    /// use etcetera::app_strategy::AppStrategyArgs;
25    ///
26    /// let strategy_args = AppStrategyArgs {
27    ///     top_level_domain: "org".to_string(),
28    ///     author: "Acme Corp".to_string(),
29    ///     app_name: "Frobnicator Plus".to_string(),
30    /// };
31    ///
32    /// assert_eq!(strategy_args.bundle_id(), "org.acme-corp.Frobnicator-Plus".to_string());
33    /// ```
34    pub fn bundle_id(&self) -> String {
35        let author = self.author.to_lowercase().replace(' ', "-");
36        let app_name = self.app_name.replace(' ', "-");
37        let mut parts = vec![
38            self.top_level_domain.as_str(),
39            author.as_str(),
40            app_name.as_str(),
41        ];
42        parts.retain(|part| !part.is_empty());
43        parts.join(".")
44    }
45
46    /// Returns a ‘unixy’ version of the application’s name, akin to what would usually be used as a binary name.
47    ///
48    /// ```
49    /// use etcetera::app_strategy::AppStrategyArgs;
50    ///
51    /// let strategy_args = AppStrategyArgs {
52    ///     top_level_domain: "org".to_string(),
53    ///     author: "Acme Corp".to_string(),
54    ///     app_name: "Frobnicator Plus".to_string(),
55    /// };
56    ///
57    /// assert_eq!(strategy_args.unixy_name(), "frobnicator-plus".to_string());
58    /// ```
59    pub fn unixy_name(&self) -> String {
60        self.app_name.to_lowercase().replace(' ', "-")
61    }
62}
63
64macro_rules! in_dir_method {
65    ($self: ident, $path_extra: expr, $dir_method_name: ident) => {{
66        let mut path = $self.$dir_method_name();
67        path.push(Path::new(&$path_extra));
68        path
69    }};
70    (opt: $self: ident, $path_extra: expr, $dir_method_name: ident) => {{
71        let mut path = $self.$dir_method_name()?;
72        path.push(Path::new(&$path_extra));
73        Some(path)
74    }};
75}
76
77/// Allows applications to retrieve the paths of configuration, data, and cache directories specifically for them.
78pub trait AppStrategy {
79    /// Gets the home directory of the current user.
80    fn home_dir(&self) -> &Path;
81
82    /// Gets the configuration directory for your application.
83    fn config_dir(&self) -> PathBuf;
84
85    /// Gets the data directory for your application.
86    fn data_dir(&self) -> PathBuf;
87
88    /// Gets the cache directory for your application.
89    fn cache_dir(&self) -> PathBuf;
90
91    /// Gets the state directory for your application.
92    /// Currently, only the [`Xdg`](struct.Xdg.html) & [`Unix`](struct.Unix.html) strategies support
93    /// this.
94    fn state_dir(&self) -> Option<PathBuf>;
95
96    /// Gets the runtime directory for your application.
97    /// Currently, only the [`Xdg`](struct.Xdg.html) & [`Unix`](struct.Unix.html) strategies support
98    /// this.
99    ///
100    /// Note: The [XDG Base Directory Specification](spec) places additional requirements on this
101    /// directory related to ownership, permissions, and persistence. This library does not check
102    /// these requirements.
103    ///
104    /// [spec]: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
105    fn runtime_dir(&self) -> Option<PathBuf>;
106
107    /// Constructs a path inside your application’s configuration directory to which a path of your choice has been appended.
108    fn in_config_dir<P: AsRef<OsStr>>(&self, path: P) -> PathBuf {
109        in_dir_method!(self, path, config_dir)
110    }
111
112    /// Constructs a path inside your application’s data directory to which a path of your choice has been appended.
113    fn in_data_dir<P: AsRef<OsStr>>(&self, path: P) -> PathBuf {
114        in_dir_method!(self, path, data_dir)
115    }
116
117    /// Constructs a path inside your application’s cache directory to which a path of your choice has been appended.
118    fn in_cache_dir<P: AsRef<OsStr>>(&self, path: P) -> PathBuf {
119        in_dir_method!(self, path, cache_dir)
120    }
121
122    /// Constructs a path inside your application’s state directory to which a path of your choice has been appended.
123    ///
124    /// Currently, this is only implemented for the [`Xdg`](struct.Xdg.html) strategy.
125    fn in_state_dir<P: AsRef<OsStr>>(&self, path: P) -> Option<PathBuf> {
126        in_dir_method!(opt: self, path, state_dir)
127    }
128
129    /// Constructs a path inside your application’s runtime directory to which a path of your choice has been appended.
130    /// Currently, only the [`Xdg`](struct.Xdg.html) & [`Unix`](struct.Unix.html) strategies support
131    /// this.
132    ///
133    /// See the note in [`runtime_dir`](#method.runtime_dir) for more information.
134    fn in_runtime_dir<P: AsRef<OsStr>>(&self, path: P) -> Option<PathBuf> {
135        in_dir_method!(opt: self, path, runtime_dir)
136    }
137}
138
139macro_rules! create_strategies {
140    ($native: ty, $app: ty) => {
141        /// Returns the current OS’s native [`AppStrategy`](trait.AppStrategy.html).
142        /// This uses the [`Windows`](struct.Windows.html) strategy on Windows, [`Apple`](struct.Apple.html) on macOS & iOS, and [`Xdg`](struct.Xdg.html) everywhere else.
143        /// This is the convention used by most GUI applications.
144        pub fn choose_native_strategy(args: AppStrategyArgs) -> Result<$native, HomeDirError> {
145            <$native>::new(args)
146        }
147
148        /// Returns the current OS’s default [`AppStrategy`](trait.AppStrategy.html).
149        /// This uses the [`Windows`](struct.Windows.html) strategy on Windows, and [`Xdg`](struct.Xdg.html) everywhere else.
150        /// This is the convention used by most CLI applications.
151        pub fn choose_app_strategy(args: AppStrategyArgs) -> Result<$app, HomeDirError> {
152            <$app>::new(args)
153        }
154    };
155}
156
157cfg_if::cfg_if! {
158    if #[cfg(target_os = "windows")] {
159        create_strategies!(Windows, Windows);
160    } else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
161        create_strategies!(Apple, Xdg);
162    } else {
163        create_strategies!(Xdg, Xdg);
164    }
165}
166
167mod apple;
168mod unix;
169mod windows;
170mod xdg;
171
172pub use apple::Apple;
173pub use unix::Unix;
174pub use windows::Windows;
175pub use xdg::Xdg;