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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
//! Argument parsing and command dispatch.
use std::io;
use std::path::{Path, PathBuf};
use clap::{ArgAction, Args, Parser, Subcommand, ValueEnum};
mod aggressive;
mod config_view;
mod housekeeping;
mod reap;
pub use reap::{ReapArgs, write_summary as write_reap_summary};
pub use housekeeping::{ClaudePruneArgs, DockerPruneArgs, GitPruneArgs, render_claude, render_docker, render_git};
use crate::catalog::CATALOG;
use crate::config::resolve::Flags;
use crate::error::Result;
use crate::policy::{KeepPolicy, parse_duration, parse_size};
use crate::report::human::HumanOptions;
use crate::report::{RunResult, human, json};
use crate::run::RunOptions;
use crate::watch::WatchOptions;
/// Fast, safe, parallel build-artifact pruning across every major language ecosystem.
///
/// voom deletes by default. `--dry-run` previews. There is no confirmation prompt — the safety
/// comes from marker anchoring and the rails, not from a question you would learn to click
/// through.
#[derive(Debug, Parser)]
#[command(name = "voom", version, about, long_about = None, args_conflicts_with_subcommands = true)]
pub struct Cli {
/// What to do instead of sweeping.
#[command(subcommand)]
pub command: Option<Command>,
/// Sweep arguments, used when no subcommand is given.
#[command(flatten)]
pub prune: PruneArgs,
}
/// Subcommands.
#[derive(Debug, Subcommand)]
pub enum Command {
/// Print the built-in ecosystem catalog.
///
/// This is generated from the same table the classifier reads, so it cannot drift from
/// what voom will actually do.
Catalog,
/// Inspect configuration.
Config {
/// What to show.
#[command(subcommand)]
action: ConfigAction,
},
/// Report repeated directories the catalog does not know about.
///
/// Ranks by what a `.gitignore` in the tree already names, since somebody has written down
/// that those are not source — and prints the `include` line that would sweep each. It
/// removes nothing, and it is slower than a sweep: it traverses twice and measures what it
/// finds.
Suggest(SuggestArgs),
/// Keep a tree pruned continuously as you work.
Watch(WatchArgs),
/// Run git's own housekeeping over every repository in a tree.
///
/// An ordinary sweep already does the local half of this; the subcommand is for running it
/// alone, and for the network step a sweep will not do (`--remotes`).
GitPrune(GitPruneArgs),
/// Reclaim scratch left behind by Claude Code's background jobs, once a job has been quiet
/// long enough and nothing on this machine is still running it.
///
/// Reports only, unless `--remove` is given: nothing on disk reliably says a job is done,
/// only how long it has been quiet. See `adrs/0015-claude-code-job-scratch.md`.
ClaudePrune(ClaudePruneArgs),
/// Reclaim Docker disk space: dangling images, unused images past an age, idle build cache,
/// and then the VM's freed blocks.
///
/// Never removes containers or anything a container uses. Volumes only with `--volumes`. See
/// `adrs/0017-docker-housekeeping.md`.
DockerPrune(DockerPruneArgs),
/// Free what earlier runs detached into the trash, waiting for a background reaper first.
Reap(ReapArgs),
}
/// `voom suggest` arguments.
#[derive(Debug, Args)]
pub struct SuggestArgs {
/// Trees to inspect.
#[arg(default_value = ".")]
pub paths: Vec<PathBuf>,
/// Do not cross filesystem boundaries.
#[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
pub one_file_system: bool,
/// Worker threads.
#[arg(short, long, value_name = "N")]
pub jobs: Option<usize>,
}
/// `voom config` actions.
#[derive(Debug, Subcommand)]
pub enum ConfigAction {
/// Print the fully merged, resolved configuration with the file each value came from.
Show {
/// The tree whose configuration to resolve.
#[arg(value_name = "PATH", default_value = ".")]
path: PathBuf,
},
}
/// Output format.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Format {
/// Colored, sorted, human-readable.
Human,
/// A single JSON object with a stable, versioned shape.
Json,
}
/// When to colorize.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum Color {
/// Colorize when stdout is a terminal, honouring `NO_COLOR` and `CLICOLOR_FORCE`.
Auto,
/// Always colorize.
Always,
/// Never colorize.
Never,
}
impl From<Color> for anstream::ColorChoice {
fn from(color: Color) -> Self {
match color {
Color::Auto => Self::Auto,
Color::Always => Self::Always,
Color::Never => Self::Never,
}
}
}
/// Everything a sweep takes.
#[expect(
clippy::struct_excessive_bools,
reason = "these are command-line flags, which are bools by nature"
)]
#[derive(Debug, Args)]
#[command(group(clap::ArgGroup::new("worktree_removal").args(["remove_merged_worktrees", "aggressive"]).multiple(true)))]
pub struct PruneArgs {
/// Trees to sweep.
#[arg(value_name = "PATH", default_value = ".")]
pub paths: Vec<PathBuf>,
/// Report what would be removed, without touching anything.
#[arg(short = 'n', long, help_heading = "Behaviour")]
pub dry_run: bool,
/// Enable all catalog artifacts, dependencies, caches, permission repair and unused Docker cleanup.
///
/// Also removes worktrees without an age limit, discarding uncommitted and ignored files,
/// and dangling checkouts whose Git metadata is gone. Detached commits are retained in Git;
/// no recovery archive is made. Artifact proofs, exclusions and keep policies still apply,
/// along with filesystem safety rails.
#[arg(long, help_heading = "Behaviour")]
pub aggressive: bool,
/// Print the per-artifact report. This is the default; the flag is accepted so the
/// published git hooks can name it explicitly.
#[arg(long, help_heading = "Behaviour")]
pub report: bool,
/// Exit 3 when a dry run finds artifacts, so a hook can fail on findings.
#[arg(long, help_heading = "Behaviour")]
pub exit_code: bool,
/// Skip git housekeeping: `git worktree prune` and `git gc --auto` in every repository swept.
///
/// Both steps are local, idempotent, and are what git itself runs after an ordinary commit —
/// which is why they are on by default. Neither contacts a network, and neither expires a
/// reflog beyond git's own policy. Also settable as `[git] enabled = false` in `voom.toml`,
/// which this flag overrides.
#[arg(long, help_heading = "Behaviour")]
pub no_git: bool,
/// Remove linked git worktrees whose work is already merged into the default branch.
///
/// Off by default and not settable from `voom.toml`: unlike the rest of git housekeeping,
/// removing a checkout can lose work. A worktree goes only when its `HEAD` is in the default
/// branch (the local `origin/HEAD`, `main` or `master`; voom never fetches), it is not
/// locked or the current directory, it sits below a path being swept, and its working tree
/// holds nothing but deleted tracked build output such as `dist/` or ignored build-output
/// trees. A merged worktree with any other local change, including an ignored `.env`, is
/// reported and kept. Branches are never deleted. With `-n`, only reports.
#[arg(long, help_heading = "Behaviour")]
pub remove_merged_worktrees: bool,
/// With `--remove-merged-worktrees`, also recognize squash/rebase merges using exact HEAD
/// matches to merged GitHub PRs.
///
/// Contacts github.com through `gh`; lookup failure keeps the checkout. The same clean
/// working-tree and containment checks apply. HEADs proved only by GitHub are retained under
/// `refs/voom/merged-worktrees/` before removal.
#[arg(long, requires = "worktree_removal", help_heading = "Behaviour")]
pub github_merged_worktrees: bool,
/// With `--remove-merged-worktrees`, also remove worktrees that are not merged but have been
/// idle at least this long, e.g. `30d`.
///
/// Idle is the later of the `HEAD` commit's date and the last commit, checkout or rebase
/// recorded in the worktree's reflog. Only a worktree whose commits are reachable from
/// another ref goes (removal keeps the branch; a detached `HEAD` nothing else reaches never
/// does), and the same working-tree rule applies as for a merged one: nothing but deleted
/// build output may differ. Off unless given.
#[arg(
long,
value_name = "DURATION",
requires = "worktree_removal",
help_heading = "Behaviour"
)]
pub stale_worktrees: Option<String>,
/// Skip Bazel housekeeping: output bases that are orphaned, abandoned or idle for longer
/// than `--bazel-max-age`, install bases nothing uses, and stale downloads.
///
/// Runs beside the sweep, over the conventional output-user-roots, and is silent when there
/// is nothing to do. A base with a running server is never touched. `--clear-caches` clears
/// Bazel completely instead.
#[arg(long, help_heading = "Behaviour")]
pub no_bazel: bool,
/// How long an output base may go unbuilt in before the sweep treats it as stale, e.g. `14d`.
#[arg(long, value_name = "DURATION", help_heading = "Behaviour")]
pub bazel_max_age: Option<String>,
/// Also prune Docker beside the sweep: dangling images, unused images older than
/// `--docker-max-age`, idle build cache, then trim the VM's disk.
///
/// Off by default because it talks to a daemon. Never touches containers or anything a
/// container uses. A missing docker, a stopped daemon or a refused socket is one line on
/// stderr, never a failure. Also `[docker] enabled = true`.
#[arg(long, help_heading = "Behaviour")]
pub docker: bool,
/// How old an unused Docker image or idle build-cache record must be, e.g. `7d`.
#[arg(long, value_name = "DURATION", help_heading = "Behaviour")]
pub docker_max_age: Option<String>,
/// With `--docker`, also remove anonymous volumes no container mounts. Volumes are data.
///
/// Only volumes docker created without a name; `--docker-volumes-all` also takes named ones.
/// Command line only, never `voom.toml`.
#[arg(long, requires = "docker", help_heading = "Behaviour")]
pub docker_volumes: bool,
/// With `--docker`, also remove every volume no container mounts, named ones included.
#[arg(long, requires = "docker", help_heading = "Behaviour")]
pub docker_volumes_all: bool,
/// Retry a failed removal, repairing permissions inside the artifact first.
///
/// Clears read-only bits, and on macOS the user-immutable flag, on paths *inside* an
/// artifact that has already passed every safety rail — then retries with a short backoff.
/// It never relaxes a rail, never follows a symlink, never widens a hard-linked file, and
/// never touches anything outside the artifact, including its parent directory: an artifact
/// held by a read-only parent is reported, not forced. Retries add up to about a second per
/// artifact. No effect under `--dry-run`.
///
/// A repair that does not go on to succeed is not undone: an artifact voom could not remove
/// even with `--force` is left with the owner's write bit set on the directories inside it.
///
/// Filed under Behaviour rather than Safety deliberately — it is not one of the protections.
#[arg(long, help_heading = "Behaviour")]
pub force: bool,
/// Unlink every artifact before exiting, instead of detaching it into the trash for a
/// background reaper to free. Also set by `VOOM_WAIT=1`.
#[arg(long, help_heading = "Behaviour")]
pub wait: bool,
/// Explain every candidate that was passed over, and expand `--list-caches` to the whole
/// table rather than only the caches present on this machine.
#[arg(short, long, help_heading = "Output")]
pub verbose: bool,
/// Print only the totals footer.
#[arg(long, help_heading = "Output")]
pub summary: bool,
/// Output format.
#[arg(long, value_enum, default_value_t = Format::Human, help_heading = "Output")]
pub format: Format,
/// When to colorize output.
#[arg(long, value_enum, default_value_t = Color::Auto, help_heading = "Output")]
pub color: Color,
/// Worker threads. Lower this on spinning disks and network filesystems.
#[arg(short = 'j', long, value_name = "N", help_heading = "Behaviour")]
pub jobs: Option<usize>,
/// Stay on the scan root's filesystem.
///
/// `require_equals` is what makes `voom --one-file-system ~` work. Without it an optional
/// value is greedy, so clap reads the path that follows as the flag's value and rejects the
/// run — on a safety flag, in the ordinary invocation.
#[arg(
long,
value_name = "BOOL",
num_args = 0..=1,
require_equals = true,
default_value_t = true,
default_missing_value = "true",
action = ArgAction::Set,
help_heading = "Safety"
)]
pub one_file_system: bool,
/// Never remove an artifact modified more recently than this, e.g. `7d`.
#[arg(long, value_name = "DURATION", help_heading = "Keep policies")]
pub min_age: Option<String>,
/// Skip artifacts smaller than this, e.g. `1MB`.
#[arg(long, value_name = "SIZE", help_heading = "Keep policies")]
pub min_size: Option<String>,
/// Skip artifacts larger than this, e.g. `50GB`.
#[arg(long, value_name = "SIZE", help_heading = "Keep policies")]
pub max_size: Option<String>,
/// Only sweep these ecosystems. Repeatable.
#[arg(short = 'e', long, value_name = "ID", help_heading = "Selection")]
pub ecosystem: Vec<String>,
/// Turn on an off-by-default artifact, e.g. `python.venv`. Repeatable.
#[arg(long, value_name = "SPEC", help_heading = "Selection")]
pub enable: Vec<String>,
/// Turn off an ecosystem or artifact. Repeatable.
#[arg(long, value_name = "SPEC", help_heading = "Selection")]
pub disable: Vec<String>,
/// Also remove dependency directories: `node_modules/`, Rust, composer and Go `vendor/`,
/// mix `deps/`, and Python virtualenvs.
///
/// These are network-fetched caches rather than build output, so removing one costs a
/// re-download and can break offline work — which is why voom leaves them alone unless you
/// say otherwise. Exactly equivalent to `--enable`-ing each of the specs it covers, so a
/// marker still has to prove every directory it removes and every keep policy still applies.
#[arg(long, help_heading = "Selection")]
pub clean_dependencies: bool,
/// Never scan these paths. Repeatable.
///
/// A relative pattern is relative to the tree being swept, the same rule a `voom.toml`
/// follows for its own directory. `~` expands, and a pattern starting `**` is left alone.
#[arg(long, value_name = "GLOB", help_heading = "Selection")]
pub exclude: Vec<String>,
/// Remove these paths whether or not a marker proves them. Repeatable.
///
/// The escape hatch for build output the catalog does not know about — a tool's per-project
/// cache, an unconventional target directory. A matched path is taken whole and never
/// descended into, and it outranks every prune, so an `--include` can name a directory the
/// walker would otherwise skip. It cannot reach *inside* one, and `--exclude` still beats
/// it.
///
/// Relative patterns follow the same rule as `--exclude`: relative to the tree being
/// swept. This is the one way to remove a directory nothing proved, so it is worth being
/// exact about — the same list can live in `voom.toml` as `include = [...]` once you are
/// sure.
#[arg(long, value_name = "GLOB", help_heading = "Selection")]
pub include: Vec<String>,
/// Remove named machine-global tool caches; with no ids, remove every cache the table
/// knows about, and tagged build caches under the swept tree.
///
/// Each is proven the way everything else is — by a marker the tool wrote inside the
/// directory, at a location that names the tool — and a cache is never removed unless it
/// lies under the tree being swept. A bare `--clean-caches` (also spelled
/// `--clear-caches`) asks for the whole table, the same list `--clean-caches=all` names; the
/// full clear also enables `--clean-tagged`, reaching relocated Cargo targets and other
/// build caches with valid tags. Named ids keep their narrower scope. The ids form is
/// `--clean-caches=uv,go-build`, repeatable for several. The `=` is required so
/// the flag can never swallow the next path argument.
///
/// Run `--list-caches` for the table, what each one costs to lose, and whether it exists
/// here. `bazel` is a reserved id, not a table row: `--clean-caches=bazel` (or a bare
/// `--clean-caches`) clears Bazel's output bases, install bases and download cache
/// machine-wide, stopping running servers first.
///
/// An id prefixed with `-` is taken back out: `--clean-caches=all,-bazel` is the whole table
/// without the Bazel clear.
#[arg(
long,
visible_alias = "clear-caches",
allow_hyphen_values = true,
value_name = "IDS",
num_args = 0..=1,
require_equals = true,
default_missing_value = "all",
value_delimiter = ',',
help_heading = "Selection"
)]
pub clean_caches: Vec<String>,
/// Print the machine-global tool caches `--clean-caches` can remove, and exit without
/// scanning.
///
/// By default only the caches present on this machine, each with its path;
/// `--verbose` prints the whole table, absent locations and markers included.
#[arg(long, help_heading = "Output")]
pub list_caches: bool,
/// With `--list-caches`, measure each cache and print its size.
///
/// Off by default because sizing is the slow part: a machine's caches run to tens of
/// gigabytes and millions of files, and the listing is otherwise instant. The figure comes
/// from the sizer the sweep uses, so it is what `--clean-caches` would reclaim.
#[arg(long, requires = "list_caches", help_heading = "Output")]
pub sizes: bool,
/// Remove directories that declare themselves regenerable with a `CACHEDIR.TAG`.
///
/// The [tag](https://bford.info/cachedir/) is a file a tool writes inside its own cache to
/// say the contents can be rebuilt; `tar --exclude-caching`, `rsync --exclude-tag`, Borg and
/// restic all honour it. It is the one proof that does not depend on a name or a location, so
/// it reaches what the catalog cannot: a `CARGO_TARGET_DIR` pointed at `/tmp`, a build
/// directory somebody renamed, a cache belonging to a tool voom has never heard of.
///
/// Never on by default, for that same reason — it will take a directory of any name. voom
/// verifies the tag's signature rather than trusting the filename, an anchored artifact still
/// wins where both apply, and every keep policy and safety rail is unchanged. Also settable
/// as `[tagged] enabled = true` in `voom.toml`. A full `--clean-caches` clear also enables
/// this; either flag overrides the configuration.
#[arg(long, help_heading = "Selection")]
pub clean_tagged: bool,
/// Use this configuration file instead of the discovered hierarchy.
#[arg(long, value_name = "PATH", help_heading = "Selection")]
pub config: Option<PathBuf>,
}
/// Watch-mode arguments.
#[derive(Debug, Args)]
pub struct WatchArgs {
/// Trees to keep pruned.
#[arg(value_name = "PATH", default_value = ".")]
pub paths: Vec<PathBuf>,
/// Coalesce filesystem events over this window.
#[arg(long, value_name = "DURATION", default_value = "5s")]
pub debounce: String,
/// Only remove an artifact after its subtree has been idle this long.
#[arg(long, value_name = "DURATION", default_value = "60s")]
pub quiet_period: String,
}
impl WatchArgs {
/// The pipeline options for a watch, taking the sweep flags from the top-level arguments.
///
/// # Errors
///
/// Whatever [`PruneArgs::flags`] rejects.
pub fn to_run_options(&self, prune: &PruneArgs) -> Result<RunOptions> {
let mut options = prune.to_run_options()?;
options.roots.clone_from(&self.paths);
Ok(options)
}
/// The debounce and quiet-period windows.
///
/// # Errors
///
/// [`crate::error::Error::InvalidDuration`] for an unparseable window.
pub fn to_watch_options(&self) -> Result<WatchOptions> {
Ok(WatchOptions {
debounce: parse_duration(&self.debounce)?,
quiet_period: parse_duration(&self.quiet_period)?,
})
}
}
impl PruneArgs {
/// The Bazel housekeeping a sweep runs after the artifacts, or `None` when the resolved
/// configuration (`--no-bazel`, `[bazel] enabled`) turned it off.
///
/// A full clear when `--clear-caches` named Bazel (which a bare flag does), otherwise the
/// age-based prune.
#[must_use]
pub fn bazel_options(&self, resolved: &crate::config::Resolved) -> Option<crate::bazel::BazelPruneOptions> {
if !resolved.bazel {
return None;
}
let mut options = crate::bazel::BazelPruneOptions::conventional(self.dry_run, self.one_file_system);
options.force = self.force || self.aggressive;
if let Some(age) = resolved.bazel_max_age {
options.max_age = age;
}
options.clear_all = resolved.clean_caches.iter().any(|id| id == crate::caches::BAZEL_ID);
options.jobs = self.jobs;
Some(options)
}
/// The Docker housekeeping a sweep runs beside the artifacts, or `None` unless `--docker` or
/// `[docker] enabled` asked for it.
#[must_use]
pub fn docker_options(&self, resolved: &crate::config::Resolved) -> Option<crate::docker::DockerPruneOptions> {
resolved.docker.then(|| crate::docker::DockerPruneOptions {
dry_run: self.dry_run,
max_age: resolved.docker_max_age.unwrap_or(crate::docker::DEFAULT_MAX_AGE),
volumes: housekeeping::volume_scope(self.docker_volumes, self.docker_volumes_all),
..crate::docker::DockerPruneOptions::default()
})
}
/// Turns flags into the overrides that sit above every configuration layer.
///
/// # Errors
///
/// [`Error::InvalidDuration`] or [`Error::InvalidSize`] for an unparseable keep value.
pub fn flags(&self) -> Result<Flags> {
Ok(Flags {
ecosystems: (!self.ecosystem.is_empty()).then(|| self.ecosystem.clone()),
enable: self.enable_specs(),
disable: self.disable.clone(),
keep: self.keep()?,
exclude: self.exclude.clone(),
include: self.include.clone(),
clean_caches: self.cache_specs(),
clean_tagged: (self.clean_tagged || self.aggressive).then_some(true),
// Only ever `Some(false)`: the flag can turn housekeeping off, and nothing turns it
// on, because it is already on.
git: self.no_git.then_some(false),
bazel: self.no_bazel.then_some(false),
bazel_max_age: self.bazel_max_age.as_deref().map(parse_duration).transpose()?,
// Only ever `Some(true)`: the flag can turn Docker on, and nothing turns it off,
// because it is already off.
docker: (self.docker || self.aggressive).then_some(true),
docker_max_age: self
.docker_max_age
.as_deref()
.map(parse_duration)
.transpose()?
.or(self.aggressive.then_some(std::time::Duration::ZERO)),
})
}
/// Turns flags into keep policies.
///
/// # Errors
///
/// [`Error::InvalidDuration`] or [`Error::InvalidSize`] for an unparseable value.
pub fn keep(&self) -> Result<KeepPolicy> {
Ok(KeepPolicy {
min_age: self.min_age.as_deref().map(parse_duration).transpose()?,
min_size: self.min_size.as_deref().map(parse_size).transpose()?,
max_size: self.max_size.as_deref().map(parse_size).transpose()?,
})
}
/// Assembles the run.
///
/// # Errors
///
/// Whatever [`Self::flags`] rejects.
pub fn to_run_options(&self) -> Result<RunOptions> {
Ok(RunOptions {
roots: self.paths.clone(),
dry_run: self.dry_run,
jobs: self.jobs,
one_file_system: self.one_file_system,
force: self.force || self.aggressive,
// JSON always carries skip detail — a machine consumer has no `--verbose` to reach
// for and paying for the detail is cheaper than a second run.
verbose: self.verbose || self.format == Format::Json,
config: self.config.clone(),
flags: self.flags()?,
// A spinner is only useful for a human watching a scan scroll past; JSON and
// summary output would only be interrupted by it.
progress: self.format == Format::Human && !self.summary,
})
}
}
/// Renders a finished run in the requested format.
///
/// # Errors
///
/// Propagates write failures.
pub fn render(result: &RunResult, args: &PruneArgs, out: &mut impl io::Write) -> io::Result<()> {
match args.format {
Format::Human => {
let options = HumanOptions {
verbose: args.verbose,
summary_only: args.summary,
forced: args.force,
};
human::render(result, options, out)
}
Format::Json => json::render(result, out),
}
}
/// Prints what a tree keeps repeating that the catalog does not claim.
///
/// # Errors
///
/// Propagates write failures.
pub fn render_suggestions(suggestions: &[crate::suggest::Suggestion], out: &mut impl io::Write) -> io::Result<()> {
use owo_colors::OwoColorize;
if suggestions.is_empty() {
return writeln!(
out,
"Nothing repeated that a `.gitignore` here names and the catalog does not already handle."
);
}
for suggestion in suggestions {
writeln!(
out,
" {:>10} {} {}",
humansize::format_size(suggestion.bytes, humansize::DECIMAL).bold(),
Path::new(&suggestion.name).display(),
format_args!("across {} directories", suggestion.paths.len()).dimmed()
)?;
}
writeln!(out)?;
writeln!(out, "Add to voom.toml what you recognise:")?;
writeln!(out)?;
for suggestion in suggestions {
writeln!(out, " {}", suggestion.include_line())?;
}
writeln!(out)?;
writeln!(
out,
"{}",
"Read the list before pasting it. A `.gitignore` also lists local configuration and \
scratch data, which is why voom suggests rather than sweeps."
.dimmed()
)
}
/// Prints the cache table, resolved against this machine.
///
/// By default only the caches that actually exist here: one line per location. `--verbose`
/// prints the whole table — every known location with whether it is present and whether a
/// marker proves it, the markers themselves, and what removing each cache costs. `measure`
/// adds how much disk each present location holds; it is opt-in because sizing is the only
/// part of this that is not instant.
///
/// # Errors
///
/// Propagates write failures.
pub fn render_caches(out: &mut impl io::Write, verbose: bool, measure: bool) -> io::Result<()> {
let home = dirs::home_dir();
let sizes = if measure {
present_cache_sizes(home.as_deref())
} else {
std::collections::HashMap::new()
};
let size_of = |path: &Path| {
if measure {
humansize::format_size(sizes.get(path).copied().unwrap_or(0), humansize::DECIMAL)
} else {
String::new()
}
};
if verbose {
render_cache_table(out, home.as_deref(), &size_of)
} else {
render_cache_list(out, home.as_deref(), &size_of)
}
}
/// The whole table: every known location with its state, the markers, and what losing each costs.
fn render_cache_table(
out: &mut impl io::Write,
home: Option<&Path>,
size_of: &dyn Fn(&Path) -> String,
) -> io::Result<()> {
use owo_colors::OwoColorize;
for cache in crate::caches::CACHES {
writeln!(out, "{} {}", cache.name.bold(), format_args!("({})", cache.id).dimmed())?;
for location in cache.locations {
// The state is resolved against this machine rather than described in the
// abstract, because the question a reader actually has is whether the entry is
// worth naming *here* — and "present but unproven" is a real answer that a table
// of paths alone could not give.
let resolved = home.map(|home| home.join(location));
let (size, state) = match resolved.as_deref() {
Some(path) if !path.is_dir() => (String::new(), "not on this machine".dimmed().to_string()),
Some(path) => {
let size = size_of(path);
let state = if cache.proven_in(path) {
"present".green().to_string()
} else {
"present, but no marker proves it".yellow().to_string()
};
(size, state)
}
None => (String::new(), "home directory unknown".dimmed().to_string()),
};
let size = if size.is_empty() {
String::new()
} else {
format!("{size:>12}")
};
writeln!(out, " ~/{location} {size} {state}")?;
}
writeln!(out, " markers: {} (inside)", cache.markers.join(", "))?;
if !cache.in_all {
writeln!(
out,
" {}",
"not part of a bare --clean-caches; name it to remove it".yellow()
)?;
}
writeln!(out, " {}", cache.note.dimmed())?;
writeln!(out)?;
}
writeln!(
out,
"None of these is ever removed unless it lies under the tree being swept, and never \
without its marker. A bare `--clean-caches` removes every cache; `--clean-caches=<id>` \
removes one, comma-separated for several."
)?;
writeln!(
out,
"The same ids can sit in `[caches] enable = [\"<id>\"]` in voom.toml."
)?;
writeln!(
out,
"{}",
"A cache is only reachable when it lies under the tree being swept.".dimmed()
)?;
writeln!(
out,
"`bazel` is a reserved id, not a row here: a bare `--clean-caches` or \
`--clean-caches=bazel` clears Bazel's output bases, install bases and download cache \
machine-wide, stopping running servers first."
)
}
/// The caches present on this machine, one line per location.
fn render_cache_list(
out: &mut impl io::Write,
home: Option<&Path>,
size_of: &dyn Fn(&Path) -> String,
) -> io::Result<()> {
use owo_colors::OwoColorize;
let mut rows: Vec<(&str, String)> = Vec::new();
for cache in crate::caches::CACHES {
for location in cache.locations {
let Some(path) = home.map(|home| home.join(location)) else {
continue;
};
if !path.is_dir() {
continue;
}
rows.push((location, size_of(&path)));
}
}
if rows.is_empty() {
writeln!(out, "{}", "No known tool caches found on this machine.".bold())?;
} else {
// The path column is padded to its longest row so the sizes line up.
let width = rows
.iter()
.map(|(location, _)| location.chars().count())
.max()
.unwrap_or(0);
for (location, size) in rows {
if size.is_empty() {
writeln!(out, " {}", format!("~/{location}").dimmed())?;
} else {
writeln!(out, " {} {size:>12}", format!("~/{location:<width$}").dimmed())?;
}
}
}
writeln!(out)?;
writeln!(
out,
"{}",
"Only caches present on this machine are listed. None is removed unless it lies under \
the swept tree and its marker proves it — `--verbose` for the whole table, `--sizes` \
for how much each holds."
.dimmed()
)?;
writeln!(
out,
"{}",
"`bazel` is also clearable: a bare `--clean-caches` or `--clean-caches=bazel` clears \
Bazel's output bases machine-wide, stopping running servers first."
.dimmed()
)
}
/// The size of every known cache location that exists on this machine.
///
/// Measured once, in parallel, with the same [`crate::size`] walker the sweep uses, so the
/// figure is what `--clean-caches` would actually reclaim.
fn present_cache_sizes(home: Option<&Path>) -> std::collections::HashMap<PathBuf, u64> {
let paths: Vec<PathBuf> = crate::caches::CACHES
.iter()
.flat_map(|cache| cache.locations)
.filter_map(|location| home.map(|home| home.join(location)))
.filter(|path| path.is_dir())
.collect();
let measured = crate::size::measure_all(&paths);
paths
.into_iter()
.zip(measured)
.map(|(path, measured)| (path, measured.bytes))
.collect()
}
/// Prints the built-in catalog.
///
/// # Errors
///
/// Propagates write failures.
pub fn render_catalog(out: &mut impl io::Write) -> io::Result<()> {
use owo_colors::OwoColorize;
for ecosystem in CATALOG {
writeln!(
out,
"{} {}",
ecosystem.name.bold(),
format_args!("({})", ecosystem.id).dimmed()
)?;
writeln!(out, " markers: {}", ecosystem.markers.join(", "))?;
let anchor = match ecosystem.anchor {
crate::catalog::Anchor::Sibling => "sibling".to_owned(),
crate::catalog::Anchor::Ancestor(levels) => format!("ancestor({levels})"),
crate::catalog::Anchor::Inside => "inside".to_owned(),
crate::catalog::Anchor::WorkspaceRoot => "workspace-root".to_owned(),
};
writeln!(out, " anchor: {anchor}")?;
for artifact in ecosystem.artifacts {
let state = if artifact.default_on { "on " } else { "off" };
write!(
out,
" {state} {:<24} {}.{}",
artifact.path,
ecosystem.id,
artifact.slug()
)?;
match artifact.note {
Some(note) => writeln!(out, "\n {}", note.dimmed())?,
None => writeln!(out)?,
}
}
writeln!(out)?;
}
writeln!(
out,
"{}",
"`off` artifacts need an explicit opt-in: --enable <spec>, or in voom.toml.".dimmed()
)?;
writeln!(
out,
"{}",
format_args!(
"`--clean-dependencies` enables the dependency directories together: {}.",
crate::catalog::DEPENDENCY_ARTIFACTS.join(", ")
)
.dimmed()
)
}
/// Prints the fully merged, resolved configuration with the files it came from.
///
/// A hierarchical merge nobody can inspect is a hierarchical merge nobody can trust — this is
/// what a user reaches for when asking "why did it delete that?" (ADR 0004).
///
/// # Errors
///
/// [`crate::error::Error::Config`] if a configuration file is broken, or a write failure.
pub fn render_config(root: &Path, args: &PruneArgs, out: &mut impl io::Write) -> Result<()> {
let mut options = args.to_run_options()?;
options.roots = vec![root.to_path_buf()];
let merged = crate::run::resolver_for(root, &options)?.root_config()?;
config_view::write_merged(out, &merged).map_err(|error| crate::error::Error::Config {
path: root.to_path_buf(),
reason: error.to_string(),
})
}