Skip to main content

lean_ctx/core/
data_dir.rs

1use std::path::PathBuf;
2
3/// Resolve the lean-ctx data directory.
4///
5/// Priority order (backward-compatible XDG migration):
6/// 1. `LEAN_CTX_DATA_DIR` env var (explicit override)
7/// 2. `~/.lean-ctx` if it already exists (don't break existing installs)
8/// 3. `$XDG_CONFIG_HOME/lean-ctx` (XDG compliant, default `~/.config/lean-ctx`)
9pub fn lean_ctx_data_dir() -> Result<PathBuf, String> {
10    if let Ok(dir) = std::env::var("LEAN_CTX_DATA_DIR") {
11        let trimmed = dir.trim();
12        if !trimmed.is_empty() {
13            return Ok(PathBuf::from(trimmed));
14        }
15    }
16
17    let home = dirs::home_dir().ok_or_else(|| "Cannot determine home directory".to_string())?;
18
19    let legacy = home.join(".lean-ctx");
20    if legacy.exists() {
21        return Ok(legacy);
22    }
23
24    let xdg_config = std::env::var("XDG_CONFIG_HOME")
25        .ok()
26        .filter(|s| !s.trim().is_empty())
27        .map_or_else(|| home.join(".config"), PathBuf::from);
28
29    Ok(xdg_config.join("lean-ctx"))
30}
31
32pub fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
33    use std::sync::{Mutex, OnceLock};
34    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
35    let mutex = LOCK.get_or_init(|| Mutex::new(()));
36    mutex
37        .lock()
38        .unwrap_or_else(std::sync::PoisonError::into_inner)
39}