Skip to main content

rmv_core/
dirs.rs

1//! Where `rmv` keeps its configuration. On Linux and macOS it follows the
2//! XDG base directories: `~/.config/rmv`, or below `$XDG_CONFIG_HOME`. On
3//! Windows it is the usual one below `%APPDATA%`.
4//!
5//! `rmv` keeps nothing else: no cache and no state, so no answer of the API
6//! is stored.
7
8#[cfg(not(windows))]
9use std::ffi::OsString;
10#[cfg(not(windows))]
11use std::path::Path;
12use std::path::PathBuf;
13
14const NAME: &str = "rmv";
15
16/// The directory of the configuration. `None` if the home directory is
17/// unknown.
18#[cfg(not(windows))]
19pub fn config() -> Option<PathBuf> {
20    xdg(
21        std::env::var_os("XDG_CONFIG_HOME"),
22        home().as_deref(),
23        ".config",
24    )
25}
26
27/// The directory of the configuration. `None` if the home directory is
28/// unknown.
29#[cfg(windows)]
30pub fn config() -> Option<PathBuf> {
31    directories::ProjectDirs::from("", "", NAME).map(|dirs| dirs.config_dir().to_owned())
32}
33
34#[cfg(not(windows))]
35fn home() -> Option<PathBuf> {
36    directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_owned())
37}
38
39/// The directory of `rmv` below the XDG variable, or below its default in
40/// the home directory. The specification ignores relative paths.
41#[cfg(not(windows))]
42fn xdg(variable: Option<OsString>, home: Option<&Path>, default: &str) -> Option<PathBuf> {
43    let base = variable
44        .map(PathBuf::from)
45        .filter(|path| path.is_absolute())
46        .or_else(|| home.map(|home| home.join(default)))?;
47    Some(base.join(NAME))
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    #[cfg(not(windows))]
56    fn follows_the_variable() {
57        assert_eq!(
58            xdg(Some("/xdg".into()), Some(Path::new("/home/me")), ".config"),
59            Some(PathBuf::from("/xdg/rmv"))
60        );
61    }
62
63    #[test]
64    #[cfg(not(windows))]
65    fn falls_back_to_the_home_directory() {
66        let home = Some(Path::new("/home/me"));
67        let expected = Some(PathBuf::from("/home/me/.config/rmv"));
68        assert_eq!(xdg(None, home, ".config"), expected);
69        assert_eq!(xdg(Some("".into()), home, ".config"), expected);
70        assert_eq!(xdg(Some("relative".into()), home, ".config"), expected);
71    }
72
73    #[test]
74    #[cfg(not(windows))]
75    fn needs_a_home_directory() {
76        assert_eq!(xdg(None, None, ".config"), None);
77    }
78
79    #[test]
80    fn lies_in_a_directory_of_rmv() {
81        let dir = config().unwrap();
82        assert!(
83            dir.components().any(|part| part.as_os_str() == NAME),
84            "{}",
85            dir.display()
86        );
87    }
88}