1#[cfg(not(windows))]
12use std::ffi::OsString;
13#[cfg(not(windows))]
14use std::path::Path;
15use std::path::PathBuf;
16
17const NAME: &str = "transitous";
18
19#[cfg(not(windows))]
22pub fn config() -> Option<PathBuf> {
23 xdg(
24 std::env::var_os("XDG_CONFIG_HOME"),
25 home().as_deref(),
26 ".config",
27 )
28}
29
30#[cfg(windows)]
33pub fn config() -> Option<PathBuf> {
34 directories::ProjectDirs::from("", "", NAME).map(|dirs| dirs.config_dir().to_owned())
35}
36
37#[cfg(not(windows))]
40pub fn state() -> Option<PathBuf> {
41 xdg(
42 std::env::var_os("XDG_STATE_HOME"),
43 home().as_deref(),
44 ".local/state",
45 )
46}
47
48#[cfg(windows)]
51pub fn state() -> Option<PathBuf> {
52 directories::ProjectDirs::from("", "", NAME).map(|dirs| dirs.data_local_dir().to_owned())
53}
54
55#[cfg(not(any(windows, target_os = "macos")))]
58pub fn cache() -> Option<PathBuf> {
59 xdg(
60 std::env::var_os("XDG_CACHE_HOME"),
61 home().as_deref(),
62 ".cache",
63 )
64}
65
66#[cfg(target_os = "macos")]
69pub fn cache() -> Option<PathBuf> {
70 directories::BaseDirs::new().map(|dirs| dirs.cache_dir().join(NAME))
71}
72
73#[cfg(windows)]
76pub fn cache() -> Option<PathBuf> {
77 directories::ProjectDirs::from("", "", NAME).map(|dirs| dirs.cache_dir().to_owned())
78}
79
80#[cfg(not(windows))]
81fn home() -> Option<PathBuf> {
82 directories::BaseDirs::new().map(|dirs| dirs.home_dir().to_owned())
83}
84
85#[cfg(not(windows))]
88fn xdg(variable: Option<OsString>, home: Option<&Path>, default: &str) -> Option<PathBuf> {
89 let base = variable
90 .map(PathBuf::from)
91 .filter(|path| path.is_absolute())
92 .or_else(|| home.map(|home| home.join(default)))?;
93 Some(base.join(NAME))
94}
95
96#[cfg(test)]
97mod tests {
98 use super::*;
99
100 #[test]
101 #[cfg(not(windows))]
102 fn follows_the_variable() {
103 assert_eq!(
104 xdg(Some("/xdg".into()), Some(Path::new("/home/me")), ".config"),
105 Some(PathBuf::from("/xdg/transitous"))
106 );
107 }
108
109 #[test]
110 #[cfg(not(windows))]
111 fn falls_back_to_the_home_directory() {
112 let home = Some(Path::new("/home/me"));
113 let expected = Some(PathBuf::from("/home/me/.local/state/transitous"));
114 assert_eq!(xdg(None, home, ".local/state"), expected);
115 assert_eq!(xdg(Some("".into()), home, ".local/state"), expected);
116 assert_eq!(xdg(Some("relative".into()), home, ".local/state"), expected);
117 }
118
119 #[test]
120 #[cfg(not(windows))]
121 fn needs_a_home_directory() {
122 assert_eq!(xdg(None, None, ".config"), None);
123 }
124
125 #[test]
126 fn lies_in_a_directory_of_transitous() {
127 for dir in [config().unwrap(), state().unwrap(), cache().unwrap()] {
128 assert!(
129 dir.components().any(|part| part.as_os_str() == NAME),
130 "{}",
131 dir.display()
132 );
133 }
134 }
135}