bevy_platform/dirs/linux.rs
1use std::{
2 env::{self, home_dir},
3 path::PathBuf,
4};
5
6/// The path if it's absolute or [`None`]. Empty paths are not absolute.
7///
8/// [XDG Base Directory Specification] requires that the path specified in environment variables must be absolute. If it's not, we should ignore it and fallback to the default path.
9///
10/// [XDG Base Directory Specification]: https://specifications.freedesktop.org/basedir/latest/
11fn is_absolute_path(path: impl Into<PathBuf>) -> Option<PathBuf> {
12 let path = path.into();
13 if path.is_absolute() {
14 Some(path)
15 } else {
16 None
17 }
18}
19
20/// Returns the path to the directory used for application settings.
21pub fn preferences_dir() -> Option<PathBuf> {
22 // default value for XDG_CONFIG_HOME when unset, empty, or invalid is ~/.config/
23 env::var_os("XDG_CONFIG_HOME")
24 .and_then(is_absolute_path)
25 .or_else(|| home_dir().map(|home| home.join(".config")))
26}
27
28#[cfg(test)]
29mod tests {
30 use super::*;
31
32 #[test]
33 fn empty_is_not_absolute() {
34 // preferences_dir() depends on is_absolute_path() returning None for empty paths, so we test that here.
35 assert!(is_absolute_path("").is_none());
36 }
37}