Repository navigation
Expand file tree
/
Copy pathmain.rs
More file actions
417 lines (385 loc) · 14.7 KB
/
Copy pathmain.rs
File metadata and controls
417 lines (385 loc) · 14.7 KB
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
use anyhow::{Context, Result};
use clap::{Parser, Subcommand, ValueEnum};
use diskern_core::{
ai::{AiProvider, TemplateNarrator},
human_bytes, report,
rules::RulesDb,
scanner, Category, Finding, Verdict,
};
use std::path::PathBuf;
use std::sync::Arc;
mod output;
#[derive(Parser)]
#[command(
name = "diskern",
about = "Diskern — understand your disk before you clean it"
)]
struct Cli {
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Read-only scan: find duplicates, caches, and reclaimable space.
Scan {
/// Directories to scan
#[arg(required = true)]
roots: Vec<PathBuf>,
/// Directories to skip while scanning; may be repeated
#[arg(long, value_name = "DIR")]
exclude: Vec<PathBuf>,
/// Emit full JSON report instead of a summary
#[arg(long)]
json: bool,
/// Write the JSON report to a file instead of stdout; requires --json
#[arg(long, value_name = "FILE", requires = "json")]
output: Option<PathBuf>,
/// Print a deterministic plain-language explanation of the report
#[arg(long)]
explain: bool,
/// Show at most N findings per category; 0 shows every one
#[arg(long, value_name = "N", default_value_t = 5)]
top: usize,
/// Only show findings with this verdict
#[arg(long, value_enum)]
verdict: Option<VerdictFilter>,
/// Load rules from a JSON file; embedded protected rules still apply
#[arg(long, value_name = "FILE")]
rules: Option<PathBuf>,
},
}
/// Mirrors `Verdict` for clap. The core enum can't derive `ValueEnum`
/// without diskern-core taking a dependency on the CLI's argument parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
enum VerdictFilter {
Safe,
Review,
Risky,
Protected,
}
impl From<VerdictFilter> for Verdict {
fn from(v: VerdictFilter) -> Self {
match v {
VerdictFilter::Safe => Verdict::Safe,
VerdictFilter::Review => Verdict::Review,
VerdictFilter::Risky => Verdict::Risky,
VerdictFilter::Protected => Verdict::Protected,
}
}
}
/// Suffix for English pluralization: empty for 1, "s" for any other count.
fn plural(n: usize) -> &'static str {
if n == 1 {
""
} else {
"s"
}
}
/// Display strings live in the CLI, not in diskern-core — the engine is
/// deliberately UI-agnostic. These mirror the labels the desktop app uses
/// so the two front ends describe the same finding the same way.
fn verdict_label(v: Verdict) -> &'static str {
match v {
Verdict::Safe => "Safe to remove",
Verdict::Review => "Review first",
Verdict::Risky => "Risky — not recommended",
Verdict::Protected => "Protected — do not touch",
}
}
fn category_label(c: Category) -> &'static str {
match c {
Category::BrowserCache => "Browser cache",
Category::BuildArtifact => "Build artifacts",
Category::PackageManagerCache => "Package manager cache",
Category::TempFile => "Temporary files",
Category::Log => "Logs",
Category::Installer => "Installers",
Category::SystemCritical => "System critical",
Category::Unknown => "Unrecognized",
}
}
/// Group by category, biggest reclaimable total first. Findings arrive
/// already sorted by size, so each group keeps that order.
fn by_category<'a>(findings: &[&'a Finding]) -> Vec<(Category, Vec<&'a Finding>)> {
let mut groups: Vec<(Category, Vec<&'a Finding>)> = Vec::new();
for &f in findings {
// position(), not iter_mut().find() — the latter keeps `groups`
// mutably borrowed through the None arm, which then can't push.
match groups.iter().position(|(c, _)| *c == f.category) {
Some(i) => groups[i].1.push(f),
None => groups.push((f.category, vec![f])),
}
}
groups.sort_by_key(|(_, items)| {
std::cmp::Reverse(items.iter().map(|f| f.reclaimable).sum::<u64>())
});
groups
}
/// Verdict, then category, then the findings themselves with the rule that
/// matched. Verdicts are printed in ascending order — safest first — which
/// is also what `Verdict`'s Ord derives.
fn print_findings(findings: &[&Finding], top: usize) {
for verdict in [
Verdict::Safe,
Verdict::Review,
Verdict::Risky,
Verdict::Protected,
] {
let group: Vec<&Finding> = findings
.iter()
.copied()
.filter(|f| f.verdict == verdict)
.collect();
if group.is_empty() {
continue;
}
// Issue #100. A risky finding's `reclaimable` is deliberately
// zero — nothing will offer to move it — but as a row's size
// column that printed `0 B` next to files that are anything but,
// hiding the number the reader wants: how big the thing they're
// being warned about is. Rows in this section show the file's
// real size, while the totals keep reporting reclaimable bytes —
// and say so, so a large risky file can't be mistaken for space
// on offer.
let risky = verdict == Verdict::Risky;
let total_label = if risky { " reclaimable" } else { "" };
let total: u64 = group.iter().map(|f| f.reclaimable).sum();
println!();
println!(
"{} — {} finding{} · {}{}",
verdict_label(verdict),
group.len(),
plural(group.len()),
human_bytes(total),
total_label
);
for (category, items) in by_category(&group) {
let subtotal: u64 = items.iter().map(|f| f.reclaimable).sum();
println!(
" {} · {} · {}{}",
category_label(category),
items.len(),
human_bytes(subtotal),
total_label
);
let shown = if top == 0 {
items.len()
} else {
top.min(items.len())
};
for f in &items[..shown] {
let size = if risky { f.entry.size } else { f.reclaimable };
println!(" {:>9} {}", human_bytes(size), f.entry.path.display());
// Every reason, not just the matched rule. The rule says
// what the file is; the rest say why this copy of it got
// the verdict it did — "referenced by 3 projects" is the
// line that explains a risky node_modules, and printing
// only the first hid exactly that.
for reason in &f.reasons {
println!(" {:>9} {reason}", "");
}
}
if shown < items.len() {
println!(" {:>9} … {} more", "", items.len() - shown);
}
}
}
}
fn load_rules(path: Option<&std::path::Path>) -> Result<RulesDb> {
let Some(path) = path else {
return Ok(RulesDb::embedded());
};
let contents = std::fs::read(path).with_context(|| {
format!(
"could not read rules file '{}'; check that it exists and is readable",
path.display()
)
})?;
let rules: RulesDb = serde_json::from_slice(&contents)
.with_context(|| format!("could not parse rules file '{}' as JSON", path.display()))?;
rules.validate().with_context(|| {
format!(
"could not validate rules file '{}'; every pattern must be a valid glob",
path.display()
)
})?;
Ok(rules.with_embedded_protected_rules())
}
fn scan_options(roots: Vec<PathBuf>, excludes: Vec<PathBuf>) -> Result<scanner::ScanOptions> {
let mut opts = scanner::ScanOptions {
roots,
..Default::default()
};
for exclude in excludes {
let absolute = std::path::absolute(&exclude).with_context(|| {
format!(
"could not normalize exclude path '{}'; check that the path is valid",
exclude.display()
)
})?;
opts.excludes.push(absolute.to_string_lossy().into_owned());
}
Ok(opts)
}
fn main() -> Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),
)
.with_writer(std::io::stderr)
.init();
let cli = Cli::parse();
match cli.command {
Command::Scan {
roots,
exclude,
json,
output,
explain,
top,
verdict,
rules,
} => {
let external_rules = rules.as_deref();
let rules_db = load_rules(external_rules)?;
let opts = scan_options(roots, exclude)?;
let progress = Arc::new(scanner::ScanProgress::default());
let entries = scanner::scan(&opts, progress)?;
let report = report::build(entries, &rules_db);
if json {
if let Some(path) = external_rules {
eprintln!("Using external rules database: {}", path.display());
}
let rendered = serde_json::to_string_pretty(&report)?;
match output {
// Issue #166. A file beats a stdout dump for large
// scans: nothing to page through, and the report
// survives the terminal. stdout stays clean so the
// command composes in scripts either way.
Some(path) => {
output::write_json(&path, &rendered).with_context(|| {
format!(
"could not write JSON report to '{}'; check that the directory exists and is writable",
path.display()
)
})?;
eprintln!("Wrote JSON report to {}", path.display());
}
None => println!("{rendered}"),
}
} else {
println!(
"Scanned {} file{}.",
report.files_scanned,
plural(report.files_scanned as usize)
);
if let Some(path) = external_rules {
println!("Rules: external database — {}", path.display());
}
println!(
"Reclaimable: {} across {} finding{} and {} duplicate set{}.",
human_bytes(report.total_reclaimable),
report.findings.len(),
plural(report.findings.len()),
report.duplicate_sets.len(),
plural(report.duplicate_sets.len())
);
// Filter after the summary line, so the headline totals
// still describe the whole scan rather than the slice.
let wanted = verdict.map(Verdict::from);
let findings: Vec<&Finding> = report
.findings
.iter()
.filter(|f| wanted.is_none_or(|v| f.verdict == v))
.collect();
if explain {
println!();
println!("Explanation:");
println!("{}", TemplateNarrator.narrate(&report.findings)?);
}
print_findings(&findings, top);
// Duplicates have no verdict of their own, so a --verdict
// filter is asking about findings only; hide them then.
if verdict.is_none() && !report.duplicate_sets.is_empty() {
let wasted: u64 = report.duplicate_sets.iter().map(|d| d.wasted).sum();
println!();
println!(
"Duplicate files — {} set{} · {} wasted",
report.duplicate_sets.len(),
plural(report.duplicate_sets.len()),
human_bytes(wasted)
);
let dup_shown = if top == 0 {
report.duplicate_sets.len()
} else {
top.min(report.duplicate_sets.len())
};
for set in report.duplicate_sets.iter().take(dup_shown) {
println!(
" {:>9} x{} copies {}",
human_bytes(set.wasted),
set.paths.len(),
set.paths[0].display()
);
}
if dup_shown < report.duplicate_sets.len() {
println!(
" {:>9} … {} more",
"",
report.duplicate_sets.len() - dup_shown
);
}
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{human_bytes, plural, scan_options, Cli};
use clap::{error::ErrorKind, Parser};
use std::path::PathBuf;
#[test]
fn scan_requires_at_least_one_root() {
let error = match Cli::try_parse_from(["diskern", "scan"]) {
Ok(_) => panic!("scan without roots should be rejected"),
Err(error) => error,
};
assert_eq!(error.kind(), ErrorKind::MissingRequiredArgument);
}
#[test]
fn scan_options_append_cli_excludes_to_defaults() {
let before = diskern_core::scanner::ScanOptions::default().excludes.len();
let opts = scan_options(vec![PathBuf::from(".")], vec![PathBuf::from("target")]).unwrap();
assert_eq!(opts.roots, vec![PathBuf::from(".")]);
assert_eq!(opts.excludes.len(), before + 1);
assert!(opts.excludes.last().unwrap().ends_with("target"));
}
#[test]
fn plural_returns_empty_only_for_singular() {
assert_eq!(plural(0), "s");
assert_eq!(plural(1), "");
assert_eq!(plural(2), "s");
assert_eq!(plural(10), "s");
}
#[test]
fn scales_to_a_readable_unit() {
assert_eq!(human_bytes(0), "0 B");
assert_eq!(human_bytes(999), "999 B");
assert_eq!(human_bytes(1_000), "1.0 KB");
assert_eq!(human_bytes(1_500_000), "1.5 MB");
assert_eq!(human_bytes(2_300_000_000), "2.3 GB");
}
#[test]
fn rolls_over_instead_of_printing_a_four_digit_mantissa() {
assert_eq!(human_bytes(999_949), "999.9 KB");
assert_eq!(human_bytes(999_999), "1.0 MB");
assert_eq!(human_bytes(999_999_999), "1.0 GB");
}
#[test]
fn stops_at_the_largest_unit_it_knows() {
assert_eq!(human_bytes(u64::MAX), "18446744.1 TB");
}
}