use crate::error::JmdictError;
use std::path::PathBuf;
use std::sync::OnceLock;
static OVERRIDE: OnceLock<PathBuf> = OnceLock::new();
pub fn init_sdk_cache_dir(path: PathBuf) -> Result<(), JmdictError> {
OVERRIDE
.set(path)
.map_err(|_| JmdictError::CacheDirAlreadySet)
}
pub fn resolved_cache_dir() -> Result<PathBuf, JmdictError> {
if let Some(p) = OVERRIDE.get() {
return Ok(p.clone());
}
platform_default()
}
fn platform_default() -> Result<PathBuf, JmdictError> {
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
{
dirs::cache_dir().ok_or(JmdictError::CacheDirRequired {
platform: std::env::consts::OS,
})
}
#[cfg(target_os = "ios")]
{
Err(JmdictError::CacheDirRequired { platform: "ios" })
}
#[cfg(target_os = "android")]
{
Err(JmdictError::CacheDirRequired { platform: "android" })
}
#[cfg(target_arch = "wasm32")]
{
Err(JmdictError::CacheDirRequired { platform: "wasm" })
}
#[cfg(not(any(
target_os = "macos",
target_os = "linux",
target_os = "windows",
target_os = "ios",
target_os = "android",
target_arch = "wasm32",
)))]
{
Err(JmdictError::CacheDirRequired {
platform: std::env::consts::OS,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolved_cache_dir_returns_path_on_desktop() {
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
{
let dir = resolved_cache_dir().expect("desktop should have a default cache dir");
assert!(dir.is_absolute(), "cache dir should be absolute, got {dir:?}");
}
}
}