voom 0.14.1

Fast, safe, parallel build-artifact pruning across every major language ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! The two renderers over one result set, in the same house style as `bazel::report` and
//! `git::report` (ADR 0007): an aligned em dash before a reason, colour as a second channel,
//! every state named in words, deterministic order. Always the explicit subcommand's full
//! listing — every job found, including the ones left alone, since there is no sweep to stay
//! quiet on the user's behalf.

use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

use owo_colors::{OwoColorize, Style};
use serde_json::{Value, json};

use super::{ClaudePruneResult, Job, JobState, SCHEMA_VERSION};
use crate::delete::Outcome;

const GUTTER: &str = "  ";
const BECAUSE: &str = "— ";

mod palette {
    use owo_colors::Style;

    pub fn removed() -> Style {
        Style::new().green()
    }

    pub fn would_remove() -> Style {
        Style::new().yellow()
    }

    pub fn kept() -> Style {
        Style::new().cyan()
    }

    pub fn live() -> Style {
        Style::new().blue()
    }

    pub fn refused() -> Style {
        Style::new().red()
    }

    pub fn quiet() -> Style {
        Style::new().dimmed()
    }
}

struct Row {
    label: &'static str,
    style: Style,
    path: String,
    detail: Option<String>,
}

fn base_path(roots: &[PathBuf]) -> Option<&Path> {
    let first = roots.first()?;
    let base = first
        .ancestors()
        .find(|candidate| roots.iter().all(|root| root.starts_with(candidate)))?;
    (base.is_absolute() && base.parent().is_some()).then_some(base)
}

fn shorten(path: &Path, base: Option<&Path>) -> String {
    let Some(base) = base else {
        return path.display().to_string();
    };
    match path.strip_prefix(base) {
        Ok(relative) if relative.as_os_str().is_empty() => ".".to_owned(),
        Ok(relative) => relative.display().to_string(),
        Err(_) => path.display().to_string(),
    }
}

fn days(age: Duration) -> u64 {
    age.as_secs() / (24 * 60 * 60)
}

/// `, 1.2 GiB` when the scratch was measured, and nothing when there was none to measure.
fn size_phrase(bytes: Option<u64>) -> String {
    bytes.map_or_else(String::new, |bytes| {
        format!(", {}", humansize::format_size(bytes, humansize::BINARY))
    })
}

fn row(job: &Job, dry_run: bool, remove: bool, base: Option<&Path>) -> Row {
    let (label, style, detail) = match (&job.state, &job.outcome) {
        (JobState::Unproven(reason), _) => ("kept", palette::kept(), Some(reason.to_string())),
        (JobState::Live { session_id }, _) => (
            "kept",
            palette::live(),
            Some(format!("session {session_id} is running right now")),
        ),
        (JobState::TooRecent { age }, _) => (
            "kept",
            palette::kept(),
            Some(format!("quiet for only {} days", days(*age))),
        ),
        (JobState::Eligible { age }, Some(Outcome::Removed)) => (
            "removed",
            palette::removed(),
            Some(format!("quiet for {} days{}", days(*age), size_phrase(job.bytes))),
        ),
        (JobState::Eligible { age }, Some(Outcome::Detached)) => (
            "detached",
            palette::removed(),
            Some(format!("quiet for {} days; freeing in the background", days(*age))),
        ),
        (JobState::Eligible { age }, Some(Outcome::WouldRemove)) => (
            if dry_run { "would remove" } else { "removed" },
            palette::would_remove(),
            Some(format!("quiet for {} days{}", days(*age), size_phrase(job.bytes))),
        ),
        (JobState::Eligible { age }, Some(Outcome::Refused(refusal))) => (
            "refused",
            palette::refused(),
            Some(format!("{refusal} — quiet for {} days", days(*age))),
        ),
        (JobState::Eligible { age }, Some(Outcome::Failed(failure))) => (
            "failed",
            palette::refused(),
            Some(format!("{failure} — quiet for {} days", days(*age))),
        ),
        (JobState::Eligible { age }, Some(Outcome::PartiallyRemoved { failure, .. })) => (
            "partially removed",
            palette::refused(),
            Some(format!("{failure} — quiet for {} days", days(*age))),
        ),
        (JobState::Eligible { age }, None) if remove => (
            "kept",
            palette::kept(),
            Some(format!(
                "quiet for {} days, but its scratch is already gone",
                days(*age)
            )),
        ),
        (JobState::Eligible { age }, None) => (
            "eligible",
            palette::kept(),
            Some(format!(
                "quiet for {} days{} — rerun with --remove to reclaim it",
                days(*age),
                size_phrase(job.bytes),
            )),
        ),
    };
    Row {
        label,
        style,
        path: shorten(&job.path, base),
        detail,
    }
}

