use std::path::PathBuf;
use super::FILE_NAME;
const DIRECTORY: &str = "zond";
pub fn user() -> Option<PathBuf> {
user_directory().map(|directory| directory.join(FILE_NAME))
}
pub fn user_directory() -> Option<PathBuf> {
#[cfg(windows)]
{
return std::env::var_os("APPDATA")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.map(|path| path.join(DIRECTORY));
}
#[cfg(not(windows))]
{
if let Some(configured) = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
{
return Some(configured.join(DIRECTORY));
}
std::env::var_os("HOME")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.map(|home| home.join(".config").join(DIRECTORY))
}
}
pub fn system() -> Option<PathBuf> {
#[cfg(windows)]
{
return std::env::var_os("PROGRAMDATA")
.map(PathBuf::from)
.filter(|path| path.is_absolute())
.map(|path| path.join(DIRECTORY).join(FILE_NAME));
}
#[cfg(not(windows))]
{
Some(PathBuf::from("/etc").join(DIRECTORY).join(FILE_NAME))
}
}
pub fn layered() -> Vec<PathBuf> {
[system(), user()].into_iter().flatten().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_computed_path_ends_in_the_expected_directory_and_file() {
if let Some(path) = user() {
assert!(path.is_absolute(), "{path:?}");
assert!(
path.ends_with(format!("{DIRECTORY}/{FILE_NAME}")),
"{path:?}"
);
}
if let Some(path) = system() {
assert!(path.is_absolute(), "{path:?}");
assert!(
path.ends_with(format!("{DIRECTORY}/{FILE_NAME}")),
"{path:?}"
);
}
}
#[test]
fn the_user_file_layers_after_the_system_one() {
let paths = layered();
if let (Some(system), Some(user)) = (system(), user()) {
let system_at = paths.iter().position(|path| *path == system);
let user_at = paths.iter().position(|path| *path == user);
assert!(system_at < user_at, "{paths:?}");
}
}
#[test]
fn computing_a_path_touches_no_filesystem() {
let before = user().and_then(|path| path.parent().map(std::path::Path::exists));
let _ = user();
let _ = user_directory();
let _ = system();
let _ = layered();
let after = user().and_then(|path| path.parent().map(std::path::Path::exists));
assert_eq!(before, after, "asking where the settings are created them");
}
}