nu_path/
helpers.rs

1use std::path::PathBuf;
2
3use crate::AbsolutePathBuf;
4
5pub fn home_dir() -> Option<AbsolutePathBuf> {
6    dirs::home_dir().and_then(|home| AbsolutePathBuf::try_from(home).ok())
7}
8
9/// Return the data directory for the current platform or XDG_DATA_HOME if specified.
10pub fn data_dir() -> Option<AbsolutePathBuf> {
11    configurable_dir_path("XDG_DATA_HOME", dirs::data_dir)
12}
13
14/// Return the cache directory for the current platform or XDG_CACHE_HOME if specified.
15pub fn cache_dir() -> Option<AbsolutePathBuf> {
16    configurable_dir_path("XDG_CACHE_HOME", dirs::cache_dir)
17}
18
19/// Return the nushell config directory.
20pub fn nu_config_dir() -> Option<AbsolutePathBuf> {
21    configurable_dir_path("XDG_CONFIG_HOME", dirs::config_dir).map(|mut p| {
22        p.push("nushell");
23        p
24    })
25}
26
27fn configurable_dir_path(
28    name: &'static str,
29    dir: impl FnOnce() -> Option<PathBuf>,
30) -> Option<AbsolutePathBuf> {
31    std::env::var(name)
32        .ok()
33        .and_then(|path| AbsolutePathBuf::try_from(path).ok())
34        .or_else(|| dir().and_then(|path| AbsolutePathBuf::try_from(path).ok()))
35        .map(|path| path.canonicalize().map(Into::into).unwrap_or(path))
36}