/// Renders the subcommand's human report.
///
/// # Errors
///
/// Propagates any write failure from `out`.
pub fn render_human(result: &ClaudePruneResult, out: &mut impl io::Write) -> io::Result<()> {
    let base = base_path(&result.roots);
    let rows: Vec<Row> = result
        .jobs
        .iter()
        .map(|job| row(job, result.dry_run, result.remove, base))
        .collect();

    if let Some(base) = base.filter(|_| !rows.is_empty()) {
        writeln!(out, "{}", base.display().bold())?;
    }
    write_block(&rows, out)?;
    if !rows.is_empty() {
        writeln!(out)?;
    }
    write_footer(result, out)
}

fn write_block(rows: &[Row], out: &mut impl io::Write) -> io::Result<()> {
    let label_width = rows.iter().map(|row| width_of(row.label)).max().unwrap_or(0);
    let path_width = rows
        .iter()
        .filter(|row| row.detail.is_some())
        .map(|row| width_of(&row.path))
        .max()
        .unwrap_or(0);

    for row in rows {
        write!(out, "{GUTTER}{}", row.style.style(row.label))?;
        write_fill(out, label_width.saturating_sub(width_of(row.label)))?;
        write!(out, "{GUTTER}{}", row.path)?;
        match &row.detail {
            None => writeln!(out)?,
            Some(detail) => {
                write_fill(out, path_width.saturating_sub(width_of(&row.path)))?;
                writeln!(
                    out,
                    "{GUTTER}{}",
                    format_args!("{BECAUSE}{detail}").style(palette::quiet())
                )?;
            }
        }
    }
    Ok(())
}

fn write_footer(result: &ClaudePruneResult, out: &mut impl io::Write) -> io::Result<()> {
    let totals = result.totals();
    if result.remove {
        let verb = if result.dry_run {
            "would be reclaimed"
        } else {
            "reclaimed"
        };
        writeln!(
            out,
            "{} {} found, {} {verb} ({}) in {:.2?}",
            totals.found.bold(),
            jobs_word(totals.found),
            totals.removed.bold(),
            humansize::format_size(totals.bytes, humansize::BINARY),
            result.elapsed
        )?;
    } else {
        writeln!(
            out,
            "{} {} found, {} eligible ({}; rerun with --remove to reclaim) in {:.2?}",
            totals.found.bold(),
            jobs_word(totals.found),
            totals.eligible.bold(),
            humansize::format_size(totals.eligible_bytes, humansize::BINARY),
            result.elapsed
        )?;
    }
    if totals.refused > 0 {
        writeln!(
            out,
            "{GUTTER}{}",
            format!("{} refused by a rail", totals.refused).style(palette::refused())
        )?;
    }
    Ok(())
}

fn jobs_word(count: usize) -> &'static str {
    if count == 1 { "job" } else { "jobs" }
}

fn width_of(text: &str) -> usize {
    text.chars().count()
}

fn write_fill(out: &mut impl io::Write, spaces: usize) -> io::Result<()> {
    write!(out, "{:spaces$}", "")
}

/// Builds the JSON document.
#[must_use]
pub fn document(result: &ClaudePruneResult) -> Value {
    let totals = result.totals();
    json!({
        "schema_version": SCHEMA_VERSION,
        "remove": result.remove,
        "dry_run": result.dry_run,
        "roots": result.roots.iter().map(|root| root.display().to_string()).collect::<Vec<_>>(),
        "jobs": result.jobs.iter().map(job_value).collect::<Vec<_>>(),
        "totals": {
            "found": totals.found,
            "removed": totals.removed,
            "refused": totals.refused,
            "kept": totals.kept,
            "bytes": totals.bytes,
        },
        "elapsed_ms": u64::try_from(result.elapsed.as_millis()).unwrap_or(u64::MAX),
    })
}

fn job_value(job: &Job) -> Value {
    let (state, detail) = match &job.state {
        JobState::Unproven(reason) => ("unproven", json!({ "reason": reason.code() })),
        JobState::Live { session_id } => ("live", json!({ "session_id": session_id })),
        JobState::TooRecent { age } => ("too_recent", json!({ "age_days": days(*age) })),
        JobState::Eligible { age } => ("eligible", json!({ "age_days": days(*age) })),
    };
    json!({
        "path": job.path.display().to_string(),
        "state": state,
        "detail": detail,
        "bytes": job.bytes,
        "outcome": job.outcome.as_ref().map(outcome_code),
    })
}

