use std::path::PathBuf;
use crate::error::SessionError;
pub fn resolve_data_dir_with(
env: impl Fn(&str) -> Option<String>,
) -> Result<PathBuf, SessionError> {
if let Some(val) = env("ZENITH_DATA_DIR")
&& !val.is_empty()
{
return Ok(PathBuf::from(val));
}
dirs::data_dir().map(|d| d.join("zenith")).ok_or_else(|| {
SessionError::new(
"cannot determine data directory \
(no ZENITH_DATA_DIR and platform data dir unavailable)",
)
})
}
pub fn resolve_data_dir() -> Result<PathBuf, SessionError> {
resolve_data_dir_with(|k| std::env::var(k).ok())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn custom_override_is_used() {
let result = resolve_data_dir_with(|_| Some("/custom/path".into()));
assert_eq!(result.unwrap(), PathBuf::from("/custom/path"));
}
#[test]
fn empty_override_falls_through_to_platform() {
let result = resolve_data_dir_with(|k| {
if k == "ZENITH_DATA_DIR" {
Some(String::new()) } else {
None
}
});
match result {
Ok(path) => {
assert!(
path.ends_with("zenith"),
"expected path to end with 'zenith', got: {}",
path.display()
);
}
Err(_) => {
}
}
}
#[test]
fn no_override_yields_platform_or_err() {
let result = resolve_data_dir_with(|_| None);
match result {
Ok(path) => {
assert!(
path.ends_with("zenith"),
"expected path to end with 'zenith', got: {}",
path.display()
);
}
Err(e) => {
assert!(e.message.contains("cannot determine data directory"));
}
}
}
}