1#[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#[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#[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#[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}