1use std::path::PathBuf;
27
28pub fn config_dir_with(app: &str, env: impl Fn(&str) -> Option<String>) -> Option<PathBuf> {
31 if cfg!(target_arch = "wasm32") {
32 return None;
33 }
34 let absolute = |v: Option<String>| v.map(PathBuf::from).filter(|p| p.is_absolute());
35 let base = if cfg!(windows) {
36 absolute(env("APPDATA"))?
37 } else if cfg!(target_os = "macos") {
38 absolute(env("HOME"))?.join("Library/Application Support")
39 } else {
40 match absolute(env("XDG_CONFIG_HOME")) {
41 Some(p) => p,
42 None => absolute(env("HOME"))?.join(".config"),
43 }
44 };
45 Some(base.join(app))
46}
47
48pub fn config_dir(app: &str) -> Option<PathBuf> {
50 config_dir_with(app, |name| std::env::var(name).ok())
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn the_folder_follows_the_platform() {
59 let env = |name: &str| match name {
60 "HOME" => Some("/home/me".to_string()),
61 "APPDATA" => Some("C:\\Users\\me\\AppData\\Roaming".to_string()),
62 _ => None,
63 };
64 let dir = config_dir_with("swatch", env).unwrap();
65 if cfg!(windows) {
66 assert!(dir.ends_with("Roaming\\swatch"), "{dir:?}");
67 } else if cfg!(target_os = "macos") {
68 assert_eq!(
69 dir,
70 PathBuf::from("/home/me/Library/Application Support/swatch")
71 );
72 } else {
73 assert_eq!(dir, PathBuf::from("/home/me/.config/swatch"));
74 }
75 assert_eq!(config_dir_with("swatch", |_| None), None);
77 let relative =
78 |name: &str| (name == "XDG_CONFIG_HOME" || name == "HOME").then(|| "rel".to_string());
79 if cfg!(all(unix, not(target_os = "macos"))) {
80 assert_eq!(config_dir_with("swatch", relative), None);
81 }
82 }
83}