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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! The two renderers over one result, in the same house style as `bazel::report` and
//! `claude::report` (ADR 0007): an em dash before a reason, colour as a second channel, every
//! state named in words, deterministic order.
//!
//! Sizes are decimal (`1.5 GB`), unlike the binary units the filesystem reports use, because every
//! figure here originates in docker's own decimal output and is meant to be compared with
//! `docker system df`.

use std::io;
use std::time::Duration;

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

use super::plan::{LaneKind, VolumeScope};
use super::{DockerPruneResult, Lane, LaneOutcome, SCHEMA_VERSION, Trim, TrimOutcome};

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

/// Strips terminal control sequences from text voom did not author — a daemon's error line, a
/// profile or instance name parsed out of an endpoint, a `DOCKER_HOST` — before it reaches a TTY.
///
/// A hostile or merely broken peer could otherwise move the cursor, recolour the rest of the
/// report, or (via OSC 52) write the clipboard. Docker's stdout/stderr and the environment are the
/// only inputs here that are not voom's own literals.
fn sanitize(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(character) = chars.next() {
        if character != '\u{1b}' {
            if !character.is_control() {
                out.push(character);
            }
            continue;
        }
        match chars.next() {
            // CSI: `ESC [ params… final`, the final byte in 0x40..=0x7e.
            Some('[') => {
                for byte in chars.by_ref() {
                    if ('\u{40}'..='\u{7e}').contains(&byte) {
                        break;
                    }
                }
            }
            // OSC: `ESC ] … ` ended by BEL or ST (`ESC \`).
            Some(']') => {
                for byte in chars.by_ref() {
                    if byte == '\u{7}' || byte == '\u{1b}' {
                        break;
                    }
                }
            }
            // Any other escape: drop the introducer and the character after it.
            _ => {}
        }
    }
    out
}

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 refused() -> Style {
        Style::new().red()
    }

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

struct Row {
    label: &'static str,
    style: Style,
    subject: String,
    detail: String,
}

fn size(bytes: u64) -> String {
    format_size(bytes, DECIMAL)
}

fn days(age: Duration) -> String {
    let hours = age.as_secs() / 3600;
    if hours.is_multiple_of(24) {
        format!("{}d", hours / 24)
    } else {
        format!("{hours}h")
    }
}

fn noun(kind: LaneKind, count: usize) -> &'static str {
    match (kind, count) {
        (LaneKind::Images, 1) => "image",
        (LaneKind::Images, _) => "images",
        (LaneKind::BuildCache, 1) => "cache record",
        (LaneKind::BuildCache, _) => "cache records",
        (LaneKind::Volumes, 1) => "volume",
        (LaneKind::Volumes, _) => "volumes",
    }
}

fn lane_row(lane: &Lane, result: &DockerPruneResult) -> Row {
    let kind = lane.plan.kind;
    let age = days(result.max_age);
    let scope = match kind {
        LaneKind::Images => format!("dangling, or unused for over {age}"),
        LaneKind::BuildCache => format!("idle for over {age}"),
        LaneKind::Volumes => format!(
            "{}, mounted by no container",
            result.volumes.map_or("none", |scope| scope.label())
        ),
    };
    let counted = format!(
        "{} {}, {}",
        lane.plan.candidates,
        noun(kind, lane.plan.candidates),
        size(lane.bytes())
    );
    let (label, style, detail) = match &lane.outcome {
        LaneOutcome::WouldReclaim => ("would reclaim", palette::would_remove(), format!("{counted}: {scope}")),
        // A real volume prune removes whatever the daemon finds unused at execution time, which can
        // differ from the inventory taken earlier, so the count is named for what it is — what the
        // inventory matched — and only the bytes are docker's own figure.
        LaneOutcome::Reclaimed { bytes: Some(_) } if kind == LaneKind::Volumes => (
            "reclaimed",
            palette::removed(),
            format!(
                "{} {} matched in the inventory, {}: {scope}",
                lane.plan.candidates,
                noun(kind, lane.plan.candidates),
                size(lane.bytes())
            ),
        ),
        LaneOutcome::Reclaimed { bytes: Some(_) } => ("reclaimed", palette::removed(), format!("{counted}: {scope}")),
        LaneOutcome::Reclaimed { bytes: None } => (
            "pruned",
            palette::removed(),
            format!(
                "{} {} matched: {scope}; docker reported no size",
                lane.plan.candidates,
                noun(kind, lane.plan.candidates)
            ),
        ),
        LaneOutcome::Skipped { reason } => ("skipped", palette::kept(), reason.clone()),
        LaneOutcome::Failed { message } => ("failed", palette::refused(), message.clone()),
    };
    Row {
        label,
        style,
        subject: kind.label().to_owned(),
        detail,
    }
}

