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(PathBuf::from)
28        .unwrap_or_else(|| home.join(".config"));
29
30    Ok(xdg_config.join("lean-ctx"))
31}
32
33pub fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
34    use std::sync::{Mutex, OnceLock};
35    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
36    let mutex = LOCK.get_or_init(|| Mutex::new(()));
37    mutex
38        .lock()
39        .unwrap_or_else(|poisoned| poisoned.into_inner())
40}