subspace_core/path/
cache.rs1use std::collections::BTreeMap;
15use std::path::{Path, PathBuf};
16use std::sync::{Mutex, OnceLock};
17
18use chrono::{DateTime, Utc};
19use serde::{Deserialize, Serialize};
20
21use crate::log::{Level, Logger};
22
23pub(super) const CACHE_VERSION: &str = "1";
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(tag = "kind", rename_all = "snake_case")]
29pub enum CacheSource {
30 LoginShell {
31 shell: PathBuf,
32 },
33 Terminal,
34 Registry,
36}
37
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct PathCache {
41 pub version: String,
42 pub saved_at: DateTime<Utc>,
43 pub source: CacheSource,
44 pub path: Vec<PathBuf>,
46 #[serde(default)]
49 pub tools: BTreeMap<String, PathBuf>,
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct CachedPath {
55 pub saved_at: DateTime<Utc>,
56 pub source: CacheSource,
57 pub version: String,
58 pub added: usize,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
64pub struct CachedTool {
65 pub path: PathBuf,
66 pub saved_at: DateTime<Utc>,
68 pub usable: bool,
70}
71
72pub fn read_cache(file: &Path) -> Option<PathCache> {
78 let bytes = std::fs::read(file).ok()?;
79 let mut cache = serde_json::from_slice::<PathCache>(&bytes)
80 .ok()
81 .filter(|cache| cache.version == CACHE_VERSION)?;
82 cache.tools.retain(|_, path| path.is_absolute());
83 Some(cache)
84}
85
86pub(super) fn write_cache(file: &Path, cache: &PathCache) -> std::io::Result<()> {
89 use std::io::Write as _;
90
91 let directory = file.parent().unwrap_or(Path::new("."));
92 std::fs::create_dir_all(directory)?;
93 let bytes = serde_json::to_vec_pretty(cache).map_err(std::io::Error::other)?;
94 let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
95 crate::private_file::set_owner_only(temporary.path())?;
96 temporary.write_all(&bytes)?;
97 temporary.as_file().sync_all()?;
98 temporary.persist(file).map_err(|error| error.error)?;
99 Ok(())
100}
101
102struct Active {
104 file: PathBuf,
105 tools: Mutex<BTreeMap<String, PathBuf>>,
106}
107
108static ACTIVE: OnceLock<Active> = OnceLock::new();
109
110pub(super) fn activate(file: PathBuf, cache: Option<&PathCache>) {
112 let tools = cache.map(|cache| cache.tools.clone()).unwrap_or_default();
113 let _ = ACTIVE.set(Active {
114 file,
115 tools: Mutex::new(tools),
116 });
117}
118
119pub(super) fn remember_tool(name: &str, found: &Path) {
122 let Some(active) = ACTIVE.get() else {
123 return;
124 };
125 let Ok(mut tools) = active.tools.lock() else {
126 return;
127 };
128 if tools.get(name).is_some_and(|saved| saved == found) {
129 return;
130 }
131 if remember_in(&active.file, name, found).is_ok() {
132 tools.insert(name.to_string(), found.to_path_buf());
133 }
134}
135
136pub(super) fn remember_in(file: &Path, name: &str, found: &Path) -> std::io::Result<()> {
138 let Some(mut cache) = read_cache(file) else {
139 return Err(std::io::Error::other("no path cache"));
140 };
141 cache.tools.insert(name.to_string(), found.to_path_buf());
142 write_cache(file, &cache)
143}
144
145pub(super) fn cached_tool_in(
147 cache: &PathCache,
148 name: &str,
149 usable: fn(&Path) -> bool,
150) -> Option<CachedTool> {
151 let path = cache.tools.get(name)?;
152 Some(CachedTool {
153 path: path.clone(),
154 saved_at: cache.saved_at,
155 usable: usable(path),
156 })
157}
158
159pub(super) fn cached_tool(name: &str) -> Option<PathBuf> {
161 let active = ACTIVE.get()?;
162 let tool = read_cached_tool(&active.file, name)?;
163 record_tool_use(name, tool)
164}
165
166fn record_tool_use(name: &str, tool: CachedTool) -> Option<PathBuf> {
167 if !tool.usable {
168 return None;
169 }
170 let path = tool.path.display().to_string();
171 Logger::new("path").record(
172 Level::Info,
173 "cached tool path used",
174 &[("tool", name), ("path", &path)],
175 );
176 Some(tool.path)
177}
178
179pub(super) fn cached_tool_readonly(name: &str) -> Option<PathBuf> {
181 let active = ACTIVE.get()?;
182 cached_tool_readonly_in(&active.file, name)
183}
184
185pub(super) fn cached_tool_readonly_in(file: &Path, name: &str) -> Option<PathBuf> {
186 let tool = read_cached_tool(file, name)?;
187 tool.usable.then_some(tool.path)
188}
189
190fn read_cached_tool(file: &Path, name: &str) -> Option<CachedTool> {
191 let cache = read_cache(file)?;
192 cached_tool_in(&cache, name, super::lookup::usable_cached)
193}
194
195#[cfg(test)]
196mod tests;