fn outcome_code(outcome: &Outcome) -> &'static str {
    match outcome {
        Outcome::Removed => "removed",
        Outcome::Detached => "detached",
        Outcome::WouldRemove => "would_remove",
        Outcome::Refused(_) => "refused",
        Outcome::Failed(_) => "failed",
        Outcome::PartiallyRemoved { .. } => "partially_removed",
    }
}

/// Renders the document as pretty-printed JSON.
///
/// # Errors
///
/// Propagates write and serialization failures from `out`.
pub fn render_json(result: &ClaudePruneResult, out: &mut impl io::Write) -> io::Result<()> {
    serde_json::to_writer_pretty(&mut *out, &document(result))?;
    writeln!(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::claude::Unproven;

    fn result(jobs: Vec<Job>, remove: bool, dry_run: bool) -> ClaudePruneResult {
        ClaudePruneResult {
            roots: vec![PathBuf::from("/home/dev/.claude/jobs")],
            jobs,
            remove,
            dry_run,
            elapsed: Duration::from_millis(20),
        }
    }

    fn eligible(path: &str, age_days: u64, outcome: Option<Outcome>) -> Job {
        Job {
            path: PathBuf::from(path),
            state: JobState::Eligible {
                age: Duration::from_secs(age_days * 86400),
            },
            bytes: Some(4096),
            outcome,
        }
    }

    #[test]
    fn should_report_eligible_without_remove_and_say_how_to_reclaim_it() {
        let mut buffer = Vec::new();
        render_human(
            &result(vec![eligible("/home/dev/.claude/jobs/old", 30, None)], false, false),
            &mut buffer,
        )
        .expect("writing to a Vec cannot fail");
        let text = String::from_utf8(buffer).expect("the report is UTF-8");
        assert!(text.contains("eligible"), "{text}");
        assert!(text.contains("--remove"), "{text}");
    }

    /// A dry run exists to say what would be reclaimed, so the size is in the row and in the JSON
    /// even though nothing was asked to be removed.
    #[test]
    fn should_report_the_size_of_an_eligible_job_without_remove() {
        let result = result(vec![eligible("/home/dev/.claude/jobs/old", 30, None)], false, false);
        let mut buffer = Vec::new();
        render_human(&result, &mut buffer).expect("writing to a Vec cannot fail");
        let text = String::from_utf8(buffer).expect("the report is UTF-8");
        assert!(text.contains("4 KiB"), "{text}");
        assert_eq!(document(&result)["jobs"][0]["bytes"], json!(4096));
    }

    #[test]
    fn should_total_the_eligible_scratch_in_a_report_only_footer() {
        let result = result(vec![eligible("/home/dev/.claude/jobs/old", 30, None)], false, false);
        let mut buffer = Vec::new();
        render_human(&result, &mut buffer).expect("writing to a Vec cannot fail");
        let text = String::from_utf8(buffer).expect("the report is UTF-8");
        assert!(text.contains("(4 KiB; rerun with --remove to reclaim)"), "{text}");
    }

    #[test]
    fn should_give_the_reason_a_job_is_unproven() {
        let job = Job {
            path: PathBuf::from("/home/dev/.claude/jobs/parked"),
            state: JobState::Unproven(Unproven::NotFinished),
            bytes: None,
            outcome: None,
        };
        let result = result(vec![job], false, false);
        let mut buffer = Vec::new();
        render_human(&result, &mut buffer).expect("writing to a Vec cannot fail");
        let text = String::from_utf8(buffer).expect("the report is UTF-8");
        assert!(text.contains("has not finished"), "{text}");
        assert!(!text.contains("no readable state.json"), "{text}");
        assert_eq!(document(&result)["jobs"][0]["detail"]["reason"], json!("not_finished"));
    }

    #[test]
    fn should_name_a_live_session_and_never_call_it_removed() {
        let job = Job {
            path: PathBuf::from("/home/dev/.claude/jobs/live"),
            state: JobState::Live {
                session_id: "abc-123".to_owned(),
            },
            bytes: None,
            outcome: None,
        };
        let mut buffer = Vec::new();
        render_human(&result(vec![job], true, false), &mut buffer).expect("writing to a Vec cannot fail");
        let text = String::from_utf8(buffer).expect("the report is UTF-8");
        assert!(text.contains("is running right now"), "{text}");
        assert!(text.contains("kept"), "{text}");
    }

    #[test]
    fn should_write_valid_json_carrying_the_schema_version() {
        let mut buffer = Vec::new();
        render_json(&result(Vec::new(), false, false), &mut buffer).expect("writing to a Vec cannot fail");
        let parsed: Value = serde_json::from_slice(&buffer).expect("the output parses");
        assert_eq!(parsed["schema_version"], SCHEMA_VERSION);
        assert_eq!(parsed["remove"], false);
    }
}