use crate::utils::{format_bytes, get_directory_size_parallel, home_dir};
use anyhow::Result;
use colored::Colorize;
use rayon::prelude::*;
use serde::Serialize;
use std::ffi::OsString;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Serialize)]
pub struct CacheEntry {
pub id: String,
pub name: String,
pub category: String,
pub risk: String,
#[serde(skip)]
paths: Vec<PathBuf>,
pub size_bytes: u64,
pub note: Option<String>,
}
impl CacheEntry {
fn new(id: &str, name: &str, category: &str, risk: &str, paths: Vec<PathBuf>) -> Self {
Self {
id: id.to_string(),
name: name.to_string(),
category: category.to_string(),
risk: risk.to_string(),
paths,
size_bytes: 0,
note: None,
}
}
fn with_note(mut self, note: &str) -> Self {
self.note = Some(note.to_string());
self
}
}
#[derive(Debug, Serialize)]
pub struct CacheCleanResult {
pub id: String,
pub name: String,
pub success: bool,
pub freed_bytes: u64,
pub error: Option<String>,
}
pub fn build_registry() -> Vec<CacheEntry> {
let home = match home_dir() {
Some(h) => h,
None => return Vec::new(),
};
let xdg = env_base_dir(
std::env::var_os("XDG_CACHE_HOME"),
home.join(".cache"),
);
let mac = home.join("Library/Caches");
let win_local = env_base_dir(
std::env::var_os("LOCALAPPDATA"),
home.join("AppData/Local"),
);
let app_support = home.join("Library/Application Support");
let config = env_base_dir(
std::env::var_os("XDG_CONFIG_HOME"),
home.join(".config"),
);
let win_roaming = env_base_dir(
std::env::var_os("APPDATA"),
home.join("AppData/Roaming"),
);
build_registry_for(&home, &xdg, &mac, &win_local, &app_support, &config, &win_roaming)
}
fn env_base_dir(env: Option<OsString>, fallback: PathBuf) -> PathBuf {
env.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or(fallback)
}
fn build_registry_for(
home: &Path,
xdg: &Path,
mac: &Path,
win_local: &Path,
app_support: &Path,
config: &Path,
win_roaming: &Path,
) -> Vec<CacheEntry> {
let vscode_paths = vscode_family_paths(app_support, config, win_roaming);
vec![
CacheEntry::new(
"cargo-cache",
"Cargo registry cache",
"Rust",
"safe",
vec![home.join(".cargo/registry/cache")],
),
CacheEntry::new(
"cargo-src",
"Cargo registry src",
"Rust",
"heavy",
vec![home.join(".cargo/registry/src")],
)
.with_note("Unpacked crate sources; re-extracts on next build"),
CacheEntry::new(
"cargo-git",
"Cargo git checkouts",
"Rust",
"safe",
vec![home.join(".cargo/git")],
)
.with_note("Git dep checkouts; re-clones on next build"),
CacheEntry::new(
"sccache",
"sccache",
"Rust",
"safe",
vec![
mac.join("Mozilla.sccache"),
xdg.join("sccache"),
win_local.join("Mozilla/sccache"),
],
),
CacheEntry::new(
"pip",
"pip",
"Python",
"safe",
vec![mac.join("pip"), xdg.join("pip"), win_local.join("pip")],
),
CacheEntry::new(
"uv",
"uv",
"Python",
"safe",
vec![
xdg.join("uv"),
mac.join("uv"),
win_local.join("uv"),
],
),
CacheEntry::new(
"poetry",
"Poetry",
"Python",
"safe",
vec![
mac.join("pypoetry"),
xdg.join("pypoetry"),
win_local.join("pypoetry"),
],
),
CacheEntry::new(
"conda",
"Conda pkgs",
"Python",
"safe",
vec![
home.join("anaconda3/pkgs"),
home.join("miniconda3/pkgs"),
home.join("miniforge3/pkgs"),
home.join(".conda/pkgs"),
],
)
.with_note("Package cache; re-downloads on env create (envs unaffected)"),
CacheEntry::new(
"npm",
"npm",
"JS/TS",
"safe",
vec![
home.join(".npm/_cacache"),
home.join(".npm/_npx"),
win_local.join("npm-cache"),
],
),
CacheEntry::new(
"bun",
"Bun install cache",
"JS/TS",
"safe",
vec![home.join(".bun/install/cache"), mac.join("bun")],
),
CacheEntry::new(
"pnpm",
"pnpm store",
"JS/TS",
"safe",
vec![
home.join(".local/share/pnpm"),
home.join("Library/pnpm"),
win_local.join("pnpm"),
],
),
CacheEntry::new(
"yarn",
"Yarn cache",
"JS/TS",
"safe",
vec![
mac.join("Yarn"),
home.join(".yarn"),
win_local.join("Yarn"),
],
),
CacheEntry::new(
"deno",
"Deno",
"JS/TS",
"safe",
vec![mac.join("deno"), xdg.join("deno"), win_local.join("deno")],
),
CacheEntry::new(
"node-gyp",
"node-gyp",
"JS/TS",
"safe",
vec![
mac.join("node-gyp"),
xdg.join("node-gyp"),
win_local.join("node-gyp"),
],
),
CacheEntry::new("vercel", "Vercel CLI", "JS/TS", "safe", vec![mac.join("com.vercel.cli")]),
CacheEntry::new(
"prisma",
"Prisma engines",
"JS/TS",
"heavy",
vec![xdg.join("prisma"), mac.join("prisma")],
)
.with_note("Engine binaries; re-downloads on next prisma generate"),
CacheEntry::new(
"chrome-devtools-mcp",
"Chrome DevTools MCP",
"JS/TS",
"heavy",
vec![xdg.join("chrome-devtools-mcp")],
)
.with_note("Chrome-for-testing binaries; re-downloads on next run"),
CacheEntry::new(
"selenium",
"Selenium Manager",
"JS/TS",
"heavy",
vec![xdg.join("selenium")],
)
.with_note("Browser/driver binaries; re-downloads on next run"),
CacheEntry::new(
"nuget",
"NuGet packages",
".NET",
"safe",
vec![home.join(".nuget/packages")],
)
.with_note("Global package cache; re-downloads on next restore"),
CacheEntry::new(
"homebrew",
"Homebrew",
"Other",
"safe",
vec![mac.join("Homebrew")],
),
CacheEntry::new(
"puppeteer",
"Puppeteer (Chrome)",
"Other",
"heavy",
vec![xdg.join("puppeteer")],
)
.with_note("Browser binaries; re-downloads on next run"),
CacheEntry::new(
"playwright",
"Playwright browsers",
"Other",
"heavy",
vec![
mac.join("ms-playwright"),
mac.join("ms-playwright-mcp"),
xdg.join("ms-playwright"),
xdg.join("ms-playwright-mcp"),
win_local.join("ms-playwright"),
win_local.join("ms-playwright-mcp"),
],
)
.with_note("Browser binaries; re-downloads on next run"),
CacheEntry::new(
"huggingface",
"HuggingFace",
"Other",
"heavy",
vec![xdg.join("huggingface")],
)
.with_note("Model weights; re-downloads on demand"),
CacheEntry::new(
"torch",
"PyTorch models",
"Other",
"heavy",
vec![xdg.join("torch")],
)
.with_note("Model weights; re-downloads on demand"),
CacheEntry::new(
"go-build",
"Go build cache",
"Other",
"safe",
vec![
mac.join("go-build"),
xdg.join("go-build"),
win_local.join("go-build"),
],
),
CacheEntry::new(
"go-mod",
"Go module cache",
"Other",
"safe",
vec![home.join("go/pkg/mod")],
)
.with_note("Re-downloads modules on next build"),
CacheEntry::new(
"gradle",
"Gradle",
"Java",
"safe",
vec![home.join(".gradle/caches")],
)
.with_note("Build + dependency caches; regenerates on next build"),
CacheEntry::new(
"maven",
"Maven",
"Java",
"safe",
vec![home.join(".m2/repository")],
)
.with_note("Re-downloads artifacts on next build"),
CacheEntry::new(
"javasharedresources",
"JVM shared class cache",
"Java",
"safe",
vec![xdg.join("javasharedresources"), mac.join("javasharedresources")],
)
.with_note("IBM/Semeru shared class cache; rebuilt on next run"),
CacheEntry::new(
"xcode-deriveddata",
"Xcode DerivedData",
"Apple",
"safe",
vec![home.join("Library/Developer/Xcode/DerivedData")],
)
.with_note("Build artifacts; recompiles on next build"),
CacheEntry::new(
"xcode-devicesupport",
"Xcode DeviceSupport",
"Apple",
"safe",
vec![
home.join("Library/Developer/Xcode/iOS DeviceSupport"),
home.join("Library/Developer/Xcode/macOS DeviceSupport"),
home.join("Library/Developer/Xcode/tvOS DeviceSupport"),
home.join("Library/Developer/Xcode/watchOS DeviceSupport"),
home.join("Library/Developer/Xcode/visionOS DeviceSupport"),
],
)
.with_note("Device symbol caches; regenerated on next device connect"),
CacheEntry::new(
"coresimulator",
"iOS Simulator",
"Apple",
"heavy",
vec![home.join("Library/Developer/CoreSimulator")],
)
.with_note("Simulator runtimes + devices; recreates via Xcode"),
CacheEntry::new(
"swiftpm",
"SwiftPM",
"Apple",
"safe",
vec![
mac.join("org.swift.swiftpm"),
home.join("Library/org.swift.swiftpm"),
xdg.join("org.swift.swiftpm"),
],
)
.with_note("Dependency clones + module cache; re-fetches on resolve"),
CacheEntry::new(
"cocoapods",
"CocoaPods",
"Apple",
"safe",
vec![home.join(".cocoapods"), mac.join("CocoaPods")],
)
.with_note("Specs repo + cache; re-fetches on next pod install"),
CacheEntry::new(
"cypress",
"Cypress",
"JS/TS",
"heavy",
vec![
mac.join("Cypress"),
xdg.join("Cypress"),
win_local.join("Cypress/Cache"),
],
)
.with_note("Browser binaries; re-downloads on next run"),
CacheEntry::new(
"electron",
"Electron",
"JS/TS",
"heavy",
vec![
mac.join("electron"),
xdg.join("electron"),
win_local.join("electron/Cache"),
],
)
.with_note("Electron binaries; re-downloads on next install"),
CacheEntry::new(
"codex-runtimes",
"Codex runtimes",
"Other",
"heavy",
vec![xdg.join("codex-runtimes")],
)
.with_note("Agent runtimes; re-fetches on next session"),
CacheEntry::new(
"jetbrains",
"JetBrains IDEs",
"IDE",
"safe",
vec![
mac.join("JetBrains"),
xdg.join("JetBrains"),
win_local.join("JetBrains"),
],
)
.with_note("Index + log caches; IDEs reindex on next launch"),
CacheEntry::new(
"vscode-family",
"VS Code-family editor caches",
"IDE",
"safe",
vscode_paths,
)
.with_note("Chromium caches, logs, extension installers; editors regenerate"),
CacheEntry::new("bazel", "Bazel", "Other", "safe", vec![xdg.join("bazel"), mac.join("bazel")])
.with_note("output_user_root; next build starts cold"),
CacheEntry::new("zig", "Zig", "Other", "safe", vec![xdg.join("zig"), mac.join("zig")]),
CacheEntry::new("gh", "GitHub CLI", "Other", "safe", vec![xdg.join("gh"), mac.join("gh")]),
CacheEntry::new(
"chroma",
"ChromaDB models",
"Other",
"heavy",
vec![xdg.join("chroma")],
)
.with_note("Embedding models; re-downloads on demand"),
CacheEntry::new(
"opencode",
"opencode",
"Other",
"heavy",
vec![xdg.join("opencode"), mac.join("opencode")],
)
.with_note("Agent caches; re-fetches on next session"),
]
}
fn vscode_family_paths(app_support: &Path, config: &Path, win_roaming: &Path) -> Vec<PathBuf> {
const APPS: &[&str] = &[
"Code",
"Code - Insiders",
"VSCodium",
"Cursor",
"Windsurf",
"Trae",
"Qoder",
"Positron",
"Kiro",
"Void",
];
const SUBDIRS: &[&str] = &[
"Cache",
"CachedData",
"Code Cache",
"GPUCache",
"CachedExtensionVSIXs",
"logs",
];
[app_support, config, win_roaming]
.iter()
.flat_map(|base| {
APPS.iter().flat_map(move |app| {
SUBDIRS.iter().map(move |sub| base.join(app).join(sub))
})
})
.collect()
}
pub fn discover_caches() -> Vec<CacheEntry> {
let mut entries = build_registry();
entries.par_iter_mut().for_each(|e| {
e.size_bytes = e
.paths
.iter()
.filter(|p| p.exists())
.map(|p| get_directory_size_parallel(p))
.sum();
});
entries.into_iter().filter(|e| e.size_bytes > 0).collect()
}
fn remove_path(p: &Path) -> std::io::Result<()> {
if p.is_dir() {
std::fs::remove_dir_all(p)
} else if p.is_file() {
std::fs::remove_file(p)
} else {
Ok(())
}
}
pub fn clean_caches(entries: &[CacheEntry], dry_run: bool) -> Vec<CacheCleanResult> {
entries
.par_iter()
.map(|e| {
let freed = e.size_bytes;
if dry_run {
return CacheCleanResult {
id: e.id.clone(),
name: e.name.clone(),
success: true,
freed_bytes: freed,
error: None,
};
}
let mut error = None;
let mut success = true;
for p in &e.paths {
if p.exists()
&& let Err(err) = remove_path(p)
{
success = false;
error = Some(format!("{}: {}", p.display(), err));
}
}
CacheCleanResult {
id: e.id.clone(),
name: e.name.clone(),
success,
freed_bytes: freed,
error,
}
})
.collect()
}
pub fn parse_selection(input: &str, count: usize) -> Vec<usize> {
let mut seen = std::collections::HashSet::new();
let mut out = Vec::new();
for token in input.split(|c: char| c == ',' || c.is_whitespace()) {
if let Ok(n) = token.trim().parse::<usize>()
&& n >= 1
&& n <= count
&& seen.insert(n - 1)
{
out.push(n - 1);
}
}
out
}
fn print_cache_list(caches: &[CacheEntry]) {
println!("{} Available caches to clean:", "[INFO]".blue().bold());
println!();
println!(
" {:>3} {:<26} {:<10} {:<6} {:>10}",
"#", "Cache", "Category", "Risk", "Size"
);
for (i, c) in caches.iter().enumerate() {
println!(
" {:>3} {:<26} {:<10} {:<6} {:>10}",
i + 1,
c.name,
c.category,
c.risk,
format_bytes(c.size_bytes)
);
if let Some(ref note) = c.note {
println!(" {}", note.dimmed());
}
}
}
fn print_cache_results(results: &[CacheCleanResult]) {
println!();
println!("{} === CACHE CLEAN SUMMARY ===", "[INFO]".blue().bold());
let total_freed: u64 = results.iter().map(|r| r.freed_bytes).sum();
let ok = results.iter().filter(|r| r.success).count();
let failed = results.len() - ok;
for r in results {
if r.success {
println!(
" {} {} (freed: {})",
"✓".green(),
r.name,
format_bytes(r.freed_bytes)
);
} else {
println!(
" {} {} - {}",
"✗".red(),
r.name,
r.error.as_deref().unwrap_or("failed")
);
}
}
println!();
if failed == 0 {
println!(
"{} Cleaned {} cache(s), freed {}",
"[SUCCESS]".green().bold(),
ok,
format_bytes(total_freed)
);
} else {
println!(
"{} Cleaned {}, failed {}, freed {}",
"[INFO]".blue().bold(),
ok,
failed,
format_bytes(total_freed)
);
}
}
fn prompt_selection(count: usize) -> Result<Vec<usize>> {
print!("Select caches to clean (comma-separated numbers, 'all', or 'q' to quit): ");
io::stdout().flush()?;
let mut line = String::new();
io::stdin().lock().read_line(&mut line)?;
let trimmed = line.trim().to_ascii_lowercase();
match trimmed.as_str() {
"q" | "quit" | "exit" | "n" | "" => Ok(Vec::new()),
"all" | "a" | "y" | "yes" => Ok((0..count).collect()),
other => Ok(parse_selection(other, count)),
}
}
fn confirm() -> Result<bool> {
print!("Proceed? [y/N]: ");
io::stdout().flush()?;
let mut line = String::new();
io::stdin().lock().read_line(&mut line)?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
fn select_safe_caches(caches: &[CacheEntry]) -> Vec<CacheEntry> {
caches
.iter()
.filter(|c| c.risk == "safe")
.cloned()
.collect()
}
pub fn run_cache_mode(dry_run: bool, json: bool, all: bool) -> Result<()> {
let caches = discover_caches();
if caches.is_empty() {
if json {
println!("[]");
} else {
println!("{} No caches found to clean", "[INFO]".blue().bold());
}
return Ok(());
}
if all {
return run_cache_all_mode(&caches, dry_run, json);
}
if json {
println!("{}", serde_json::to_string_pretty(&caches)?);
return Ok(());
}
print_cache_list(&caches);
let total: u64 = caches.iter().map(|c| c.size_bytes).sum();
println!();
println!(" Total reclaimable: {}", format_bytes(total).bold());
println!();
let selection = prompt_selection(caches.len())?;
if selection.is_empty() {
println!("{} Cancelled", "[INFO]".blue().bold());
return Ok(());
}
let selected: Vec<CacheEntry> = selection
.iter()
.filter_map(|&i| caches.get(i).cloned())
.collect();
let sel_total: u64 = selected.iter().map(|c| c.size_bytes).sum();
println!();
println!(
"{} About to clean {} cache(s), freeing ~{}",
"[INFO]".cyan().bold(),
selected.len(),
format_bytes(sel_total)
);
if dry_run {
println!(
"{} DRY RUN MODE - no changes will be made",
"[INFO]".yellow().bold()
);
} else if !confirm()? {
println!("{} Cancelled by user", "[INFO]".blue().bold());
return Ok(());
}
let results = clean_caches(&selected, dry_run);
print_cache_results(&results);
if results.iter().any(|r| !r.success) {
std::process::exit(1);
}
Ok(())
}
fn run_cache_all_mode(caches: &[CacheEntry], dry_run: bool, json: bool) -> Result<()> {
let safe = select_safe_caches(caches);
if json {
let results = clean_caches(&safe, dry_run);
println!("{}", serde_json::to_string_pretty(&results)?);
if results.iter().any(|r| !r.success) {
std::process::exit(1);
}
return Ok(());
}
if safe.is_empty() {
println!(
"{} No safe caches found to clean (heavy caches require interactive --caches)",
"[INFO]".blue().bold()
);
return Ok(());
}
print_cache_list(&safe);
let total: u64 = safe.iter().map(|c| c.size_bytes).sum();
println!();
println!(
"{} Cleaning all {} safe cache(s), freeing ~{}",
"[INFO]".cyan().bold(),
safe.len(),
format_bytes(total)
);
if dry_run {
println!(
"{} DRY RUN MODE - no changes will be made",
"[INFO]".yellow().bold()
);
}
println!(
"{} Heavy caches skipped — clean them interactively with --caches",
"[INFO]".blue().bold()
);
let results = clean_caches(&safe, dry_run);
print_cache_results(&results);
if results.iter().any(|r| !r.success) {
std::process::exit(1);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::utils::get_directory_size;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_build_registry_has_known_caches() {
let reg = build_registry();
assert!(!reg.is_empty());
let ids: Vec<_> = reg.iter().map(|e| e.id.as_str()).collect();
assert!(ids.contains(&"npm"));
assert!(ids.contains(&"cargo-cache"));
assert!(ids.contains(&"huggingface"));
}
#[test]
fn test_parse_selection_basic() {
assert_eq!(parse_selection("1,3", 5), vec![0, 2]);
assert_eq!(parse_selection("1 3", 5), vec![0, 2]);
}
#[test]
fn test_parse_selection_out_of_range() {
assert!(parse_selection("0", 5).is_empty());
assert!(parse_selection("6", 5).is_empty());
}
#[test]
fn test_parse_selection_dedup() {
assert_eq!(parse_selection("1,1,2", 5), vec![0, 1]);
}
#[test]
fn test_parse_selection_invalid_ignored() {
assert_eq!(parse_selection("1,foo,3", 5), vec![0, 2]);
}
#[test]
fn test_clean_caches_removes_dirs() {
let temp = TempDir::new().unwrap();
let dir = temp.path().join("npm_cache");
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("a"), "hello world").unwrap();
let size = get_directory_size(&dir).unwrap();
let entry = CacheEntry {
id: "test".into(),
name: "test".into(),
category: "Test".into(),
risk: "safe".into(),
paths: vec![dir.clone()],
size_bytes: size,
note: None,
};
let results = clean_caches(&[entry], false);
assert_eq!(results.len(), 1);
assert!(results[0].success);
assert_eq!(results[0].freed_bytes, size);
assert!(!dir.exists());
}
#[test]
fn test_clean_caches_dry_run_keeps_dirs() {
let temp = TempDir::new().unwrap();
let dir = temp.path().join("cache");
fs::create_dir_all(&dir).unwrap();
fs::write(dir.join("a"), "data").unwrap();
let size = get_directory_size(&dir).unwrap();
let entry = CacheEntry {
id: "test".into(),
name: "test".into(),
category: "Test".into(),
risk: "safe".into(),
paths: vec![dir.clone()],
size_bytes: size,
note: None,
};
let results = clean_caches(&[entry], true);
assert!(results[0].success);
assert!(dir.exists(), "dry run should not delete");
}
#[test]
fn test_clean_caches_multiple_paths() {
let temp = TempDir::new().unwrap();
let dir1 = temp.path().join("cache1");
let dir2 = temp.path().join("cache2");
fs::create_dir_all(&dir1).unwrap();
fs::create_dir_all(&dir2).unwrap();
fs::write(dir1.join("a"), "aaa").unwrap();
fs::write(dir2.join("b"), "bbbbbb").unwrap();
let size = get_directory_size(&dir1).unwrap() + get_directory_size(&dir2).unwrap();
let entry = CacheEntry {
id: "multi".into(),
name: "multi".into(),
category: "Test".into(),
risk: "safe".into(),
paths: vec![dir1.clone(), dir2.clone()],
size_bytes: size,
note: None,
};
let results = clean_caches(&[entry], false);
assert!(results[0].success);
assert_eq!(results[0].freed_bytes, size);
assert!(!dir1.exists());
assert!(!dir2.exists());
}
#[test]
fn test_clean_caches_nonexistent_paths_succeeds() {
let entry = CacheEntry {
id: "ghost".into(),
name: "ghost".into(),
category: "Test".into(),
risk: "safe".into(),
paths: vec![PathBuf::from("/nonexistent/path/that/does/not/exist")],
size_bytes: 100,
note: None,
};
let results = clean_caches(&[entry], false);
assert!(results[0].success, "non-existent paths should not cause failure");
}
#[test]
fn test_clean_caches_empty_entries() {
let results = clean_caches(&[], false);
assert!(results.is_empty());
}
#[test]
fn test_registry_risk_values_valid() {
let reg = build_registry();
for entry in ® {
assert!(
entry.risk == "safe" || entry.risk == "heavy",
"entry {} has invalid risk: {}",
entry.id,
entry.risk
);
}
}
#[test]
fn test_registry_unique_ids() {
let reg = build_registry();
let mut ids: Vec<&str> = reg.iter().map(|e| e.id.as_str()).collect();
ids.sort();
let len_before = ids.len();
ids.dedup();
assert_eq!(
ids.len(),
len_before,
"registry has duplicate cache IDs"
);
}
#[test]
fn test_registry_all_categories_nonempty() {
let reg = build_registry();
for entry in ® {
assert!(!entry.category.is_empty(), "entry {} has empty category", entry.id);
assert!(!entry.name.is_empty(), "entry {} has empty name", entry.id);
}
}
#[test]
fn test_remove_path_on_file() {
let temp = TempDir::new().unwrap();
let file = temp.path().join("single_file");
fs::write(&file, "data").unwrap();
assert!(file.is_file());
remove_path(&file).unwrap();
assert!(!file.exists());
}
#[test]
fn test_remove_path_nonexistent_is_ok() {
let result = remove_path(Path::new("/nonexistent/path"));
assert!(result.is_ok());
}
#[test]
fn test_parse_selection_all_tokens() {
assert_eq!(parse_selection("1,2,3,4,5", 5), vec![0, 1, 2, 3, 4]);
}
#[test]
fn test_parse_selection_mixed_separators() {
assert_eq!(parse_selection("1, 2 3", 5), vec![0, 1, 2]);
}
#[test]
fn test_parse_selection_empty() {
assert!(parse_selection("", 5).is_empty());
}
#[test]
fn test_env_base_dir_treats_empty_as_unset() {
let fallback = PathBuf::from("/fallback");
assert_eq!(env_base_dir(None, fallback.clone()), fallback);
assert_eq!(env_base_dir(Some("".into()), fallback.clone()), fallback);
assert_eq!(
env_base_dir(Some("/custom".into()), fallback),
PathBuf::from("/custom")
);
}
fn reg(home: &Path) -> Vec<CacheEntry> {
build_registry_for(
home,
&home.join(".cache"),
&home.join("Library/Caches"),
&home.join("AppData/Local"),
&home.join("Library/Application Support"),
&home.join(".config"),
&home.join("AppData/Roaming"),
)
}
#[test]
fn test_registry_windows_localappdata_paths() {
let home = PathBuf::from("/home/t");
let win_local = home.join("AppData/Local");
let reg = reg(&home);
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
assert!(find("npm").paths.contains(&win_local.join("npm-cache")));
assert!(find("pip").paths.contains(&win_local.join("pip")));
assert!(find("uv").paths.contains(&win_local.join("uv")));
assert!(find("poetry").paths.contains(&win_local.join("pypoetry")));
assert!(find("pnpm").paths.contains(&win_local.join("pnpm")));
assert!(find("yarn").paths.contains(&win_local.join("Yarn")));
assert!(find("playwright").paths.contains(&win_local.join("ms-playwright")));
assert!(find("go-build").paths.contains(&win_local.join("go-build")));
}
#[test]
fn test_registry_xdg_default_covers_windows_dotcache() {
let home = PathBuf::from("/home/t");
let reg = reg(&home);
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
assert!(find("puppeteer").paths.contains(&home.join(".cache/puppeteer")));
assert!(find("huggingface").paths.contains(&home.join(".cache/huggingface")));
assert!(find("torch").paths.contains(&home.join(".cache/torch")));
}
#[test]
fn test_registry_cargo_and_bun_are_home_based_on_all_platforms() {
let home = PathBuf::from("/home/t");
let reg = reg(&home);
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
assert!(find("cargo-cache").paths.contains(&home.join(".cargo/registry/cache")));
assert!(find("bun").paths.contains(&home.join(".bun/install/cache")));
}
#[test]
fn test_registry_tier1_paths() {
let home = PathBuf::from("/home/t");
let mac = home.join("Library/Caches");
let xdg = home.join(".cache");
let win_local = home.join("AppData/Local");
let reg = reg(&home);
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
assert!(find("xcode-deriveddata")
.paths
.contains(&home.join("Library/Developer/Xcode/DerivedData")));
assert!(find("gradle").paths.contains(&home.join(".gradle/caches")));
assert!(find("maven").paths.contains(&home.join(".m2/repository")));
assert!(find("go-mod").paths.contains(&home.join("go/pkg/mod")));
let cypress = find("cypress");
assert!(cypress.paths.contains(&mac.join("Cypress")));
assert!(cypress.paths.contains(&xdg.join("Cypress")));
assert!(cypress.paths.contains(&win_local.join("Cypress/Cache")));
let electron = find("electron");
assert!(electron.paths.contains(&mac.join("electron")));
assert!(electron.paths.contains(&xdg.join("electron")));
assert!(electron.paths.contains(&win_local.join("electron/Cache")));
}
#[test]
fn test_registry_tier1_risk_and_category() {
let reg = build_registry();
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
for id in ["gradle", "maven", "go-mod", "xcode-deriveddata"] {
assert_eq!(find(id).risk, "safe", "{} should be safe", id);
}
for id in ["cypress", "electron"] {
assert_eq!(find(id).risk, "heavy", "{} should be heavy", id);
}
assert_eq!(find("xcode-deriveddata").category, "Apple");
assert_eq!(find("gradle").category, "Java");
assert_eq!(find("maven").category, "Java");
}
#[test]
fn test_select_safe_caches_filters_heavy() {
let mk = |id: &str, risk: &str| CacheEntry {
id: id.into(),
name: id.into(),
category: "T".into(),
risk: risk.into(),
paths: vec![],
size_bytes: 10,
note: None,
};
let caches = vec![mk("a", "safe"), mk("b", "heavy"), mk("c", "safe")];
let safe = select_safe_caches(&caches);
let ids: Vec<_> = safe.iter().map(|c| c.id.as_str()).collect();
assert_eq!(ids, vec!["a", "c"]);
assert!(select_safe_caches(&[]).is_empty());
let heavy_only = vec![mk("h", "heavy")];
assert!(select_safe_caches(&heavy_only).is_empty());
}
#[test]
fn test_registry_tier2_paths() {
let home = PathBuf::from("/home/t");
let mac = home.join("Library/Caches");
let xdg = home.join(".cache");
let win_local = home.join("AppData/Local");
let app_support = home.join("Library/Application Support");
let config = home.join(".config");
let win_roaming = home.join("AppData/Roaming");
let reg = reg(&home);
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
assert!(find("cargo-git").paths.contains(&home.join(".cargo/git")));
assert!(find("sccache").paths.contains(&mac.join("Mozilla.sccache")));
assert!(find("sccache").paths.contains(&win_local.join("Mozilla/sccache")));
assert!(find("nuget").paths.contains(&home.join(".nuget/packages")));
assert!(find("conda").paths.contains(&home.join("miniconda3/pkgs")));
assert!(find("deno").paths.contains(&xdg.join("deno")));
assert!(find("playwright").paths.contains(&mac.join("ms-playwright-mcp")));
assert!(find("playwright").paths.contains(&win_local.join("ms-playwright-mcp")));
assert!(find("coresimulator")
.paths
.contains(&home.join("Library/Developer/CoreSimulator")));
assert!(find("xcode-devicesupport")
.paths
.contains(&home.join("Library/Developer/Xcode/iOS DeviceSupport")));
assert!(find("xcode-devicesupport")
.paths
.contains(&home.join("Library/Developer/Xcode/visionOS DeviceSupport")));
assert!(find("swiftpm").paths.contains(&mac.join("org.swift.swiftpm")));
assert!(find("swiftpm").paths.contains(&home.join("Library/org.swift.swiftpm")));
assert!(find("cocoapods").paths.contains(&home.join(".cocoapods")));
assert!(find("jetbrains").paths.contains(&mac.join("JetBrains")));
let vscode = find("vscode-family");
assert!(vscode.paths.contains(&app_support.join("Code/Cache")));
assert!(vscode.paths.contains(&app_support.join("Cursor/CachedData")));
assert!(vscode.paths.contains(&config.join("Code/Code Cache")));
assert!(vscode.paths.contains(&config.join("Windsurf/logs")));
assert!(vscode.paths.contains(&win_roaming.join("Code/CachedExtensionVSIXs")));
assert!(vscode.paths.contains(&win_roaming.join("Trae/GPUCache")));
}
#[test]
fn test_registry_tier2_risk_and_category() {
let reg = build_registry();
let find = |id: &str| {
reg.iter()
.find(|e| e.id == id)
.unwrap_or_else(|| panic!("missing entry {}", id))
};
for id in [
"prisma",
"chrome-devtools-mcp",
"selenium",
"coresimulator",
"chroma",
"opencode",
] {
assert_eq!(find(id).risk, "heavy", "{} should be heavy", id);
}
for id in [
"cargo-git",
"sccache",
"conda",
"deno",
"node-gyp",
"vercel",
"nuget",
"javasharedresources",
"xcode-devicesupport",
"swiftpm",
"cocoapods",
"jetbrains",
"vscode-family",
"bazel",
"zig",
"gh",
] {
assert_eq!(find(id).risk, "safe", "{} should be safe", id);
}
assert_eq!(find("nuget").category, ".NET");
assert_eq!(find("jetbrains").category, "IDE");
assert_eq!(find("vscode-family").category, "IDE");
assert_eq!(find("coresimulator").category, "Apple");
}
}