directories_next/lib.rs
1//! The _directories_ crate is
2//!
3//! - a tiny library with a minimal API (3 structs, 4 factory functions, getters)
4//! - that provides the platform-specific, user-accessible locations
5//! - for finding and storing configuration, cache and other data
6//! - on Linux, Redox, Windows (≥ Vista) and macOS.
7//!
8//! The library provides the location of these directories by leveraging the mechanisms defined by
9//!
10//! - the [XDG base directory](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) and the [XDG user directory](https://www.freedesktop.org/wiki/Software/xdg-user-dirs/) specifications on Linux,
11//! - the [Known Folder](https://msdn.microsoft.com/en-us/library/windows/desktop/bb776911(v=vs.85).aspx) system on Windows, and
12//! - the [Standard Directories](https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW6) on macOS.
13//!
14
15#![deny(missing_docs)]
16#![warn(rust_2018_idioms)]
17
18use cfg_if::cfg_if;
19
20use std::path::Path;
21use std::path::PathBuf;
22
23cfg_if! {
24 if #[cfg(target_os = "windows")] {
25 mod win;
26 use win as sys;
27 } else if #[cfg(any(target_os = "macos", target_os = "ios"))] {
28 mod mac;
29 use mac as sys;
30 } else if #[cfg(target_arch = "wasm32")] {
31 mod wasm;
32 use wasm as sys;
33 } else {
34 mod lin;
35 use crate::lin as sys;
36 }
37}
38
39/// `BaseDirs` provides paths of user-invisible standard directories, following the conventions of the operating system the library is running on.
40///
41/// To compute the location of cache, config or data directories for individual projects or applications, use `ProjectDirs` instead.
42///
43/// # Examples
44///
45/// All examples on this page are computed with a user named _Alice_.
46///
47/// ```
48/// use directories_next::BaseDirs;
49/// if let Some(base_dirs) = BaseDirs::new() {
50/// base_dirs.config_dir();
51/// // Linux: /home/alice/.config
52/// // Windows: C:\Users\Alice\AppData\Roaming
53/// // macOS: /Users/Alice/Library/Application Support
54/// }
55/// ```
56#[derive(Debug, Clone)]
57pub struct BaseDirs {
58 // home directory
59 home_dir: PathBuf,
60
61 // base directories
62 cache_dir: PathBuf,
63 config_dir: PathBuf,
64 data_dir: PathBuf,
65 data_local_dir: PathBuf,
66 executable_dir: Option<PathBuf>,
67 runtime_dir: Option<PathBuf>,
68}
69
70/// `UserDirs` provides paths of user-facing standard directories, following the conventions of the operating system the library is running on.
71///
72/// # Examples
73///
74/// All examples on this page are computed with a user named _Alice_.
75///
76/// ```
77/// use directories_next::UserDirs;
78/// if let Some(user_dirs) = UserDirs::new() {
79/// user_dirs.audio_dir();
80/// // Linux: /home/alice/Music
81/// // Windows: C:\Users\Alice\Music
82/// // macOS: /Users/Alice/Music
83/// }
84/// ```
85#[derive(Debug, Clone)]
86pub struct UserDirs {
87 // home directory
88 home_dir: PathBuf,
89
90 // user directories
91 audio_dir: Option<PathBuf>,
92 desktop_dir: Option<PathBuf>,
93 document_dir: Option<PathBuf>,
94 download_dir: Option<PathBuf>,
95 font_dir: Option<PathBuf>,
96 picture_dir: Option<PathBuf>,
97 public_dir: Option<PathBuf>,
98 template_dir: Option<PathBuf>,
99 // trash_dir: PathBuf,
100 video_dir: Option<PathBuf>,
101}
102
103/// `ProjectDirs` computes the location of cache, config or data directories for a specific application,
104/// which are derived from the standard directories and the name of the project/organization.
105///
106/// # Examples
107///
108/// All examples on this page are computed with a user named _Alice_,
109/// and a `ProjectDirs` struct created with `ProjectDirs::from("com", "Foo Corp", "Bar App")`.
110///
111/// ```
112/// use directories_next::ProjectDirs;
113/// if let Some(proj_dirs) = ProjectDirs::from("com", "Foo Corp", "Bar App") {
114/// proj_dirs.config_dir();
115/// // Linux: /home/alice/.config/barapp
116/// // Windows: C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App
117/// // macOS: /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App
118/// }
119/// ```
120#[derive(Debug, Clone)]
121pub struct ProjectDirs {
122 project_path: PathBuf,
123
124 // base directories
125 cache_dir: PathBuf,
126 config_dir: PathBuf,
127 data_dir: PathBuf,
128 data_local_dir: PathBuf,
129 runtime_dir: Option<PathBuf>,
130}
131
132impl BaseDirs {
133 /// Creates a `BaseDirs` struct which holds the paths to user-invisible directories for cache, config, etc. data on the system.
134 ///
135 /// The returned value depends on the operating system and is either
136 /// - `Some`, containing a snapshot of the state of the system's paths at the time `new()` was invoked, or
137 /// - `None`, if no valid home directory path could be retrieved from the operating system.
138 ///
139 /// To determine whether a system provides a valid `$HOME` path, the following rules are applied:
140 ///
141 /// ### Linux and macOS:
142 ///
143 /// - Use `$HOME` if it is set and not empty.
144 /// - If `$HOME` is not set or empty, then the function `getpwuid_r` is used to determine
145 /// the home directory of the current user.
146 /// - If `getpwuid_r` lacks an entry for the current user id or the home directory field is empty,
147 /// then the function returns `None`.
148 ///
149 /// ### Windows:
150 ///
151 /// - Retrieve the user profile folder using `SHGetKnownFolderPath`.
152 /// - If this fails, then the function returns `None`.
153 ///
154 /// _Note:_ This logic differs from [`std::env::home_dir`],
155 /// which works incorrectly on Linux, macOS and Windows.
156 ///
157 /// [`std::env::home_dir`]: https://doc.rust-lang.org/std/env/fn.home_dir.html
158 pub fn new() -> Option<BaseDirs> {
159 sys::base_dirs()
160 }
161 /// Returns the path to the user's home directory.
162 ///
163 /// |Platform | Value | Example |
164 /// | ------- | -------------------- | -------------- |
165 /// | Linux | `$HOME` | /home/alice |
166 /// | macOS | `$HOME` | /Users/Alice |
167 /// | Windows | `{FOLDERID_Profile}` | C:\Users\Alice |
168 pub fn home_dir(&self) -> &Path {
169 self.home_dir.as_path()
170 }
171 /// Returns the path to the user's cache directory.
172 ///
173 /// |Platform | Value | Example |
174 /// | ------- | ----------------------------------- | ---------------------------- |
175 /// | Linux | `$XDG_CACHE_HOME` or `$HOME`/.cache | /home/alice/.cache |
176 /// | macOS | `$HOME`/Library/Caches | /Users/Alice/Library/Caches |
177 /// | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local |
178 pub fn cache_dir(&self) -> &Path {
179 self.cache_dir.as_path()
180 }
181 /// Returns the path to the user's config directory.
182 ///
183 /// |Platform | Value | Example |
184 /// | ------- | ------------------------------------- | -------------------------------- |
185 /// | Linux | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config |
186 /// | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support |
187 /// | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming |
188 pub fn config_dir(&self) -> &Path {
189 self.config_dir.as_path()
190 }
191 /// Returns the path to the user's data directory.
192 ///
193 /// |Platform | Value | Example |
194 /// | ------- | ---------------------------------------- | ---------------------------------------- |
195 /// | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share |
196 /// | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support |
197 /// | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming |
198 pub fn data_dir(&self) -> &Path {
199 self.data_dir.as_path()
200 }
201 /// Returns the path to the user's local data directory.
202 ///
203 /// |Platform | Value | Example |
204 /// | ------- | ---------------------------------------- | ---------------------------------------- |
205 /// | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share |
206 /// | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support |
207 /// | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local |
208 pub fn data_local_dir(&self) -> &Path {
209 self.data_local_dir.as_path()
210 }
211 /// Returns the path to the user's executable directory.
212 ///
213 /// |Platform | Value | Example |
214 /// | ------- | ---------------------------------------------------------------- | ---------------------- |
215 /// | Linux | `$XDG_BIN_HOME` or `$XDG_DATA_HOME`/../bin or `$HOME`/.local/bin | /home/alice/.local/bin |
216 /// | macOS | – | – |
217 /// | Windows | – | – |
218 pub fn executable_dir(&self) -> Option<&Path> {
219 self.executable_dir.as_ref().map(|p| p.as_path())
220 }
221 /// Returns the path to the user's runtime directory.
222 ///
223 /// |Platform | Value | Example |
224 /// | ------- | ------------------ | --------------- |
225 /// | Linux | `$XDG_RUNTIME_DIR` | /run/user/1001/ |
226 /// | macOS | – | – |
227 /// | Windows | – | – |
228 pub fn runtime_dir(&self) -> Option<&Path> {
229 self.runtime_dir.as_ref().map(|p| p.as_path())
230 }
231}
232
233impl UserDirs {
234 /// Creates a `UserDirs` struct which holds the paths to user-facing directories for audio, font, video, etc. data on the system.
235 ///
236 /// The returned value depends on the operating system and is either
237 /// - `Some`, containing a snapshot of the state of the system's paths at the time `new()` was invoked, or
238 /// - `None`, if no valid home directory path could be retrieved from the operating system.
239 ///
240 /// To determine whether a system provides a valid `$HOME` path, please refer to [`BaseDirs::new`]
241 pub fn new() -> Option<UserDirs> {
242 sys::user_dirs()
243 }
244 /// Returns the path to the user's home directory.
245 ///
246 /// |Platform | Value | Example |
247 /// | ------- | -------------------- | -------------- |
248 /// | Linux | `$HOME` | /home/alice |
249 /// | macOS | `$HOME` | /Users/Alice |
250 /// | Windows | `{FOLDERID_Profile}` | C:\Users\Alice |
251 pub fn home_dir(&self) -> &Path {
252 self.home_dir.as_path()
253 }
254 /// Returns the path to the user's audio directory.
255 ///
256 /// |Platform | Value | Example |
257 /// | ------- | ------------------ | -------------------- |
258 /// | Linux | `XDG_MUSIC_DIR` | /home/alice/Music |
259 /// | macOS | `$HOME`/Music | /Users/Alice/Music |
260 /// | Windows | `{FOLDERID_Music}` | C:\Users\Alice\Music |
261 pub fn audio_dir(&self) -> Option<&Path> {
262 self.audio_dir.as_ref().map(|p| p.as_path())
263 }
264 /// Returns the path to the user's desktop directory.
265 ///
266 /// |Platform | Value | Example |
267 /// | ------- | -------------------- | ---------------------- |
268 /// | Linux | `XDG_DESKTOP_DIR` | /home/alice/Desktop |
269 /// | macOS | `$HOME`/Desktop | /Users/Alice/Desktop |
270 /// | Windows | `{FOLDERID_Desktop}` | C:\Users\Alice\Desktop |
271 pub fn desktop_dir(&self) -> Option<&Path> {
272 self.desktop_dir.as_ref().map(|p| p.as_path())
273 }
274 /// Returns the path to the user's document directory.
275 ///
276 /// |Platform | Value | Example |
277 /// | ------- | ---------------------- | ------------------------ |
278 /// | Linux | `XDG_DOCUMENTS_DIR` | /home/alice/Documents |
279 /// | macOS | `$HOME`/Documents | /Users/Alice/Documents |
280 /// | Windows | `{FOLDERID_Documents}` | C:\Users\Alice\Documents |
281 pub fn document_dir(&self) -> Option<&Path> {
282 self.document_dir.as_ref().map(|p| p.as_path())
283 }
284 /// Returns the path to the user's download directory.
285 ///
286 /// |Platform | Value | Example |
287 /// | ------- | ---------------------- | ------------------------ |
288 /// | Linux | `XDG_DOWNLOAD_DIR` | /home/alice/Downloads |
289 /// | macOS | `$HOME`/Downloads | /Users/Alice/Downloads |
290 /// | Windows | `{FOLDERID_Downloads}` | C:\Users\Alice\Downloads |
291 pub fn download_dir(&self) -> Option<&Path> {
292 self.download_dir.as_ref().map(|p| p.as_path())
293 }
294 /// Returns the path to the user's font directory.
295 ///
296 /// |Platform | Value | Example |
297 /// | ------- | ---------------------------------------------------- | ------------------------------ |
298 /// | Linux | `$XDG_DATA_HOME`/fonts or `$HOME`/.local/share/fonts | /home/alice/.local/share/fonts |
299 /// | macOS | `$HOME`/Library/Fonts | /Users/Alice/Library/Fonts |
300 /// | Windows | – | – |
301 pub fn font_dir(&self) -> Option<&Path> {
302 self.font_dir.as_ref().map(|p| p.as_path())
303 }
304 /// Returns the path to the user's picture directory.
305 ///
306 /// |Platform | Value | Example |
307 /// | ------- | --------------------- | ----------------------- |
308 /// | Linux | `XDG_PICTURES_DIR` | /home/alice/Pictures |
309 /// | macOS | `$HOME`/Pictures | /Users/Alice/Pictures |
310 /// | Windows | `{FOLDERID_Pictures}` | C:\Users\Alice\Pictures |
311 pub fn picture_dir(&self) -> Option<&Path> {
312 self.picture_dir.as_ref().map(|p| p.as_path())
313 }
314 /// Returns the path to the user's public directory.
315 ///
316 /// |Platform | Value | Example |
317 /// | ------- | --------------------- | ------------------- |
318 /// | Linux | `XDG_PUBLICSHARE_DIR` | /home/alice/Public |
319 /// | macOS | `$HOME`/Public | /Users/Alice/Public |
320 /// | Windows | `{FOLDERID_Public}` | C:\Users\Public |
321 pub fn public_dir(&self) -> Option<&Path> {
322 self.public_dir.as_ref().map(|p| p.as_path())
323 }
324 /// Returns the path to the user's template directory.
325 ///
326 /// |Platform | Value | Example |
327 /// | ------- | ---------------------- | ---------------------------------------------------------- |
328 /// | Linux | `XDG_TEMPLATES_DIR` | /home/alice/Templates |
329 /// | macOS | – | – |
330 /// | Windows | `{FOLDERID_Templates}` | C:\Users\Alice\AppData\Roaming\Microsoft\Windows\Templates |
331 pub fn template_dir(&self) -> Option<&Path> {
332 self.template_dir.as_ref().map(|p| p.as_path())
333 }
334 /// Returns the path to the user's video directory.
335 ///
336 /// |Platform | Value | Example |
337 /// | ------- | ------------------- | --------------------- |
338 /// | Linux | `XDG_VIDEOS_DIR` | /home/alice/Videos |
339 /// | macOS | `$HOME`/Movies | /Users/Alice/Movies |
340 /// | Windows | `{FOLDERID_Videos}` | C:\Users\Alice\Videos |
341 pub fn video_dir(&self) -> Option<&Path> {
342 self.video_dir.as_ref().map(|p| p.as_path())
343 }
344}
345
346impl ProjectDirs {
347 /// Creates a `ProjectDirs` struct directly from a `PathBuf` value.
348 /// The argument is used verbatim and is not adapted to operating system standards.
349 ///
350 /// The use of `ProjectDirs::from_path` is strongly discouraged, as its results will
351 /// not follow operating system standards on at least two of three platforms.
352 ///
353 /// Use [`ProjectDirs::from`] instead.
354 pub fn from_path(project_path: PathBuf) -> Option<ProjectDirs> {
355 sys::project_dirs_from_path(project_path)
356 }
357 /// Creates a `ProjectDirs` struct from values describing the project.
358 ///
359 /// The returned value depends on the operating system and is either
360 /// - `Some`, containing project directory paths based on the state of the system's paths at the time `new()` was invoked, or
361 /// - `None`, if no valid home directory path could be retrieved from the operating system.
362 ///
363 /// To determine whether a system provides a valid `$HOME` path, please refer to [`BaseDirs::new`]
364 ///
365 /// The use of `ProjectDirs::from` (instead of `ProjectDirs::from_path`) is strongly encouraged,
366 /// as its results will follow operating system standards on Linux, macOS and Windows.
367 ///
368 /// # Parameters
369 ///
370 /// - `qualifier` – The reverse domain name notation of the application, excluding the organization or application name itself.<br/>
371 /// An empty string can be passed if no qualifier should be used (only affects macOS).<br/>
372 /// Example values: `"com.example"`, `"org"`, `"uk.co"`, `"io"`, `""`
373 /// - `organization` – The name of the organization that develops this application, or for which the application is developed.<br/>
374 /// An empty string can be passed if no organization should be used (only affects macOS and Windows).<br/>
375 /// Example values: `"Foo Corp"`, `"Alice and Bob Inc"`, `""`
376 /// - `application` – The name of the application itself.<br/>
377 /// Example values: `"Bar App"`, `"ExampleProgram"`, `"Unicorn-Programme"`
378 ///
379 /// [`BaseDirs::home_dir`]: struct.BaseDirs.html#method.home_dir
380 pub fn from(qualifier: &str, organization: &str, application: &str) -> Option<ProjectDirs> {
381 sys::project_dirs_from(qualifier, organization, application)
382 }
383 /// Returns the project path fragment used to compute the project's cache/config/data directories.
384 /// The value is derived from the `ProjectDirs::from` call and is platform-dependent.
385 pub fn project_path(&self) -> &Path {
386 self.project_path.as_path()
387 }
388 /// Returns the path to the project's cache directory.
389 ///
390 /// |Platform | Value | Example |
391 /// | ------- | --------------------------------------------------------------------- | --------------------------------------------------- |
392 /// | Linux | `$XDG_CACHE_HOME`/`_project_path_` or `$HOME`/.cache/`_project_path_` | /home/alice/.cache/barapp |
393 /// | macOS | `$HOME`/Library/Caches/`_project_path_` | /Users/Alice/Library/Caches/com.Foo-Corp.Bar-App |
394 /// | Windows | `{FOLDERID_LocalAppData}`\\`_project_path_`\\cache | C:\Users\Alice\AppData\Local\Foo Corp\Bar App\cache |
395 pub fn cache_dir(&self) -> &Path {
396 self.cache_dir.as_path()
397 }
398 /// Returns the path to the project's config directory.
399 ///
400 /// |Platform | Value | Example |
401 /// | ------- | ----------------------------------------------------------------------- | ------------------------------------------------------ |
402 /// | Linux | `$XDG_CONFIG_HOME`/`_project_path_` or `$HOME`/.config/`_project_path_` | /home/alice/.config/barapp |
403 /// | macOS | `$HOME`/Library/Application Support/`_project_path_` | /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App |
404 /// | Windows | `{FOLDERID_RoamingAppData}`\\`_project_path_`\\config | C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App\config |
405 pub fn config_dir(&self) -> &Path {
406 self.config_dir.as_path()
407 }
408 /// Returns the path to the project's data directory.
409 ///
410 /// |Platform | Value | Example |
411 /// | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- |
412 /// | Linux | `$XDG_DATA_HOME`/`_project_path_` or `$HOME`/.local/share/`_project_path_` | /home/alice/.local/share/barapp |
413 /// | macOS | `$HOME`/Library/Application Support/`_project_path_` | /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App |
414 /// | Windows | `{FOLDERID_RoamingAppData}`\\`_project_path_`\\data | C:\Users\Alice\AppData\Roaming\Foo Corp\Bar App\data |
415 pub fn data_dir(&self) -> &Path {
416 self.data_dir.as_path()
417 }
418 /// Returns the path to the project's local data directory.
419 ///
420 /// |Platform | Value | Example |
421 /// | ------- | -------------------------------------------------------------------------- | ------------------------------------------------------------- |
422 /// | Linux | `$XDG_DATA_HOME`/`_project_path_` or `$HOME`/.local/share/`_project_path_` | /home/alice/.local/share/barapp |
423 /// | macOS | `$HOME`/Library/Application Support/`_project_path_` | /Users/Alice/Library/Application Support/com.Foo-Corp.Bar-App |
424 /// | Windows | `{FOLDERID_LocalAppData}`\\`_project_path_`\\data | C:\Users\Alice\AppData\Local\Foo Corp\Bar App\data |
425 pub fn data_local_dir(&self) -> &Path {
426 self.data_local_dir.as_path()
427 }
428 /// Returns the path to the project's runtime directory.
429 ///
430 /// |Platform | Value | Example |
431 /// | ------- | ----------------------------------- | --------------------- |
432 /// | Linux | `$XDG_RUNTIME_DIR`/`_project_path_` | /run/user/1001/barapp |
433 /// | macOS | – | – |
434 /// | Windows | – | – |
435 pub fn runtime_dir(&self) -> Option<&Path> {
436 self.runtime_dir.as_ref().map(|p| p.as_path())
437 }
438}
439
440#[cfg(test)]
441mod tests {
442 #[test]
443 fn test_base_dirs() {
444 println!("BaseDirs::new())\n{:?}", crate::BaseDirs::new());
445 }
446
447 #[test]
448 fn test_user_dirs() {
449 println!("UserDirs::new())\n{:?}", crate::UserDirs::new());
450 }
451
452 #[test]
453 fn test_project_dirs() {
454 let proj_dirs = crate::ProjectDirs::from("qux", "FooCorp", "BarApp");
455 println!("ProjectDirs::from(\"qux\", \"FooCorp\", \"BarApp\")\n{:?}", proj_dirs);
456 let proj_dirs = crate::ProjectDirs::from("qux.zoo", "Foo Corp", "Bar-App");
457 println!("ProjectDirs::from(\"qux.zoo\", \"Foo Corp\", \"Bar-App\")\n{:?}", proj_dirs);
458 let proj_dirs = crate::ProjectDirs::from("com", "Foo Corp.", "Bar App");
459 println!("ProjectDirs::from(\"com\", \"Foo Corp.\", \"Bar App\")\n{:?}", proj_dirs);
460 }
461}