fn trim_row(trim: &Trim) -> Row {
    let (label, style, detail) = match &trim.outcome {
        TrimOutcome::Withheld { host_bytes } => (
            "would trim",
            palette::would_remove(),
            format!(
                "`{}`; the host disk image holds {} now",
                trim.command.join(" "),
                host_bytes.map_or_else(|| "an unmeasured amount".to_owned(), size)
            ),
        ),
        TrimOutcome::Trimmed { before, after } => (
            "trimmed",
            palette::removed(),
            match (before, after, trim.outcome.returned()) {
                (Some(before), Some(after), Some(returned)) => {
                    format!(
                        "host disk image {} -> {}, {} returned",
                        size(*before),
                        size(*after),
                        size(returned)
                    )
                }
                _ => "host disk image not found, so the bytes returned are unmeasured".to_owned(),
            },
        ),
        TrimOutcome::Failed { message } => ("failed", palette::refused(), message.clone()),
    };
    Row {
        label,
        style,
        subject: "vm disk".to_owned(),
        detail,
    }
}

/// Renders the subcommand's human report. A skipped run is one line.
///
/// # Errors
///
/// Propagates any write failure from `out`.
pub fn render_human(result: &DockerPruneResult, out: &mut impl io::Write) -> io::Result<()> {
    if let Some(skip) = &result.skipped {
        return writeln!(out, "voom: docker: {} (skipped)", sanitize(&skip.reason));
    }

    let mut rows: Vec<Row> = result.lanes.iter().map(|lane| lane_row(lane, result)).collect();
    rows.extend(result.trim.as_ref().map(trim_row));

    let heading = result.backend.as_deref().unwrap_or("docker");
    writeln!(out, "{}", sanitize(&format!("docker — {heading}")).bold())?;
    write_block(&rows, out)?;
    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| row.label.chars().count()).max().unwrap_or(0);
    let subject_width = rows.iter().map(|row| row.subject.chars().count()).max().unwrap_or(0);
    for row in rows {
        writeln!(
            out,
            "{GUTTER}{label:<label_width$}{GUTTER}{subject:<subject_width$}{GUTTER}{detail}",
            label = row.style.style(row.label),
            subject = row.subject,
            detail = format_args!("{BECAUSE}{}", sanitize(&row.detail)).style(palette::quiet()),
        )?;
    }
    Ok(())
}

fn write_footer(result: &DockerPruneResult, out: &mut impl io::Write) -> io::Result<()> {
    let totals = result.totals();
    let verb = if result.dry_run {
        "would be reclaimed"
    } else {
        "reclaimed"
    };
    write!(
        out,
        "{} matched, {} {verb} in the VM",
        totals.candidates.bold(),
        size(totals.bytes)
    )?;
    if let Some(returned) = totals.host_bytes_returned {
        write!(out, ", {} returned to the host", size(returned))?;
    }
    writeln!(out, " in {:.2?}", result.elapsed)?;
    if totals.failed > 0 {
        writeln!(
            out,
            "{GUTTER}{}",
            format!("{} lane(s) failed; the sweep is unaffected", totals.failed).style(palette::refused())
        )?;
    }
    Ok(())
}

/// Builds the JSON document.
#[must_use]
pub fn document(result: &DockerPruneResult) -> Value {
    let totals = result.totals();
    json!({
        "schema_version": SCHEMA_VERSION,
        "dry_run": result.dry_run,
        "status": if result.skipped.is_some() { "skipped" } else { "ready" },
        "skipped_reason": result.skipped.as_ref().map(|skip| skip.reason.as_str()),
        "endpoint": result.endpoint,
        "backend": result.backend,
        "max_age_secs": result.max_age.as_secs(),
        "volumes": result.volumes.map(VolumeScope::label),
        "lanes": result.lanes.iter().map(lane_value).collect::<Vec<_>>(),
        "trim": result.trim.as_ref().map(trim_value),
        "totals": {
            "candidates": totals.candidates,
            "bytes": totals.bytes,
            "failed": totals.failed,
            "host_bytes_returned": totals.host_bytes_returned,
        },
        "elapsed_ms": u64::try_from(result.elapsed.as_millis()).unwrap_or(u64::MAX),
    })
}

fn lane_value(lane: &Lane) -> Value {
    let (outcome, reclaimed, message) = match &lane.outcome {
        LaneOutcome::WouldReclaim => ("would_reclaim", None, None),
        LaneOutcome::Reclaimed { bytes } => ("reclaimed", *bytes, None),
        LaneOutcome::Skipped { reason } => ("skipped", None, Some(reason.as_str())),
        LaneOutcome::Failed { message } => ("failed", None, Some(message.as_str())),
    };
    json!({
        "kind": match lane.plan.kind {
            LaneKind::Images => "images",
            LaneKind::BuildCache => "build_cache",
            LaneKind::Volumes => "volumes",
        },
        "candidates": lane.plan.candidates,
        "estimated_bytes": lane.plan.estimated_bytes,
        "reclaimed_bytes": reclaimed,
        "outcome": outcome,
        "message": message,
        "commands": lane.plan.commands.iter().map(|command| format!("docker {}", command.join(" "))).collect::<Vec<_>>(),
    })
}

