use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
mod catalog;
pub use catalog::{CACHES, Cache};
pub(crate) const CACHE_DIRS: &[&str] = &[
".cargo/bin",
".cargo/git",
".cargo/registry",
".rustup",
".bun",
".deno",
".npm",
".nvm",
".pnpm-store",
".volta",
".yarn",
".conda",
".local/pipx",
".local/share/virtualenvs",
".pyenv",
"miniconda3",
"miniforge3",
".gradle",
".ivy2",
".m2",
".sbt",
".sdkman",
".bundle",
".cabal",
".gem",
".ghcup",
".hex",
".opam",
".rbenv",
".stack",
".dotnet",
".nuget",
".pub-cache",
".swiftpm",
"fvm",
"go/bin",
"go/pkg",
".asdf",
".nodenv",
".terraform.d",
"google-cloud-sdk",
".local/share/gh",
".local/share/pnpm",
"Library/Developer/Toolchains",
"Library/pnpm",
".antigravity",
".codex/cache",
".codex/.tmp",
".hermes",
".vscode",
".vscode-server",
".cache",
".local/state",
"AppData/Local",
"AppData/Roaming",
"Library/Application Support",
"Library/Caches",
"scoop",
];
#[derive(Debug, Default)]
pub struct CacheRoots {
paths: HashSet<PathBuf>,
removable: HashMap<PathBuf, &'static Cache>,
}
impl CacheRoots {
#[must_use]
pub fn for_root(root: &Path, clean: &[String]) -> Self {
let Some(home) = dirs::home_dir() else {
return Self::default();
};
let mut resolved = Self::under(&home, root);
resolved.removable = removable_under(&home, root, clean);
resolved
}
#[cfg(test)]
pub(crate) fn under_with(home: &Path, root: &Path, clean: &[String]) -> Self {
let mut resolved = Self::under(home, root);
resolved.removable = removable_under(home, root, clean);
resolved
}
pub(crate) fn under(home: &Path, root: &Path) -> Self {
let (Ok(home), Ok(canonical_root)) = (home.canonicalize(), root.canonicalize()) else {
return Self::default();
};
if !canonical_root.starts_with(&home) && !home.starts_with(&canonical_root) {
return Self::default();
}
let paths = CACHE_DIRS
.iter()
.filter_map(|cache| home.join(cache).canonicalize().ok())
.filter_map(|cache| cache.strip_prefix(&canonical_root).ok().map(Path::to_path_buf))
.filter(|relative| relative.components().next().is_some())
.map(|relative| root.join(relative))
.collect();
Self {
paths,
removable: HashMap::new(),
}
}
#[must_use]
pub fn contains(&self, path: &Path) -> bool {
!self.paths.is_empty() && self.paths.contains(path)
}
#[must_use]
pub fn removable(&self, path: &Path) -> Option<&'static Cache> {
if self.removable.is_empty() {
return None;
}
self.removable.get(path).copied()
}
#[must_use]
pub fn removable_inside(&self, dir: &Path) -> Vec<(&Path, &'static Cache)> {
if self.removable.is_empty() {
return Vec::new();
}
self.removable
.iter()
.filter(|(path, _)| path.as_path() != dir && path.starts_with(dir))
.map(|(path, cache)| (path.as_path(), *cache))
.collect()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.paths.is_empty()
}
}
fn removable_under(home: &Path, root: &Path, clean: &[String]) -> HashMap<PathBuf, &'static Cache> {
if clean.is_empty() {
return HashMap::new();
}
let (Ok(home), Ok(canonical_root)) = (home.canonicalize(), root.canonicalize()) else {
return HashMap::new();
};
let mut resolved = HashMap::new();
for cache in CACHES {
if !clean.iter().any(|id| id == cache.id) {
continue;
}
for location in cache.locations {
let Ok(absolute) = home.join(location).canonicalize() else {
continue;
};
let Ok(relative) = absolute.strip_prefix(&canonical_root) else {
continue;
};
if relative.components().next().is_none() {
continue;
}
resolved.insert(root.join(relative), cache);
}
}
resolved
}
pub const BAZEL_ID: &str = "bazel";
#[must_use]
pub fn unknown_ids(clean: &[String]) -> Vec<String> {
clean
.iter()
.filter(|id| **id != BAZEL_ID && !CACHES.iter().any(|cache| cache.id == **id))
.cloned()
.collect()
}
#[cfg(test)]
mod tests {
use super::{CACHE_DIRS, CacheRoots};
use std::fs;
use tempfile::TempDir;
fn home(dirs: &[&str]) -> TempDir {
let home = TempDir::new().expect("a temp dir");
for dir in dirs {
fs::create_dir_all(home.path().join(dir)).expect("a cache dir");
}
home
}
#[test]
fn should_resolve_a_cache_directory_that_sits_under_the_root() {
let home = home(&[".cargo/registry", "projects"]);
let roots = CacheRoots::under(home.path(), home.path());
assert!(roots.contains(&home.path().join(".cargo/registry")));
assert!(!roots.contains(&home.path().join("projects")));
}
#[test]
#[cfg(unix)]
fn should_spell_the_cache_paths_the_way_the_root_is_spelled() {
let home = home(&[".npm"]);
let link = home.path().parent().expect("a parent").join("voom-cache-link");
let _ = fs::remove_file(&link);
std::os::unix::fs::symlink(home.path(), &link).expect("a symlink");
let roots = CacheRoots::under(home.path(), &link);
assert!(
roots.contains(&link.join(".npm")),
"the skip set must match what the walker produces, not where the path really is"
);
fs::remove_file(&link).expect("the link is removed");
}
#[test]
fn should_ignore_caches_that_sit_outside_the_root() {
let home = home(&[".npm", "work"]);
let roots = CacheRoots::under(home.path(), &home.path().join("work"));
assert!(roots.is_empty(), "a cache beside the root is not the walk's concern");
}
#[test]
fn should_not_skip_a_cache_named_as_the_scan_root_itself() {
let home = home(&[".npm"]);
let cache = home.path().join(".npm");
let roots = CacheRoots::under(home.path(), &cache);
assert!(roots.is_empty());
assert!(!roots.contains(&cache));
}
#[test]
fn should_always_skip_caches_by_location() {
let home = home(&[".cargo/registry"]);
let roots = CacheRoots::under_with(home.path(), home.path(), &[]);
assert!(
roots.contains(&home.path().join(".cargo/registry")),
"a sweep always skips an installed toolchain by location"
);
}
#[test]
fn should_tolerate_a_home_with_no_caches_at_all() {
let home = home(&[]);
assert!(CacheRoots::under(home.path(), home.path()).is_empty());
}
#[test]
fn the_cache_list_is_append_only() {
const REQUIRED: &[&str] = &[
".bun",
".cache",
".cargo/bin",
".cargo/git",
".cargo/registry",
".local/share/gh",
".gem",
".gradle",
".m2",
".npm",
".pub-cache",
".pyenv",
".rustup",
"Library/Application Support",
"Library/Caches",
"Library/Developer/Toolchains",
"go/bin",
"google-cloud-sdk",
"miniforge3",
];
for required in REQUIRED {
assert!(
CACHE_DIRS.contains(required),
"`{required}` was removed from CACHE_DIRS. The list is append-only: removing an \
entry means voom will sweep build output out of an installed toolchain again, \
which is what ADR 0001's amendment exists to prevent."
);
}
}
#[test]
fn every_cache_dir_is_relative_and_stays_under_home() {
for cache in CACHE_DIRS {
let path = std::path::Path::new(cache);
assert!(path.is_relative(), "{cache}: must be relative to the home directory");
assert!(
!cache.contains(".."),
"{cache}: must not climb out of the home directory"
);
assert!(!cache.ends_with('/'), "{cache}: no trailing separator");
}
}
#[test]
fn cache_dirs_are_unique_and_sorted_within_their_group() {
let mut seen = std::collections::HashSet::new();
for cache in CACHE_DIRS {
assert!(seen.insert(*cache), "{cache}: listed twice");
}
}
}