use anyhow::{Result, anyhow};
use std::path::PathBuf;
pub(crate) const CONFIG_DIR_NAME: &str = ".toolpath";
pub(crate) const CONFIG_DIR_ENV: &str = "TOOLPATH_CONFIG_DIR";
pub(crate) fn config_dir() -> Result<PathBuf> {
if let Some(override_) = std::env::var_os(CONFIG_DIR_ENV) {
return Ok(PathBuf::from(override_));
}
let home = std::env::var_os("HOME")
.ok_or_else(|| anyhow!("$HOME is not set — cannot locate config directory"))?;
Ok(PathBuf::from(home).join(CONFIG_DIR_NAME))
}
#[cfg(test)]
pub(crate) static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn config_dir_honors_override() {
let _g = TEST_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
unsafe {
std::env::set_var(CONFIG_DIR_ENV, "/tmp/test-toolpath");
}
let dir = config_dir().unwrap();
unsafe {
std::env::remove_var(CONFIG_DIR_ENV);
}
assert_eq!(dir, PathBuf::from("/tmp/test-toolpath"));
}
}