fn trim_value(trim: &Trim) -> Value {
    let (outcome, before, after, message) = match &trim.outcome {
        TrimOutcome::Withheld { host_bytes } => ("would_trim", *host_bytes, None, None),
        TrimOutcome::Trimmed { before, after } => ("trimmed", *before, *after, None),
        TrimOutcome::Failed { message } => ("failed", None, None, Some(message.as_str())),
    };
    json!({
        "backend": trim.backend,
        "command": trim.command.join(" "),
        "outcome": outcome,
        "host_bytes_before": before,
        "host_bytes_after": after,
        "host_bytes_returned": trim.outcome.returned(),
        "message": message,
    })
}

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

#[cfg(test)]
mod tests {
    use super::super::Skip;
    use super::super::plan::LanePlan;
    use super::*;

    fn lane(kind: LaneKind, candidates: usize, estimated: u64, outcome: LaneOutcome) -> Lane {
        Lane {
            plan: LanePlan {
                kind,
                candidates,
                estimated_bytes: estimated,
                commands: vec![vec!["image".to_owned(), "prune".to_owned()]],
                skipped: None,
            },
            outcome,
        }
    }

    fn result(lanes: Vec<Lane>, trim: Option<Trim>, dry_run: bool) -> DockerPruneResult {
        DockerPruneResult {
            dry_run,
            max_age: Duration::from_secs(7 * 86_400),
            volumes: Some(VolumeScope::Anonymous),
            skipped: None,
            endpoint: Some("unix:///home/dev/.colima/default/docker.sock".to_owned()),
            backend: Some("colima (profile default)".to_owned()),
            lanes,
            trim,
            elapsed: Duration::from_millis(1500),
        }
    }

    fn text(result: &DockerPruneResult) -> String {
        let mut buffer = Vec::new();
        render_human(result, &mut buffer).expect("writing to a Vec cannot fail");
        String::from_utf8(buffer).expect("the report is UTF-8")
    }

    #[test]
    fn should_strip_terminal_escapes_from_peer_supplied_text() {
        assert_eq!(sanitize("a\u{1b}[31mred\u{1b}[0m"), "ared");
        assert_eq!(sanitize("clip\u{1b}]52;c;AAAA\u{7}board"), "clipboard");
        assert_eq!(sanitize("bell\u{7}"), "bell");
        assert_eq!(sanitize("plain text"), "plain text");
    }

    #[test]
    fn should_report_a_dry_run_with_the_estimate_and_the_withheld_trim() {
        let trim = Trim {
            backend: "colima (profile default)".to_owned(),
            command: vec!["colima".to_owned(), "ssh".to_owned()],
            outcome: TrimOutcome::Withheld {
                host_bytes: Some(120_000_000_000),
            },
        };
        let report = text(&result(
            vec![lane(LaneKind::Images, 2, 1_600_000_000, LaneOutcome::WouldReclaim)],
            Some(trim),
            true,
        ));
        assert!(report.contains("would reclaim"), "{report}");
        assert!(report.contains("2 images, 1.60 GB"), "{report}");
        assert!(report.contains("would trim"), "{report}");
        assert!(report.contains("would be reclaimed in the VM"), "{report}");
    }

    #[test]
    fn should_report_docker_bytes_and_the_host_bytes_returned_after_a_real_run() {
        let trim = Trim {
            backend: "colima (profile default)".to_owned(),
            command: vec!["colima".to_owned()],
            outcome: TrimOutcome::Trimmed {
                before: Some(120_000_000_000),
                after: Some(80_000_000_000),
            },
        };
        let report = text(&result(
            vec![lane(
                LaneKind::Images,
                2,
                1_600_000_000,
                LaneOutcome::Reclaimed {
                    bytes: Some(1_400_000_000),
                },
            )],
            Some(trim),
            false,
        ));
        assert!(
            report.contains("1 images") || report.contains("2 images, 1.40 GB"),
            "{report}"
        );
        assert!(report.contains("40 GB returned"), "{report}");
        assert!(report.contains("returned to the host"), "{report}");
    }

    #[test]
    fn should_say_one_line_when_docker_was_skipped() {
        let mut skipped = result(Vec::new(), None, false);
        skipped.skipped = Some(Skip {
            reason: "the docker daemon is not running".to_owned(),
        });
        assert_eq!(
            text(&skipped),
            "voom: docker: the docker daemon is not running (skipped)\n"
        );
    }

    #[test]
    fn should_write_valid_json_carrying_the_schema_version_and_skip_reason() {
        let mut skipped = result(Vec::new(), None, true);
        skipped.skipped = Some(Skip {
            reason: "`docker` is not installed".to_owned(),
        });
        let mut buffer = Vec::new();
        render_json(&skipped, &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["status"], "skipped");
        assert_eq!(parsed["skipped_reason"], "`docker` is not installed");
    }

    #[test]
    fn should_name_each_lane_command_in_json() {
        let report = document(&result(
            vec![lane(LaneKind::Images, 1, 5, LaneOutcome::WouldReclaim)],
            None,
            true,
        ));
        assert_eq!(report["lanes"][0]["commands"][0], "docker image prune");
        assert_eq!(report["lanes"][0]["outcome"], "would_reclaim");
        assert_eq!(report["totals"]["bytes"], 5);
    }
}