1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#[derive(Clone, Debug, Default)]
pub struct Dir<'a> {
pub prefix: DirPrefix,
pub salt: &'a str,
pub path: &'a str,
}
#[derive(Clone, Debug, Default)]
pub struct CacheDir<'a> {
pub prefix: DirPrefix,
pub path: &'a str,
}
#[derive(Clone, Debug, Default)]
pub struct Include<'a> {
pub prefix: DirPrefix,
pub ignore_missing: bool,
pub path: &'a str,
}
#[derive(Clone, Copy, Debug)]
pub enum DirPrefix {
Default,
Cwd,
Xdg,
Relative,
}
parse_enum! {
DirPrefix,
(Default, "default"),
(Cwd, "cwd"),
(Xdg, "xdg"),
(Relative, "relative"),
}
impl Default for DirPrefix {
fn default() -> Self {
DirPrefix::Default
}
}
macro_rules! define_calculate_path {
($ty:ident, $xdg_env:expr, $xdg_fallback:expr) => {
impl<'a> $ty<'a> {
pub const XDG_ENV: &'static str = $xdg_env;
pub const XDG_FALLBACK_PATH: &'static str = $xdg_fallback;
#[cfg(feature = "std")]
pub fn calculate_path<P: AsRef<std::path::Path> + ?Sized>(
&self,
config_file_path: &P,
) -> std::path::PathBuf {
match self.prefix {
DirPrefix::Default => self.path.into(),
DirPrefix::Cwd => std::path::Path::new(".").join(self.path),
DirPrefix::Relative => config_file_path.as_ref().join(self.path),
DirPrefix::Xdg => std::path::PathBuf::from(
std::env::var($xdg_env).unwrap_or_else(|_| $xdg_fallback.into()),
)
.join(self.path),
}
}
}
};
}
define_calculate_path!(Dir, "XDG_DATA_HOME", "~/.local/share");
define_calculate_path!(CacheDir, "XDG_CACHE_HOME", "~/.cache");
define_calculate_path!(Include, "XDG_CONFIG_HOME", "~/.config");