Skip to main content

cargo_sift/
lib.rs

1//! `cargo-sift` — remove build artifacts from Cargo `target/` directories that
2//! the current build graph can no longer reference.
3//!
4//! Where `cargo clean` deletes everything and mtime sweepers delete still-valid
5//! artifacts, `cargo sift` performs a deterministic **reachability GC**: it
6//! reads `Cargo.lock` and the workspace manifests to learn what the project
7//! resolves to, reconstructs the build units sitting in `target/`, and removes
8//! only the unreachable ones — dependency versions no longer in the lockfile,
9//! and artifacts for removed packages and targets.
10//!
11//! The pieces: [`discovery`] finds target dirs, [`resolve`] computes the live
12//! set from `Cargo.lock` (no cargo subprocess), [`units`] reconstructs units
13//! from disk, and [`gc`] classifies and removes them.
14
15pub mod cli;
16pub mod discovery;
17pub mod gc;
18pub mod human;
19pub mod resolve;
20pub mod units;
21
22use std::path::Path;
23
24use anyhow::{Context, Result};
25
26use cli::Args;
27
28/// Entry point shared by the binary: resolve target directories, then GC each
29/// one against its own current resolve.
30pub fn run(args: Args) -> Result<()> {
31    let targets = discovery::resolve_targets(&args.paths, args.recursive)
32        .context("failed to locate Cargo target directories")?;
33
34    if targets.is_empty() {
35        let where_ = args
36            .paths
37            .iter()
38            .map(|p| p.display().to_string())
39            .collect::<Vec<_>>()
40            .join(", ");
41        eprintln!("cargo-sift: no Cargo target directories found under {where_}");
42        return Ok(());
43    }
44
45    let mut grand = gc::Stats::default();
46    let mut cleaned = 0usize;
47    for target in &targets {
48        // Fail safe: without a resolve we cannot know what's live, so skip.
49        let live = match resolve::resolve(target) {
50            Ok(live) => live,
51            Err(err) => {
52                eprintln!(
53                    "cargo-sift: skipping {} — {err}; nothing removed",
54                    target.display()
55                );
56                continue;
57            }
58        };
59
60        let plan = gc::plan(target, &live)
61            .with_context(|| format!("planning GC for {}", target.display()))?;
62        let stats = gc::execute(&plan, args.dry_run, args.verbose)?;
63        if !args.quiet {
64            print_target_result(target, &plan, &stats, args.dry_run);
65        }
66        grand.merge(&stats);
67        cleaned += 1;
68    }
69
70    if cleaned > 1 || args.quiet {
71        let verb = if args.dry_run { "would free" } else { "freed" };
72        println!(
73            "cargo-sift: {verb} {} across {cleaned} target director{} ({} units removed)",
74            human::format_size(grand.bytes_freed),
75            if cleaned == 1 { "y" } else { "ies" },
76            grand.units_removed,
77        );
78    }
79    if grand.errors > 0 {
80        eprintln!(
81            "cargo-sift: {} unit(s) could not be fully removed",
82            grand.errors
83        );
84    }
85    Ok(())
86}
87
88fn print_target_result(target: &Path, plan: &gc::Plan, stats: &gc::Stats, dry_run: bool) {
89    if plan.removals.is_empty() {
90        println!(
91            "{}: {} — already tidy",
92            target.display(),
93            human::format_size(plan.dir_bytes)
94        );
95        return;
96    }
97    let verb = if dry_run { "would free" } else { "freed" };
98    let breakdown = plan
99        .tally()
100        .into_iter()
101        .map(|(reason, count, bytes)| {
102            format!("{count} {} {}", reason.label(), human::format_size(bytes))
103        })
104        .collect::<Vec<_>>()
105        .join(", ");
106    println!(
107        "{}: {} → {verb} {} ({} units: {breakdown})",
108        target.display(),
109        human::format_size(plan.dir_bytes),
110        human::format_size(stats.bytes_freed),
111        stats.units_removed,
112    );
113}