use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant, SystemTime};
pub use kuizer::caches::guard_roots as cache_roots;
pub use kuizer::delete::Batch;
pub use kuizer::source::Source;
use kuizer::big::{self, LargeFile};
use kuizer::caches::{self, KnownCache, Locations};
use kuizer::config::{Config, DeleteConfig, DeleteMode, Excludes};
use kuizer::delete::{Executor, Removal, Status};
use kuizer::detect::Category;
use kuizer::docker;
use kuizer::dupes::{self, Duplicates, Options};
use kuizer::history::restore::Status as RestoreStatus;
use kuizer::history::{self, Action, History, TrashSnapshot, TrashView};
use kuizer::platform::{self, display_path};
use kuizer::protect::Protected;
use kuizer::repos::{self, Repository};
use kuizer::scan::{self, Cancel, Candidate, Issue, Progress, SortKey, Summary, sort_candidates};
use kuizer::system;
use kuizer::toolchains::{self, Toolchain};
use kuizer::trashcan;
use kuizer::usage::{self, MeasureConfig, UsageOptions, UsageTree, WalkDiagnostics};
use crate::activity::{self, Found, Step, Tracker, grouped, plural};
use crate::start::ScanOptions;
use crate::stats::HistoryStats;
use crate::theme;
pub const CANCELLED: &str = "cancelled";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Part {
Artifacts,
Caches,
Toolchains,
Docker,
Repos,
Trash,
System,
Big,
Usage,
History,
}
impl Part {
pub fn expected(options: &ScanOptions) -> HashSet<Part> {
[
(true, Self::Artifacts),
(options.caches, Self::Caches),
(options.toolchains, Self::Toolchains),
(options.docker, Self::Docker),
(options.repos, Self::Repos),
(options.trash, Self::Trash),
(options.system, Self::System),
(options.big, Self::Big),
(options.usage, Self::Usage),
(true, Self::History),
]
.into_iter()
.filter_map(|(on, part)| on.then_some(part))
.collect()
}
pub fn source(self) -> Option<Source> {
match self {
Self::Artifacts => Some(Source::Artifact),
Self::Caches => Some(Source::Cache),
Self::Toolchains => Some(Source::Toolchain),
Self::Docker => Some(Source::Docker),
Self::Trash => Some(Source::Trash),
Self::Big => Some(Source::Big),
Self::System => Some(Source::System),
Self::Repos | Self::Usage | Self::History => None,
}
}
}
pub enum Loaded {
Found(Vec<Candidate>),
Artifacts {
candidates: Vec<Candidate>,
issues: Vec<Issue>,
summary: Summary,
disks: Vec<Disk>,
},
ArtifactsDone {
issues: Vec<Issue>,
summary: Summary,
disks: Vec<Disk>,
},
Caches(Vec<(KnownCache, Candidate)>),
Toolchains(Vec<(Toolchain, Candidate)>),
Docker {
entries: Vec<(docker::Item, Candidate)>,
issues: Vec<String>,
},
Repos(Vec<Repository>),
Trash {
entries: Vec<(trashcan::Folder, Candidate)>,
issues: Vec<Issue>,
},
System {
entries: Vec<(system::Item, Candidate)>,
issues: Vec<String>,
},
Big(Vec<Candidate>),
Usage(Option<UsageTree>),
Diagnostics(WalkDiagnostics),
History(Result<HistoryView, String>),
}
impl Loaded {
pub fn part(&self) -> Option<Part> {
match self {
Self::Found(_) | Self::Diagnostics(_) => None,
Self::Artifacts { .. } | Self::ArtifactsDone { .. } => Some(Part::Artifacts),
Self::Caches(_) => Some(Part::Caches),
Self::Toolchains(_) => Some(Part::Toolchains),
Self::Docker { .. } => Some(Part::Docker),
Self::Repos(_) => Some(Part::Repos),
Self::Trash { .. } => Some(Part::Trash),
Self::System { .. } => Some(Part::System),
Self::Big(_) => Some(Part::Big),
Self::Usage(_) => Some(Part::Usage),
Self::History(_) => Some(Part::History),
}
}
pub fn without(&mut self, excluded: &[PathBuf], gone: &HashMap<Source, HashSet<PathBuf>>) {
let source = match self {
Self::Found(_) | Self::Artifacts { .. } | Self::ArtifactsDone { .. } => {
Some(Source::Artifact)
}
Self::Caches(_) => Some(Source::Cache),
Self::Toolchains(_) => Some(Source::Toolchain),
Self::Docker { .. } => Some(Source::Docker),
Self::Trash { .. } => Some(Source::Trash),
Self::Big(_) => Some(Source::Big),
Self::System { .. } => Some(Source::System),
Self::Repos(_) | Self::Usage(_) | Self::Diagnostics(_) | Self::History(_) => None,
};
let deleted = source.and_then(|source| gone.get(&source));
if excluded.is_empty() && deleted.is_none_or(HashSet::is_empty) {
return;
}
let stays = |path: &Path| {
!deleted.is_some_and(|deleted| deleted.contains(path))
&& !excluded.iter().any(|excluded| path.starts_with(excluded))
};
match self {
Self::Found(candidates) => candidates.retain(|candidate| stays(&candidate.path)),
Self::Artifacts {
candidates, issues, ..
} => {
candidates.retain(|candidate| stays(&candidate.path));
issues.retain(|issue| stays(&issue.path));
}
Self::ArtifactsDone { issues, .. } => issues.retain(|issue| stays(&issue.path)),
Self::Caches(caches) => caches.retain(|(_, candidate)| stays(&candidate.path)),
Self::Toolchains(toolchains) => {
toolchains.retain(|(_, candidate)| stays(&candidate.path));
}
Self::Docker { entries, .. } => entries.retain(|(_, candidate)| {
!deleted.is_some_and(|deleted| deleted.contains(&candidate.path))
}),
Self::Repos(repos) => repos.retain(|repository| stays(&repository.root)),
Self::Trash { entries, .. } => entries.retain(|(_, candidate)| stays(&candidate.path)),
Self::Big(candidates) => candidates.retain(|candidate| stays(&candidate.path)),
Self::System { entries, .. } => entries.retain(|(_, candidate)| {
!deleted.is_some_and(|deleted| deleted.contains(&candidate.path))
}),
Self::Usage(tree) => {
if let Some(tree) = tree {
let mut dropped: HashSet<PathBuf> = gone
.values()
.flat_map(|paths| paths.iter().cloned())
.collect();
dropped.extend(excluded.iter().cloned());
tree.drop_paths(&dropped);
}
}
Self::Diagnostics(_) | Self::History(_) => {}
}
}
}
pub struct Disk {
pub available: Option<u64>,
pub total: Option<u64>,
}
pub use kuizer::history::TrashState;
pub struct HistoryView {
pub history: std::sync::Arc<History>,
pub trash: TrashSnapshot,
pub stats: HistoryStats,
}
impl HistoryView {
pub fn new(history: History, trash: TrashSnapshot) -> Self {
let stats = HistoryStats::of(&history, &trash);
Self {
history: std::sync::Arc::new(history),
trash,
stats,
}
}
pub fn load() -> Result<Self, String> {
let path = history::default_path().map_err(|error| error.to_string())?;
let history = history::load(&path).map_err(|error| error.to_string())?;
let trash = TrashSnapshot::read(&history);
Ok(Self::new(history, trash))
}
pub fn trash_state(&self, run: usize) -> TrashState {
self.stats
.trash
.get(run)
.copied()
.unwrap_or(TrashState::NotTrashed)
}
pub fn delete_runs(&self) -> impl DoubleEndedIterator<Item = &history::Run> {
self.history
.runs
.iter()
.filter(|run| run.action == Action::Delete)
}
}
pub struct Report {
pub roots: Vec<PathBuf>,
pub options: ScanOptions,
pub candidates: Vec<Candidate>,
pub issues: Vec<Issue>,
pub summary: Summary,
pub caches: Vec<(KnownCache, Candidate)>,
pub toolchains: Vec<(Toolchain, Candidate)>,
pub docker: Vec<(docker::Item, Candidate)>,
pub docker_issues: Vec<String>,
pub repos: Vec<Repository>,
pub trash: Vec<(trashcan::Folder, Candidate)>,
pub trash_issues: Vec<Issue>,
pub system: Vec<(system::Item, Candidate)>,
pub system_issues: Vec<String>,
pub big: Vec<Candidate>,
pub usage: Option<UsageTree>,
pub walk_diagnostics: Option<WalkDiagnostics>,
pub duplicates: Option<Duplicates>,
pub history: Result<HistoryView, String>,
pub disks: Vec<Disk>,
pub scanned: SystemTime,
}
pub struct Bucket<K> {
pub key: K,
pub bytes: u64,
pub count: usize,
}
impl Report {
pub fn empty(roots: &[PathBuf], options: &ScanOptions) -> Self {
Self {
roots: roots.to_vec(),
options: options.clone(),
candidates: Vec::new(),
issues: Vec::new(),
summary: Summary {
progress: Progress::default(),
duration: Duration::ZERO,
cancelled: false,
},
caches: Vec::new(),
toolchains: Vec::new(),
docker: Vec::new(),
docker_issues: Vec::new(),
repos: Vec::new(),
trash: Vec::new(),
trash_issues: Vec::new(),
system: Vec::new(),
system_issues: Vec::new(),
big: Vec::new(),
usage: None,
walk_diagnostics: None,
duplicates: None,
history: Err(String::new()),
disks: Vec::new(),
scanned: SystemTime::now(),
}
}
pub fn apply(&mut self, loaded: Loaded) -> Loaded {
match loaded {
Loaded::Found(batch) => {
self.candidates.extend(batch);
Loaded::Found(Vec::new())
}
Loaded::Artifacts {
candidates,
issues,
summary,
disks,
} => Loaded::Artifacts {
candidates: std::mem::replace(&mut self.candidates, candidates),
issues: std::mem::replace(&mut self.issues, issues),
summary: std::mem::replace(&mut self.summary, summary),
disks: std::mem::replace(&mut self.disks, disks),
},
Loaded::ArtifactsDone {
issues,
summary,
disks,
} => {
sort_candidates(&mut self.candidates, SortKey::Size);
Loaded::Artifacts {
candidates: Vec::new(),
issues: std::mem::replace(&mut self.issues, issues),
summary: std::mem::replace(&mut self.summary, summary),
disks: std::mem::replace(&mut self.disks, disks),
}
}
Loaded::Caches(caches) => Loaded::Caches(std::mem::replace(&mut self.caches, caches)),
Loaded::Toolchains(toolchains) => {
Loaded::Toolchains(std::mem::replace(&mut self.toolchains, toolchains))
}
Loaded::Docker { entries, issues } => Loaded::Docker {
entries: std::mem::replace(&mut self.docker, entries),
issues: std::mem::replace(&mut self.docker_issues, issues),
},
Loaded::Repos(repos) => Loaded::Repos(std::mem::replace(&mut self.repos, repos)),
Loaded::Trash { entries, issues } => Loaded::Trash {
entries: std::mem::replace(&mut self.trash, entries),
issues: std::mem::replace(&mut self.trash_issues, issues),
},
Loaded::System { entries, issues } => Loaded::System {
entries: std::mem::replace(&mut self.system, entries),
issues: std::mem::replace(&mut self.system_issues, issues),
},
Loaded::Big(big) => Loaded::Big(std::mem::replace(&mut self.big, big)),
Loaded::Usage(usage) => Loaded::Usage(std::mem::replace(&mut self.usage, usage)),
Loaded::Diagnostics(diagnostics) => {
self.walk_diagnostics = Some(diagnostics);
Loaded::Found(Vec::new())
}
Loaded::History(history) => {
Loaded::History(std::mem::replace(&mut self.history, history))
}
}
}
pub fn into_parts(self) -> Vec<Loaded> {
vec![
Loaded::Artifacts {
candidates: self.candidates,
issues: self.issues,
summary: self.summary,
disks: self.disks,
},
Loaded::Caches(self.caches),
Loaded::Toolchains(self.toolchains),
Loaded::Docker {
entries: self.docker,
issues: self.docker_issues,
},
Loaded::Repos(self.repos),
Loaded::Trash {
entries: self.trash,
issues: self.trash_issues,
},
Loaded::System {
entries: self.system,
issues: self.system_issues,
},
Loaded::Big(self.big),
Loaded::Usage(self.usage),
Loaded::History(self.history),
]
}
pub fn section(&self, source: Source) -> Box<dyn Iterator<Item = &Candidate> + '_> {
match source {
Source::Artifact => Box::new(self.candidates.iter()),
Source::Cache => Box::new(self.caches.iter().map(|(_, candidate)| candidate)),
Source::Toolchain => Box::new(self.toolchains.iter().map(|(_, candidate)| candidate)),
Source::Docker => Box::new(self.docker.iter().map(|(_, candidate)| candidate)),
Source::Trash => Box::new(self.trash.iter().map(|(_, candidate)| candidate)),
Source::Big => Box::new(self.big.iter()),
Source::System => Box::new(self.system.iter().map(|(_, candidate)| candidate)),
}
}
#[cfg(test)]
pub fn total(&self, safety: Option<kuizer::detect::Safety>) -> u64 {
self.candidates
.iter()
.filter(|candidate| safety.is_none_or(|safety| candidate.rule.safety == safety))
.map(|candidate| candidate.usage.allocated)
.sum()
}
pub fn by_category(&self) -> Vec<Bucket<Category>> {
let mut buckets: Vec<Bucket<Category>> = Category::ALL
.iter()
.map(|&key| Bucket {
key,
bytes: 0,
count: 0,
})
.collect();
for candidate in &self.candidates {
if let Some(bucket) = buckets
.iter_mut()
.find(|bucket| bucket.key == candidate.rule.category)
{
bucket.bytes += candidate.usage.allocated;
bucket.count += 1;
}
}
buckets.retain(|bucket| bucket.count > 0);
buckets.sort_by_key(|bucket| std::cmp::Reverse(bucket.bytes));
buckets
}
pub fn drop_paths(&mut self, paths: &[PathBuf]) {
if paths.is_empty() {
return;
}
let gone = |path: &Path| paths.iter().any(|excluded| path.starts_with(excluded));
self.candidates.retain(|candidate| !gone(&candidate.path));
self.caches.retain(|(_, candidate)| !gone(&candidate.path));
self.toolchains
.retain(|(_, candidate)| !gone(&candidate.path));
self.repos.retain(|repository| !gone(&repository.root));
self.trash.retain(|(_, candidate)| !gone(&candidate.path));
self.big.retain(|candidate| !gone(&candidate.path));
if let Some(usage) = &mut self.usage {
usage.drop_paths(&paths.iter().cloned().collect());
}
self.issues.retain(|issue| !gone(&issue.path));
self.trash_issues.retain(|issue| !gone(&issue.path));
if let Some(duplicates) = &mut self.duplicates {
drop_duplicate_paths(duplicates, paths);
}
}
pub fn remove(&mut self, gone: &HashMap<Source, HashSet<PathBuf>>) {
let stays = |source: Source, candidate: &Candidate| {
!gone
.get(&source)
.is_some_and(|paths| paths.contains(&candidate.path))
};
if gone.contains_key(&Source::Artifact) {
self.candidates
.retain(|candidate| stays(Source::Artifact, candidate));
}
self.caches
.retain(|(_, candidate)| stays(Source::Cache, candidate));
self.toolchains
.retain(|(_, candidate)| stays(Source::Toolchain, candidate));
self.docker
.retain(|(_, candidate)| stays(Source::Docker, candidate));
self.trash
.retain(|(_, candidate)| stays(Source::Trash, candidate));
self.big.retain(|candidate| stays(Source::Big, candidate));
self.system
.retain(|(_, candidate)| stays(Source::System, candidate));
if let Some(usage) = &mut self.usage {
let dropped: HashSet<PathBuf> = gone
.iter()
.filter(|(source, _)| !matches!(source, Source::Docker | Source::System))
.flat_map(|(_, paths)| paths.iter().cloned())
.collect();
usage.drop_paths(&dropped);
}
}
pub fn by_project(&self) -> Vec<Bucket<PathBuf>> {
let mut projects: BTreeMap<&Path, (u64, usize)> = BTreeMap::new();
for candidate in &self.candidates {
let entry = projects
.entry(candidate.project.as_deref().unwrap_or(&candidate.path))
.or_default();
entry.0 += candidate.usage.allocated;
entry.1 += 1;
}
let mut buckets: Vec<Bucket<PathBuf>> = projects
.into_iter()
.map(|(key, (bytes, count))| Bucket {
key: key.to_path_buf(),
bytes,
count,
})
.collect();
buckets.sort_by_key(|bucket| std::cmp::Reverse(bucket.bytes));
buckets
}
}
pub fn drop_duplicate_paths(duplicates: &mut Duplicates, paths: &[PathBuf]) {
if paths.is_empty() {
return;
}
let gone = |path: &Path| paths.iter().any(|excluded| path.starts_with(excluded));
for group in &mut duplicates.groups {
group.members.retain(|member| !gone(&member.path));
}
duplicates.groups.retain(|group| group.members.len() > 1);
duplicates
.groups
.sort_by_key(|group| std::cmp::Reverse(group.reclaimable()));
}
pub fn short_path(path: &Path, roots: &[PathBuf]) -> String {
let home = platform::home_dir();
roots
.iter()
.filter(|root| Some(root.as_path()) != home.as_deref())
.find_map(|root| {
path.strip_prefix(root)
.ok()
.filter(|rest| !rest.as_os_str().is_empty())
})
.map_or_else(|| display_path(path), display_path)
}
pub fn load(
config: &Config,
roots: &[PathBuf],
options: &ScanOptions,
cancel: &Cancel,
tracker: &Tracker,
emit: &(dyn Fn(Loaded) + Sync),
) -> Result<(), String> {
let config = &options.apply(config);
let scans_artifacts = options.artifacts;
let runs_usage_pass = options.usage || options.big;
let pin_search = scans_artifacts && options.toolchains && config.toolchains.pins;
let include_dev_caches = options.scans_developer_caches(config);
let started = Instant::now();
let artifact_scan = if scans_artifacts {
Some(
repos::start_scan(config, roots, cancel.clone(), None, pin_search)
.map_err(|error| error.to_string())?,
)
} else {
None
};
tracker.update_now(|activity| {
for step in Step::ALL {
if step.enabled(options) && !matches!(step, Step::Repos) {
activity.begin(step, None);
}
}
});
let finished = AtomicBool::new(false);
let result = thread::scope(|scope| {
let ticker = spawn_part(scope, "pulse", || {
while !finished.load(Ordering::Relaxed) {
thread::park_timeout(Duration::from_millis(100));
tracker.flush();
}
});
spawn_part(scope, "history", || {
let history = HistoryView::load();
tracker.update_now(|activity| {
activity.finish(
Step::History,
started.elapsed(),
match &history {
Ok(view) => plural(view.delete_runs().count(), "cleanup"),
Err(_) => "Cannot read it".to_owned(),
},
);
});
emit(Loaded::History(history));
});
if options.docker {
spawn_part(scope, "docker", || {
let listing = docker::list(
&config.docker.engines,
config.docker.timeout(),
config.docker.recent_hours,
);
tracker.update_now(|activity| {
activity.finish(
Step::Docker,
started.elapsed(),
plural(listing.items.len(), "object"),
);
});
emit(Loaded::Docker {
entries: docker::entries(listing.items),
issues: listing.issues,
});
});
}
if options.caches {
spawn_part(scope, "caches", || {
let caches = measure_caches(config, include_dev_caches, cancel, tracker);
let bytes = caches.iter().map(|(_, c)| c.usage.allocated).sum();
tracker.update_now(|activity| {
activity.finish(
Step::Caches,
started.elapsed(),
format!("{}, {}", plural(caches.len(), "cache"), theme::bytes(bytes)),
);
});
emit(Loaded::Caches(caches));
});
}
if options.trash {
spawn_part(scope, "trash", || {
let (entries, issues) = measure_trash(config, cancel);
let items = entries.iter().map(|(folder, _)| folder.items).sum();
let bytes = entries.iter().map(|(_, c)| c.usage.allocated).sum();
tracker.update_now(|activity| {
activity.finish(
Step::Trash,
started.elapsed(),
format!("{}, {}", plural(items, "item"), theme::bytes(bytes)),
);
});
emit(Loaded::Trash { entries, issues });
});
}
if options.system {
spawn_part(scope, "system", || {
let listing = system::for_user(&config.system);
let entries = system::entries(listing.items);
let bytes = entries.iter().map(|(_, c)| c.usage.allocated).sum();
tracker.update_now(|activity| {
activity.finish(
Step::System,
started.elapsed(),
format!("{}, {}", plural(entries.len(), "item"), theme::bytes(bytes)),
);
});
emit(Loaded::System {
entries,
issues: listing.issues,
});
});
}
let usage_pass = runs_usage_pass.then(|| {
spawn_part(scope, "usage", move || {
let usage_opts = if options.usage {
UsageOptions {
one_file_system: config.scan.one_file_system,
..UsageOptions::default()
}
} else {
UsageOptions {
max_depth: config.scan.max_depth.unwrap_or(6),
max_children: 32,
min_bytes: config.big.min_size.0.min(1_000_000),
one_file_system: config.scan.one_file_system,
}
};
let mut report = usage::measure_report(
roots,
config,
&MeasureConfig {
usage: usage_opts,
collect_large_files: options.big,
collect_large_folders: options.big,
large_min_size: config.big.min_size.0,
large_limit: config.big.limit,
},
cancel,
|dirs, bytes| {
tracker.update(|activity| activity.measured(Step::Usage, dirs, bytes));
},
);
let issues = if scans_artifacts {
Vec::new()
} else {
report.tree.issues.clone()
};
let diagnostics = report.diagnostics.clone();
emit(Loaded::Diagnostics(diagnostics.clone()));
if options.usage {
tracker.update_now(|activity| {
activity.finish(
Step::Usage,
started.elapsed(),
format!(
"{} in {} folders",
theme::bytes(report.tree.total_allocated),
grouped(report.tree.total_dirs)
),
);
});
emit(Loaded::Usage(Some(report.tree)));
}
(
std::mem::take(&mut report.large_files),
std::mem::take(&mut report.large_folders),
issues,
diagnostics,
)
})
});
let downloads = (options.big && config.big.downloads)
.then(|| spawn_part(scope, "downloads", || old_downloads(config)));
let toolchains = options.toolchains.then(|| {
spawn_part(scope, "toolchains", || {
measure_toolchains(config, cancel, tracker)
})
});
let (pins, artifact_roots) = if let Some((handle, walked)) = artifact_scan {
let collected = walk(&handle, tracker, emit);
let walked = walked.recv();
if cancel.is_cancelled() {
finished.store(true, Ordering::Relaxed);
ticker.thread().unpark();
return Err(CANCELLED.to_owned());
}
let Ok(walked) = walked else {
finished.store(true, Ordering::Relaxed);
ticker.thread().unpark();
return Err("the scan stopped before finishing".to_owned());
};
let (pins, found_repos) = (walked.pins, walked.repositories);
let (issues, summary, found, artifact_bytes, artifact_roots) = collected;
let dirs = summary.progress.dirs;
emit(Loaded::ArtifactsDone {
issues,
summary,
disks: disks(roots),
});
tracker.update_now(|activity| {
activity.finish(
Step::Folders,
started.elapsed(),
format!(
"{} found, {} in {} folders",
plural(found, "item"),
theme::bytes(artifact_bytes),
grouped(dirs)
),
);
if options.repos {
activity.begin(Step::Repos, Some(found_repos.len()));
}
});
if options.repos {
spawn_part(scope, "repos", move || {
let checked = found_repos.len();
let inspected =
repos::inspect_all_collecting(found_repos, &config.git, cancel, |root| {
tracker.update(|activity| activity.advance(Step::Repos, root));
});
let failed = inspected.issues.len();
let repos = inspected.repositories;
tracker.update_now(|activity| {
activity.finish(
Step::Repos,
started.elapsed(),
if failed == 0 {
format!(
"{} of {} worth cleaning",
repos.len(),
plural(checked, "repository")
)
} else {
format!(
"{} of {} worth cleaning, {failed} could not be read",
repos.len(),
plural(checked, "repository")
)
},
);
});
emit(Loaded::Repos(repos));
});
}
(pins, artifact_roots)
} else {
(None, Vec::new())
};
let usage_result = usage_pass.and_then(|handle| handle.join().ok());
if cancel.is_cancelled() {
finished.store(true, Ordering::Relaxed);
ticker.thread().unpark();
return Err(CANCELLED.to_owned());
}
if options.big {
let (mut large, mut folders) = usage_result
.as_ref()
.map(|(files, folders, _, _)| (files.clone(), folders.clone()))
.unwrap_or_default();
if !artifact_roots.is_empty() {
large.retain(|item| !artifact_roots.iter().any(|art| item.path.starts_with(art)));
folders.retain(|folder| {
!artifact_roots
.iter()
.any(|art| folder.path.starts_with(art))
});
}
let old = downloads
.and_then(|downloads| downloads.join().ok())
.unwrap_or_default();
let big = big::candidates_with_folders(large, old, folders);
let bytes = big.iter().map(|c| c.usage.allocated).sum();
tracker.update_now(|activity| {
activity.finish(
Step::Big,
started.elapsed(),
format!("{}, {}", plural(big.len(), "item"), theme::bytes(bytes)),
);
});
emit(Loaded::Big(big));
}
if !scans_artifacts {
let (issues, summary) = match usage_result {
Some((_, _, issues, diag)) => (
issues,
Summary {
progress: Progress {
dirs: diag.dirs_visited,
files: diag.files_visited,
..Progress::default()
},
duration: diag.elapsed,
cancelled: cancel.is_cancelled(),
},
),
None => (
Vec::new(),
Summary {
progress: Progress::default(),
duration: started.elapsed(),
cancelled: cancel.is_cancelled(),
},
),
};
emit(Loaded::ArtifactsDone {
issues,
summary,
disks: disks(roots),
});
}
if let Some(measured) = toolchains {
let mut toolchains = measured.join().unwrap_or_default();
if let Some(pins) = &pins {
toolchains::apply_pins_measured(&mut toolchains, &pins.pins);
}
let bytes = toolchains.iter().map(|(_, c)| c.usage.allocated).sum();
tracker.update_now(|activity| {
activity.finish(
Step::Toolchains,
started.elapsed(),
format!(
"{}, {}",
plural(toolchains.len(), "version"),
theme::bytes(bytes)
),
);
});
emit(Loaded::Toolchains(toolchains));
}
finished.store(true, Ordering::Relaxed);
ticker.thread().unpark();
Ok(())
});
if cancel.is_cancelled() {
return Err(CANCELLED.to_owned());
}
result
}
fn spawn_part<'scope, T: Send + 'scope>(
scope: &'scope thread::Scope<'scope, '_>,
name: &str,
work: impl FnOnce() -> T + Send + 'scope,
) -> thread::ScopedJoinHandle<'scope, T> {
thread::Builder::new()
.name(format!("kuizer-gui-{name}"))
.spawn_scoped(scope, work)
.expect("spawn scan part thread")
}
#[derive(Default)]
struct Streamed {
batch: Vec<Candidate>,
artifact_roots: Vec<PathBuf>,
found: u64,
bytes: u64,
total_found: usize,
total_bytes: u64,
largest: Vec<Found>,
}
fn walk(
handle: &scan::Scan,
tracker: &Tracker,
emit: &(dyn Fn(Loaded) + Sync),
) -> (Vec<Issue>, Summary, usize, u64, Vec<PathBuf>) {
let streamed = RefCell::new(Streamed::default());
let (issues, summary) = scan::collect_streaming(
handle,
|progress| {
let (found, bytes, batch) = {
let mut streamed = streamed.borrow_mut();
let (found, bytes) = (streamed.found, streamed.bytes);
streamed.found = 0;
streamed.bytes = 0;
let batch =
(!streamed.batch.is_empty()).then(|| std::mem::take(&mut streamed.batch));
(found, bytes, batch)
};
tracker.update(|activity| {
activity.walked = progress;
activity.touch(Step::Folders, handle.current());
activity.merge(found, bytes, &streamed.borrow().largest);
});
if let Some(batch) = batch {
emit(Loaded::Found(batch));
}
},
|candidate| {
let batch = {
let mut guard = streamed.borrow_mut();
let streamed = &mut *guard;
let bytes = candidate.usage.allocated;
streamed.artifact_roots.push(candidate.path.clone());
streamed.batch.push(candidate);
streamed.found += 1;
streamed.bytes += bytes;
streamed.total_found += 1;
streamed.total_bytes += bytes;
let candidate = streamed.batch.last().expect("just added");
if activity::beats(&streamed.largest, bytes) {
activity::keep(
&mut streamed.largest,
Found {
path: candidate.path.clone(),
name: candidate.rule.name.clone(),
bytes,
},
);
}
(streamed.batch.len() >= 256).then(|| std::mem::take(&mut streamed.batch))
};
if let Some(batch) = batch {
emit(Loaded::Found(batch));
}
},
);
let mut streamed = streamed.into_inner();
if !streamed.batch.is_empty() {
emit(Loaded::Found(std::mem::take(&mut streamed.batch)));
}
(
issues,
summary,
streamed.total_found,
streamed.total_bytes,
streamed.artifact_roots,
)
}
fn disks(roots: &[PathBuf]) -> Vec<Disk> {
scan::mount_spaces(roots, &[])
.into_iter()
.map(|space| Disk {
available: Some(space.available),
total: Some(space.total),
})
.collect()
}
fn measure_caches(
config: &Config,
include_developer: bool,
cancel: &Cancel,
tracker: &Tracker,
) -> Vec<(KnownCache, Candidate)> {
let found: Vec<KnownCache> = Locations::for_user()
.map(|locations| {
caches::find_excluding_with_developer(
&locations,
&Protected::for_user(),
&config.catalog,
&config.usable_excludes(),
include_developer,
)
})
.unwrap_or_default();
tracker.update_now(|activity| activity.begin(Step::Caches, Some(found.len())));
caches::measure_threaded(found, cancel, scan::size_threads(config), |candidate| {
tracker.update(|activity| {
activity.advance(Step::Caches, &candidate.path);
if candidate.usage.entries > 0 {
activity.record(
&candidate.path,
&candidate.rule.name,
candidate.usage.allocated,
);
}
});
})
}
fn measure_trash(
config: &Config,
cancel: &Cancel,
) -> (Vec<(trashcan::Folder, Candidate)>, Vec<Issue>) {
let Some((path, layout)) = trashcan::home_trash() else {
return (Vec::new(), Vec::new());
};
match trashcan::inspect(&path, layout) {
Ok(Some(folder)) if !excluded(&config.usable_excludes(), &folder.path) => {
(trashcan::entries(vec![folder], cancel), Vec::new())
}
Ok(_) => (Vec::new(), Vec::new()),
Err(issue) => (Vec::new(), vec![issue]),
}
}
fn old_downloads(config: &Config) -> Vec<LargeFile> {
let Some(dir) = big::downloads_dir().filter(|dir| dir.is_dir()) else {
return Vec::new();
};
let mut old = big::old_downloads(
&dir,
config.big.downloads_age.0,
config.big.downloads_min_size.0,
SystemTime::now(),
&Protected::for_user(),
);
let excludes = config.usable_excludes();
old.retain(|item| !excluded(&excludes, &item.path));
old
}
fn excluded(excludes: &Excludes, path: &Path) -> bool {
path.ancestors().any(|dir| excludes.path(dir))
}
fn measure_toolchains(
config: &Config,
cancel: &Cancel,
tracker: &Tracker,
) -> Vec<(Toolchain, Candidate)> {
let found: Vec<Toolchain> = toolchains::Locations::for_user()
.map(|locations| {
toolchains::find_excluding(
&locations,
&config.toolchains.tools,
&config.usable_excludes(),
)
})
.unwrap_or_default();
tracker.update_now(|activity| activity.begin(Step::Toolchains, Some(found.len())));
toolchains::measure_with_threads(found, cancel, scan::size_threads(config), |candidate| {
tracker.update(|activity| {
activity.advance(Step::Toolchains, &candidate.path);
activity.record(
&candidate.path,
&candidate.rule.name,
candidate.usage.allocated,
);
});
})
}
pub fn find_duplicates(
config: &Config,
roots: &[PathBuf],
options: &ScanOptions,
cancel: &Cancel,
on_stage: impl FnMut(dupes::Stage),
) -> Result<Duplicates, String> {
let config = options.apply(config);
dupes::find_cancellable(
&config,
roots,
Options::from_config(&config),
cancel,
on_stage,
)
.map_err(|error| error.to_string())
}
pub const EXPLORED: &str = "disk-usage";
pub fn explored(
node: &kuizer::usage::UsageNode,
roots: &[PathBuf],
protected: &[PathBuf],
id: u64,
) -> Option<(Candidate, PathBuf)> {
if node.protected
|| Protected::protects_system_path(&node.path)
|| Protected::for_user()
.with_paths(protected)
.refuses(&node.path)
{
return None;
}
let parent = node.path.parent()?;
if !roots.iter().any(|root| parent.starts_with(root)) {
return None;
}
Some((UsageTree::candidate_for(node, id), parent.to_path_buf()))
}
pub fn refreshed(mut batch: Batch) -> Batch {
for candidate in &mut batch.candidates {
if candidate.rule.name == big::LARGE_FOLDER_RULE {
big::refresh_folder(candidate);
continue;
}
if candidate.rule.name != EXPLORED {
continue;
}
let Ok(metadata) = std::fs::symlink_metadata(&candidate.path) else {
continue;
};
if metadata.is_dir() {
let measured = scan::measure(&candidate.path, &Cancel::new());
candidate.usage.apparent = measured.usage.apparent;
candidate.newest = measured.newest;
} else {
candidate.usage.apparent = metadata.len();
candidate.newest = metadata.modified().ok();
}
}
batch
}
pub struct Outcome {
pub removals: Vec<(Source, Removal)>,
pub mode: DeleteMode,
pub history_error: Option<String>,
}
impl Outcome {
pub fn removed(&self) -> impl Iterator<Item = &(Source, Removal)> {
self.removals
.iter()
.filter(|(_, removal)| removal.status == Status::Removed)
}
pub fn trashed(&self, source: Source) -> bool {
source.trashed(self.mode)
}
pub fn failed(&self) -> impl Iterator<Item = &(Source, Removal)> {
self.removals
.iter()
.filter(|(_, removal)| removal.status == Status::Failed)
}
}
pub fn clean(
batches: Vec<Batch>,
delete: &DeleteConfig,
engines: &[String],
system_config: &system::SystemConfig,
history: Option<(std::sync::Arc<History>, TrashSnapshot)>,
stop: &std::sync::Arc<std::sync::atomic::AtomicBool>,
) -> (Outcome, Result<HistoryView, String>) {
let (system_batches, batches): (Vec<Batch>, Vec<Batch>) = batches
.into_iter()
.partition(|batch| batch.source == Source::System);
let mut roots: Vec<PathBuf> = batches
.iter()
.flat_map(|batch| batch.roots.iter().cloned())
.collect();
roots.sort();
roots.dedup();
let mode = delete.mode.into();
let mut removals = Vec::new();
let mut finished = Vec::new();
if !batches.is_empty() {
let executor = Executor::new(&roots, delete)
.with_engines(engines)
.with_session(system::Session::graphical_only())
.with_stop(std::sync::Arc::clone(stop));
removals.extend(executor.run(batches, mode, |_, _| {}).removals);
finished.push(executor.finish());
}
if !system_batches.is_empty() {
let system_config = system_config.clone();
let tools = system::Tools::for_user();
let session = system::Session::graphical_only();
let remover: kuizer::delete::Remover = std::sync::Arc::new(move |_, candidate, mode| {
system::remove_with(candidate, mode, &system_config, &tools, &session)
});
let executor = Executor::new(&[], delete)
.with_remover(remover)
.with_stop(std::sync::Arc::clone(stop));
removals.extend(executor.run(system_batches, mode, |_, _| {}).removals);
finished.push(executor.finish());
}
let finished: Result<Vec<history::Run>, history::HistoryError> =
finished.into_iter().try_fold(Vec::new(), |mut all, runs| {
all.extend(runs?);
Ok(all)
});
let (view, history_error) = match (finished, history) {
(Ok(runs), Some((history, mut trash))) => {
let mut history = std::sync::Arc::unwrap_or_clone(history);
for run in runs {
trash.record(&mut history, run);
}
(Ok(HistoryView::new(history, trash)), None)
}
(Ok(_), None) => (HistoryView::load(), None),
(Err(error), _) => (HistoryView::load(), Some(error.to_string())),
};
let outcome = Outcome {
removals,
mode: delete.mode,
history_error,
};
(outcome, view)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Restored {
pub items: usize,
pub bytes: u64,
pub problems: Vec<(PathBuf, String)>,
pub history_error: Option<String>,
}
pub fn restore(
history: std::sync::Arc<History>,
session: u64,
) -> (Result<Restored, String>, Option<HistoryView>) {
let id = format!("s{session}");
let Some(run) = history.runs.iter().position(|run| run.id == session) else {
return (Err(format!("the history has no cleanup {id}")), None);
};
let mut listing = match TrashView::list() {
Ok(listing) => listing,
Err(error) => return (Err(error.to_string()), None),
};
let mut history = std::sync::Arc::unwrap_or_clone(history);
let trash = listing.snapshot(&history);
let targets = history::restorable(&history, &trash, run);
if targets.is_empty() {
let view = HistoryView::new(history, trash);
return (
Err(format!("nothing from {id} is still in the trash")),
Some(view),
);
}
let restore = history::restore::restore_listed(&history, &targets, false, &mut listing);
let restored = Restored {
items: restore.count(RestoreStatus::Restored),
bytes: restore.bytes(RestoreStatus::Restored),
problems: restore
.outcomes
.iter()
.filter(|outcome| outcome.status != RestoreStatus::Restored)
.map(|outcome| {
(
outcome.path.clone(),
outcome.reason.clone().unwrap_or_default(),
)
})
.collect(),
history_error: restore
.record_into(&mut history)
.err()
.map(|error| error.to_string()),
};
let trash = listing.snapshot(&history);
(Ok(restored), Some(HistoryView::new(history, trash)))
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use kuizer::detect::{Kind, RuleInfo, Safety};
use kuizer::scan::Usage;
use super::*;
fn candidate(id: u64, path: &str, safety: Safety) -> Candidate {
Candidate {
id,
path: PathBuf::from(path),
kind: Kind::Dir,
rule: Arc::new(RuleInfo {
name: "node_modules".to_owned(),
category: Category::Dependencies,
safety,
ecosystem: "node".to_owned(),
}),
project: None,
usage: Usage {
allocated: id * 10,
..Usage::default()
},
newest: None,
identity: None,
project_last_active: None,
}
}
#[test]
fn duplicates_on_request_match_the_ones_a_scan_walk_collects() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("photos");
for (folder, size) in [
("a", 8192),
("b", 8192),
("c", 9000),
("d", 9000),
("e", 5000),
] {
std::fs::create_dir_all(root.join(folder)).unwrap();
std::fs::write(root.join(folder).join("same.bin"), vec![b'z'; size]).unwrap();
}
std::fs::create_dir_all(root.join("site/node_modules")).unwrap();
std::fs::write(root.join("site/package.json"), "{}").unwrap();
std::fs::write(root.join("site/node_modules/same.bin"), vec![b'z'; 8192]).unwrap();
let config = Config::default();
let roots = scan::normalize_roots(&[root]);
let options = ScanOptions::from_config(&config);
let groups = |found: Duplicates| -> Vec<Vec<PathBuf>> {
found
.groups
.into_iter()
.map(|group| {
group
.members
.into_iter()
.map(|member| member.path)
.collect()
})
.collect()
};
let lazy =
groups(find_duplicates(&config, &roots, &options, &Cancel::new(), |_| {}).unwrap());
let applied = options.apply(&config);
let duplicate_options = Options::from_config(&applied);
let (handle, walked) = repos::start_scan(
&applied,
&roots,
Cancel::new(),
Some(duplicate_options),
false,
)
.unwrap();
scan::collect(&handle, |_| {});
let files = walked.recv().unwrap().files.unwrap();
let walked = groups(dupes::group(files, duplicate_options, |_| {}));
assert_eq!(lazy.len(), 2);
assert_eq!(lazy, walked);
}
#[test]
fn streamed_candidates_keep_arrival_order_until_the_scan_finishes() {
let options = ScanOptions::from_config(&Config::default());
let mut report = Report::empty(&[], &options);
report.apply(Loaded::Found(vec![
candidate(1, "/p/small", Safety::Safe),
candidate(3, "/p/large", Safety::Safe),
]));
assert_eq!(
report
.candidates
.iter()
.map(|candidate| candidate.id)
.collect::<Vec<_>>(),
[1, 3]
);
report.apply(Loaded::ArtifactsDone {
issues: Vec::new(),
summary: Summary {
progress: Progress::default(),
duration: Duration::ZERO,
cancelled: false,
},
disks: Vec::new(),
});
assert_eq!(
report
.candidates
.iter()
.map(|candidate| candidate.id)
.collect::<Vec<_>>(),
[3, 1]
);
}
#[test]
fn short_path_strips_the_scan_root() {
let roots = [PathBuf::from("/p")];
assert_eq!(short_path(Path::new("/p/a/dist"), &roots), "a/dist");
assert_eq!(short_path(Path::new("/q/b"), &roots), "/q/b");
assert_eq!(short_path(Path::new("/p"), &roots), "/p");
}
#[test]
fn dropped_paths_leave_every_list() {
let member = |path: &str| dupes::Member {
path: PathBuf::from(path),
links: Vec::new(),
modified: None,
};
let group = |paths: &[&str]| dupes::Group {
size: 10,
allocated: 10,
hash: String::new(),
verified: true,
members: paths.iter().map(|path| member(path)).collect(),
};
let mut report = Report {
roots: vec![PathBuf::from("/p")],
options: ScanOptions::from_config(&Config::default()),
candidates: vec![
candidate(1, "/p/a/node_modules", Safety::Safe),
candidate(2, "/p/b/node_modules", Safety::Safe),
],
issues: vec![Issue {
path: PathBuf::from("/p/a/node_modules/locked"),
kind: scan::IssueKind::PermissionDenied,
message: String::new(),
}],
summary: Summary {
progress: Progress::default(),
duration: std::time::Duration::ZERO,
cancelled: false,
},
caches: Vec::new(),
toolchains: Vec::new(),
docker: Vec::new(),
docker_issues: Vec::new(),
repos: Vec::new(),
trash: Vec::new(),
trash_issues: Vec::new(),
system: Vec::new(),
system_issues: Vec::new(),
big: Vec::new(),
usage: None,
walk_diagnostics: None,
duplicates: Some(Duplicates {
groups: vec![
group(&["/p/a/node_modules/x", "/p/b/x"]),
group(&["/p/a/node_modules/y", "/p/b/y", "/p/c/y"]),
],
issues: Vec::new(),
files: 5,
duration: std::time::Duration::ZERO,
}),
history: Err(String::new()),
disks: Vec::new(),
scanned: SystemTime::now(),
};
report.drop_paths(&[PathBuf::from("/p/a/node_modules")]);
assert_eq!(report.candidates.len(), 1);
assert_eq!(report.candidates[0].id, 2);
assert!(report.issues.is_empty());
let groups = &report.duplicates.as_ref().unwrap().groups;
assert_eq!(groups.len(), 1);
assert_eq!(groups[0].members.len(), 2);
}
#[test]
fn report_groups_by_category_and_project() {
let mut first = candidate(1, "/p/a/node_modules", Safety::Safe);
first.project = Some(PathBuf::from("/p/a"));
let mut second = candidate(4, "/p/a/dist", Safety::Review);
second.project = Some(PathBuf::from("/p/a"));
let report = Report {
roots: vec![PathBuf::from("/p")],
options: ScanOptions::from_config(&Config::default()),
candidates: vec![first, second],
issues: Vec::new(),
summary: Summary {
progress: Progress::default(),
duration: std::time::Duration::ZERO,
cancelled: false,
},
caches: Vec::new(),
toolchains: Vec::new(),
docker: Vec::new(),
docker_issues: Vec::new(),
repos: Vec::new(),
trash: Vec::new(),
trash_issues: Vec::new(),
system: Vec::new(),
system_issues: Vec::new(),
big: Vec::new(),
usage: None,
walk_diagnostics: None,
duplicates: None,
history: Err(String::new()),
disks: Vec::new(),
scanned: SystemTime::now(),
};
assert_eq!(report.total(None), 50);
assert_eq!(report.total(Some(Safety::Review)), 40);
let projects = report.by_project();
assert_eq!(projects.len(), 1);
assert_eq!(projects[0].bytes, 50);
assert_eq!(projects[0].count, 2);
let categories = report.by_category();
assert_eq!(categories.len(), 1);
assert_eq!(categories[0].count, 2);
}
#[test]
#[ignore = "runs inside isolated_deletion_cases"]
fn the_trash_and_large_files_load_without_excluded_or_deleted_paths_inside() {
let Some(base) = std::env::var_os("KUIZER_GUI_TEST_BASE").map(PathBuf::from) else {
return;
};
let home = base.join("home");
let root = base.join("sources");
let _ = std::fs::remove_dir_all(&home);
let _ = std::fs::remove_dir_all(&root);
let trash_files = home.join(".local/share/Trash/files");
std::fs::create_dir_all(&trash_files).unwrap();
std::fs::write(trash_files.join("old.txt"), b"gone").unwrap();
std::fs::create_dir_all(home.join(".config")).unwrap();
std::fs::write(
home.join(".config/user-dirs.dirs"),
"XDG_DOWNLOAD_DIR=\"$HOME/Downloads\"\n",
)
.unwrap();
let downloads = home.join("Downloads");
std::fs::create_dir_all(&downloads).unwrap();
let setup = downloads.join("setup.iso");
std::fs::write(&setup, vec![1u8; 70_000]).unwrap();
std::fs::File::options()
.write(true)
.open(&setup)
.unwrap()
.set_modified(SystemTime::now() - Duration::from_secs(200 * 86_400))
.unwrap();
std::fs::create_dir_all(&root).unwrap();
let video = root.join("video.mkv");
std::fs::write(&video, vec![2u8; 80_000]).unwrap();
std::fs::write(root.join("notes.txt"), b"small").unwrap();
let mut config = Config::default();
config.big.min_size = kuizer::units::ByteSize(65_536);
config.big.downloads_min_size = kuizer::units::ByteSize(65_536);
let options = ScanOptions {
caches: false,
toolchains: false,
docker: false,
repos: false,
system: false,
..ScanOptions::from_config(&config)
};
let roots = scan::normalize_roots(&[root]);
let parts = std::sync::Mutex::new(Vec::new());
load(
&config,
&roots,
&options,
&Cancel::new(),
&Tracker::new(|_| {}),
&|loaded| {
if matches!(loaded, Loaded::Trash { .. } | Loaded::Big(_)) {
parts.lock().unwrap().push(loaded);
}
},
)
.unwrap();
let parts = parts.into_inner().unwrap();
assert_eq!(parts.len(), 2);
for mut loaded in parts {
match &loaded {
Loaded::Trash { entries, .. } => {
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].0.items, 1);
let trash = entries[0].1.path.clone();
let gone = HashMap::from([(Source::Trash, HashSet::from([trash]))]);
loaded.without(&[], &gone);
assert!(matches!(&loaded, Loaded::Trash { entries, .. } if entries.is_empty()));
}
Loaded::Big(big) => {
let mut names: Vec<&str> = big
.iter()
.map(|candidate| candidate.rule.name.as_str())
.collect();
names.sort_unstable();
assert_eq!(names, ["large-file", "old-download"]);
loaded.without(std::slice::from_ref(&downloads), &HashMap::new());
let Loaded::Big(big) = &loaded else {
unreachable!()
};
assert_eq!(big.len(), 1);
assert!(big[0].path.ends_with("video.mkv"));
let gone = HashMap::from([(Source::Big, HashSet::from([big[0].path.clone()]))]);
loaded.without(&[], &gone);
assert!(matches!(&loaded, Loaded::Big(big) if big.is_empty()));
}
_ => unreachable!(),
}
}
}
}