use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use crate::log::{Level, Logger};
pub(super) const CACHE_VERSION: &str = "1";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CacheSource {
LoginShell {
shell: PathBuf,
},
Terminal,
Registry,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathCache {
pub version: String,
pub saved_at: DateTime<Utc>,
pub source: CacheSource,
pub path: Vec<PathBuf>,
#[serde(default)]
pub tools: BTreeMap<String, PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CachedPath {
pub saved_at: DateTime<Utc>,
pub source: CacheSource,
pub version: String,
pub added: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CachedTool {
pub path: PathBuf,
pub saved_at: DateTime<Utc>,
pub usable: bool,
}
pub fn read_cache(file: &Path) -> Option<PathCache> {
let bytes = std::fs::read(file).ok()?;
let mut cache = serde_json::from_slice::<PathCache>(&bytes)
.ok()
.filter(|cache| cache.version == CACHE_VERSION)?;
cache.tools.retain(|_, path| path.is_absolute());
Some(cache)
}
pub(super) fn write_cache(file: &Path, cache: &PathCache) -> std::io::Result<()> {
use std::io::Write as _;
let directory = file.parent().unwrap_or(Path::new("."));
std::fs::create_dir_all(directory)?;
let bytes = serde_json::to_vec_pretty(cache).map_err(std::io::Error::other)?;
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
crate::private_file::set_owner_only(temporary.path())?;
temporary.write_all(&bytes)?;
temporary.as_file().sync_all()?;
temporary.persist(file).map_err(|error| error.error)?;
Ok(())
}
struct Active {
file: PathBuf,
tools: Mutex<BTreeMap<String, PathBuf>>,
}
static ACTIVE: OnceLock<Active> = OnceLock::new();
pub(super) fn activate(file: PathBuf, cache: Option<&PathCache>) {
let tools = cache.map(|cache| cache.tools.clone()).unwrap_or_default();
let _ = ACTIVE.set(Active {
file,
tools: Mutex::new(tools),
});
}
pub(super) fn remember_tool(name: &str, found: &Path) {
let Some(active) = ACTIVE.get() else {
return;
};
let Ok(mut tools) = active.tools.lock() else {
return;
};
if tools.get(name).is_some_and(|saved| saved == found) {
return;
}
if remember_in(&active.file, name, found).is_ok() {
tools.insert(name.to_string(), found.to_path_buf());
}
}
pub(super) fn remember_in(file: &Path, name: &str, found: &Path) -> std::io::Result<()> {
let Some(mut cache) = read_cache(file) else {
return Err(std::io::Error::other("no path cache"));
};
cache.tools.insert(name.to_string(), found.to_path_buf());
write_cache(file, &cache)
}
pub(super) fn cached_tool_in(
cache: &PathCache,
name: &str,
usable: fn(&Path) -> bool,
) -> Option<CachedTool> {
let path = cache.tools.get(name)?;
Some(CachedTool {
path: path.clone(),
saved_at: cache.saved_at,
usable: usable(path),
})
}
pub(super) fn cached_tool(name: &str) -> Option<PathBuf> {
let active = ACTIVE.get()?;
let tool = read_cached_tool(&active.file, name)?;
record_tool_use(name, tool)
}
fn record_tool_use(name: &str, tool: CachedTool) -> Option<PathBuf> {
if !tool.usable {
return None;
}
let path = tool.path.display().to_string();
Logger::new("path").record(
Level::Info,
"cached tool path used",
&[("tool", name), ("path", &path)],
);
Some(tool.path)
}
pub(super) fn cached_tool_readonly(name: &str) -> Option<PathBuf> {
let active = ACTIVE.get()?;
cached_tool_readonly_in(&active.file, name)
}
pub(super) fn cached_tool_readonly_in(file: &Path, name: &str) -> Option<PathBuf> {
let tool = read_cached_tool(file, name)?;
tool.usable.then_some(tool.path)
}
fn read_cached_tool(file: &Path, name: &str) -> Option<CachedTool> {
let cache = read_cache(file)?;
cached_tool_in(&cache, name, super::lookup::usable_cached)
}
#[cfg(test)]
mod tests;