cargo-reclaim 0.2.1

Safe Cargo cleanup for target directories, stale artifacts, and Cargo home caches
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
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
use std::collections::HashSet;
use std::ffi::OsString;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, SystemTime};

use cargo_reclaim::{
    ActiveObservationProvider, ApplyReport, ArtifactClass,
    BuildPlanFromScanItemsWithProviderRequest, InventoryOptions, Plan, PlanAction, PlanCommandKind,
    PlanEntry, PlanInput, PlanInvocation, PlannerOptions, PolicyKind, SavePlanOptions, ScanItem,
    ScannerOptions, TargetCandidateKind, TargetEvidence, WholeTargetMode,
    build_plan_from_roots_with_active_observation_provider,
    build_plan_from_scan_items_with_active_observation_provider, execute_persisted_plan_apply,
    load_config_from_path, persist_plan, resolve_command_toolchain_hash_options, scan_roots,
    snapshot_path, validate_persisted_plan_for_apply,
};

use super::apply::write_apply_report_with_command;
use super::persistence::{parse_days, parse_duration, parse_size};
use super::target_report::{is_cleanable_cargo_target, normalize_for_dedupe};
use super::{
    CliError, OutputFormat, inline_config_path, inline_ignore_path, inline_skip_path, next_path,
    next_value, parse_policy, parse_toolchain_name, parse_u64,
};

const CLEANUP_PLAN_EXPIRY: Duration = Duration::from_secs(5 * 60);

mod interaction;
use interaction::resolve_cleanup_assistant;

#[derive(Debug, Clone)]
pub(super) struct CleanupCommand {
    roots: Vec<PathBuf>,
    selected_targets: Vec<PathBuf>,
    all: bool,
    delete_target: bool,
    execute: bool,
    validate_only: bool,
    prompt_selector: bool,
    interactive_selection_modified: bool,
    output_format: OutputFormat,
    policy: PolicyKind,
    scanner_options: ScannerOptions,
    inventory_options: InventoryOptions,
    planner_options: PlannerOptions,
    config_path: Option<PathBuf>,
    config_version: Option<u16>,
}

pub(super) fn parse_cleanup_command(
    args: impl IntoIterator<Item = OsString>,
) -> Result<CleanupCommand, CliError> {
    let mut roots = Vec::new();
    let mut selected_targets = Vec::new();
    let mut all = false;
    let mut delete_target = false;
    let mut execute = false;
    let mut validation_alias = false;
    let mut output_format = OutputFormat::Terminal;
    let mut policy = None;
    let mut config_path = None;
    let mut scanner_options = ScannerOptions::default();
    let mut planner_options = PlannerOptions {
        whole_target_mode: WholeTargetMode::Off,
        ..PlannerOptions::default()
    };
    let mut cli_follow_symlinks = false;
    let mut cli_allow_name_only_targets = false;
    let mut cli_cross_filesystems = false;
    let mut cli_recent_write_keep_window = false;
    let mut cli_keep_size = false;
    let mut cli_keep_rustc_hashes = false;
    let mut cli_keep_installed_toolchains = false;
    let mut cli_keep_toolchains = false;
    let mut args = args.into_iter();

    while let Some(arg) = args.next() {
        if let Some(ignore_path) = inline_ignore_path(&arg)? {
            scanner_options.ignored_paths.push(ignore_path);
            continue;
        }
        if let Some(skip_path) = inline_skip_path(&arg)? {
            scanner_options.skipped_paths.push(skip_path);
            continue;
        }
        if let Some(path) = inline_config_path(&arg)? {
            config_path = Some(path);
            continue;
        }

        let Some(arg_text) = arg.as_os_str().to_str() else {
            roots.push(PathBuf::from(arg));
            continue;
        };

        match arg_text {
            "-h" | "--help" => return Err(CliError::Help(cleanup_usage())),
            "--" => {
                roots.extend(args.map(PathBuf::from));
                break;
            }
            "--all" => all = true,
            "--target" => selected_targets.push(next_path(&mut args, "--target")?),
            value if value.starts_with("--target=") => {
                let target = &value["--target=".len()..];
                if target.is_empty() {
                    return Err(CliError::Usage("--target requires a value".to_string()));
                }
                selected_targets.push(PathBuf::from(target));
            }
            "--delete-target" => delete_target = true,
            "--yes" => execute = true,
            "--dry-run" | "--validate" => validation_alias = true,
            "--json" => output_format = OutputFormat::Json,
            "--policy" => {
                policy = Some(parse_policy(&next_value(&mut args, "--policy")?)?);
            }
            value if value.starts_with("--policy=") => {
                policy = Some(parse_policy(&value["--policy=".len()..])?);
            }
            "--config" => config_path = Some(next_path(&mut args, "--config")?),
            "--ignore" => scanner_options
                .ignored_paths
                .push(next_path(&mut args, "--ignore")?),
            "--skip" => scanner_options
                .skipped_paths
                .push(next_path(&mut args, "--skip")?),
            "--allow-name-only-targets" => {
                scanner_options.allow_name_only_targets = true;
                cli_allow_name_only_targets = true;
            }
            "--follow-symlinks" => {
                scanner_options.follow_symlinks = true;
                cli_follow_symlinks = true;
            }
            "--cross-filesystems" => {
                scanner_options.cross_filesystems = true;
                cli_cross_filesystems = true;
            }
            "--keep-recent-writes" => {
                planner_options.recent_write_keep_window = Some(parse_duration(&next_value(
                    &mut args,
                    "--keep-recent-writes",
                )?)?);
                cli_recent_write_keep_window = true;
            }
            value if value.starts_with("--keep-recent-writes=") => {
                planner_options.recent_write_keep_window =
                    Some(parse_duration(&value["--keep-recent-writes=".len()..])?);
                cli_recent_write_keep_window = true;
            }
            "--keep-days" => {
                planner_options.recent_write_keep_window =
                    Some(parse_days(&next_value(&mut args, "--keep-days")?)?);
                cli_recent_write_keep_window = true;
            }
            value if value.starts_with("--keep-days=") => {
                planner_options.recent_write_keep_window =
                    Some(parse_days(&value["--keep-days=".len()..])?);
                cli_recent_write_keep_window = true;
            }
            "--keep-size" => {
                planner_options.keep_size_bytes =
                    Some(parse_size(&next_value(&mut args, "--keep-size")?)?);
                cli_keep_size = true;
            }
            value if value.starts_with("--keep-size=") => {
                planner_options.keep_size_bytes = Some(parse_size(&value["--keep-size=".len()..])?);
                cli_keep_size = true;
            }
            "--keep-rustc-hash" => {
                planner_options
                    .keep_rustc_hashes
                    .push(parse_u64(&next_value(&mut args, "--keep-rustc-hash")?)?);
                cli_keep_rustc_hashes = true;
            }
            value if value.starts_with("--keep-rustc-hash=") => {
                planner_options
                    .keep_rustc_hashes
                    .push(parse_u64(&value["--keep-rustc-hash=".len()..])?);
                cli_keep_rustc_hashes = true;
            }
            "--keep-installed-toolchains" => {
                planner_options.keep_installed_toolchains = true;
                cli_keep_installed_toolchains = true;
            }
            "--keep-toolchain" => {
                planner_options.keep_toolchains.push(parse_toolchain_name(
                    next_value(&mut args, "--keep-toolchain")?,
                    "--keep-toolchain",
                )?);
                cli_keep_toolchains = true;
            }
            value if value.starts_with("--keep-toolchain=") => {
                planner_options.keep_toolchains.push(parse_toolchain_name(
                    value["--keep-toolchain=".len()..].to_string(),
                    "--keep-toolchain",
                )?);
                cli_keep_toolchains = true;
            }
            value if value.starts_with('-') => {
                return Err(CliError::Usage(format!("unknown cleanup option `{value}`")));
            }
            _ => roots.push(PathBuf::from(arg)),
        }
    }

    if execute && validation_alias {
        return Err(CliError::Usage(
            "--dry-run/--validate conflicts with --yes".to_string(),
        ));
    }
    if all && !selected_targets.is_empty() {
        return Err(CliError::Usage(
            "--all conflicts with --target; choose one cleanup selector".to_string(),
        ));
    }
    let prompt_selector = !all && selected_targets.is_empty();

    let config = config_path
        .as_ref()
        .map(load_config_from_path)
        .transpose()?;
    let config_version = config.as_ref().map(|config| config.version);

    if roots.is_empty() {
        if let Some(config_roots) = config
            .as_ref()
            .filter(|config| !config.roots.is_empty())
            .map(|config| config.roots.clone())
        {
            roots = config_roots;
        } else if all || prompt_selector {
            roots.push(PathBuf::from("."));
        }
    }

    let policy = match policy {
        Some(policy) => policy,
        None => config
            .as_ref()
            .and_then(|config| config.policy.as_deref())
            .map(parse_policy)
            .transpose()?
            .unwrap_or(PolicyKind::Balanced),
    };

    if let Some(config) = config {
        let config_keep_rustc_hashes = config.keep_rustc_hashes;
        let config_keep_installed_toolchains = config.keep_installed_toolchains;
        let config_keep_toolchains = config.keep_toolchains;
        let mut ignored_paths = config.ignored_paths;
        ignored_paths.extend(scanner_options.ignored_paths);
        scanner_options.ignored_paths = ignored_paths;
        let mut skipped_paths = config.skipped_paths;
        skipped_paths.extend(scanner_options.skipped_paths);
        scanner_options.skipped_paths = skipped_paths;

        if !cli_follow_symlinks && let Some(follow_symlinks) = config.scanner.follow_symlinks {
            scanner_options.follow_symlinks = follow_symlinks;
        }
        if !cli_allow_name_only_targets
            && let Some(allow_name_only_targets) = config.scanner.allow_name_only_targets
        {
            scanner_options.allow_name_only_targets = allow_name_only_targets;
        }
        if !cli_cross_filesystems && let Some(cross_filesystems) = config.scanner.cross_filesystems
        {
            scanner_options.cross_filesystems = cross_filesystems;
        }
        if !cli_recent_write_keep_window {
            planner_options.recent_write_keep_window = config.recent_write_keep_window;
        }
        if !cli_keep_size {
            planner_options.keep_size_bytes = config.keep_size_bytes;
        }
        planner_options.target_size_goal_bytes = config.policy_thresholds.target_size_goal_bytes;
        planner_options.target_free_disk_bytes = config.background.target_free_disk_bytes;
        if !cli_keep_rustc_hashes {
            planner_options.keep_rustc_hashes = config_keep_rustc_hashes;
        }
        if !cli_keep_installed_toolchains {
            planner_options.keep_installed_toolchains = config_keep_installed_toolchains;
        }
        if !cli_keep_toolchains {
            planner_options.keep_toolchains = config_keep_toolchains;
        }
    }
    planner_options.whole_target_mode = WholeTargetMode::Off;

    let inventory_options = InventoryOptions {
        follow_symlinks: scanner_options.follow_symlinks,
        skipped_paths: scanner_options.skipped_paths.clone(),
        deep_target_scan: false,
        deep_directory_measurement: true,
    };

    Ok(CleanupCommand {
        roots,
        selected_targets,
        all,
        delete_target,
        execute,
        validate_only: validation_alias,
        prompt_selector,
        interactive_selection_modified: false,
        output_format,
        policy,
        scanner_options,
        inventory_options,
        planner_options,
        config_path,
        config_version,
    })
}

pub(super) fn run_cleanup_command(
    command: &CleanupCommand,
    output: &mut impl Write,
    active_observation_provider: &impl ActiveObservationProvider,
) -> Result<ExitCode, CliError> {
    let command = resolve_cleanup_assistant(command)?;
    if command.cancelled {
        writeln!(output, "cargo-reclaim cleanup cancelled")?;
        return Ok(ExitCode::SUCCESS);
    }

    let report = if command.command.delete_target {
        run_whole_target_cleanup(&command.command)?
    } else {
        run_smart_trim_cleanup(&command.command, active_observation_provider)?
    };
    let exit_code = if report.totals.failed_count == 0 {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    };
    write_apply_report_with_command(output, &report, command.command.output_format, "cleanup")?;
    Ok(exit_code)
}

fn run_smart_trim_cleanup(
    command: &CleanupCommand,
    active_observation_provider: &impl ActiveObservationProvider,
) -> Result<ApplyReport, CliError> {
    let mut planner_options = command.planner_options.clone();
    planner_options.whole_target_mode = WholeTargetMode::Off;
    resolve_command_toolchain_hash_options(&mut planner_options)?;
    let plan_roots = smart_trim_plan_roots(command);
    let scanner_options = if command.selected_targets.is_empty() {
        command.scanner_options.clone()
    } else {
        explicit_target_scanner_options(command)
    };
    let now = SystemTime::now();
    let mut plan = if command.selected_targets.is_empty() {
        build_plan_from_roots_with_active_observation_provider(
            plan_roots.clone(),
            command.policy,
            &scanner_options,
            &command.inventory_options,
            &planner_options,
            active_observation_provider,
            now,
        )?
    } else {
        let items = explicit_target_scan_items(plan_roots.clone(), &scanner_options, command)?;
        build_plan_from_scan_items_with_active_observation_provider(
            BuildPlanFromScanItemsWithProviderRequest {
                input: PlanInput::new(plan_roots)?,
                policy: command.policy,
                items,
                scanner_options: &scanner_options,
                inventory_options: &command.inventory_options,
                planner_options: &planner_options,
                active_observation_provider,
                now,
            },
        )?
    };
    if !command.selected_targets.is_empty() {
        plan = filter_plan_to_selected_targets(plan, &command.selected_targets);
    }
    apply_persisted_plan(
        command,
        &plan,
        command.policy,
        &scanner_options,
        &planner_options,
        now,
    )
}

fn smart_trim_plan_roots(command: &CleanupCommand) -> Vec<PathBuf> {
    if command.selected_targets.is_empty() {
        return command.roots.clone();
    }

    let mut roots = command.roots.clone();
    roots.extend(command.selected_targets.iter().cloned());
    roots
}

fn run_whole_target_cleanup(command: &CleanupCommand) -> Result<ApplyReport, CliError> {
    let now = SystemTime::now();
    let scanner_options = if command.selected_targets.is_empty() {
        command.scanner_options.clone()
    } else {
        explicit_target_scanner_options(command)
    };
    let selected = discover_selected_whole_targets(command, &scanner_options)?;
    let plan = selected_targets_plan(command.roots.clone(), selected, &command.inventory_options)?;
    let planner_options = PlannerOptions {
        whole_target_mode: WholeTargetMode::DeleteConfirmed,
        ..PlannerOptions::default()
    };
    apply_persisted_plan(
        command,
        &plan,
        PolicyKind::Aggressive,
        &scanner_options,
        &planner_options,
        now,
    )
}

fn explicit_target_scanner_options(command: &CleanupCommand) -> ScannerOptions {
    let mut scanner_options = command.scanner_options.clone();
    scanner_options.allow_name_only_targets = true;
    scanner_options
}

fn explicit_target_scan_items(
    roots: Vec<PathBuf>,
    scanner_options: &ScannerOptions,
    command: &CleanupCommand,
) -> Result<Vec<ScanItem>, CliError> {
    let selected = command
        .selected_targets
        .iter()
        .map(|path| normalize_for_dedupe(path))
        .collect::<HashSet<_>>();
    let mut items = scan_roots(roots, scanner_options)?;
    for item in &mut items {
        let ScanItem::TargetCandidate(candidate) = item else {
            continue;
        };
        if candidate.kind == TargetCandidateKind::CargoTargetDir
            && selected.contains(&normalize_for_dedupe(&candidate.path))
            && candidate
                .evidence
                .as_ref()
                .is_some_and(TargetEvidence::is_weak_name_only)
        {
            candidate.evidence = Some(TargetEvidence::configured_path("explicit --target")?);
        }
    }
    Ok(items)
}

fn filter_plan_to_selected_targets(plan: Plan, selected_targets: &[PathBuf]) -> Plan {
    let selected_targets = selected_targets
        .iter()
        .map(|path| normalize_for_dedupe(path))
        .collect::<Vec<_>>();
    let entries = plan
        .entries
        .into_iter()
        .filter(|entry| is_under_selected_target(&entry.snapshot.path, &selected_targets))
        .collect::<Vec<_>>();
    let skipped_paths = plan
        .skipped_paths
        .into_iter()
        .filter(|skip| is_under_selected_target(&skip.path, &selected_targets))
        .collect::<Vec<_>>();

    Plan::with_skipped_paths(plan.input, entries, skipped_paths)
}

fn is_under_selected_target(path: &Path, selected_targets: &[PathBuf]) -> bool {
    let path = normalize_for_dedupe(path);
    selected_targets
        .iter()
        .any(|target| path == *target || path.starts_with(target))
}

fn apply_persisted_plan(
    command: &CleanupCommand,
    plan: &Plan,
    policy: PolicyKind,
    scanner_options: &ScannerOptions,
    planner_options: &PlannerOptions,
    now: SystemTime,
) -> Result<ApplyReport, CliError> {
    let mut invocation = PlanInvocation::new(
        PlanCommandKind::Plan,
        policy,
        scanner_options,
        &command.inventory_options,
        planner_options,
    );
    if let (Some(config_path), Some(config_version)) =
        (&command.config_path, command.config_version)
    {
        invocation = invocation.with_config(config_path, config_version);
    }
    let document = persist_plan(
        plan,
        SavePlanOptions {
            created_at: now,
            expires_at: now
                .checked_add(CLEANUP_PLAN_EXPIRY)
                .ok_or_else(|| CliError::Usage("cleanup plan expiry overflowed".to_string()))?,
            interactive_selection_modified: command.interactive_selection_modified,
            invocation,
        },
    )?;

    if command.execute {
        Ok(execute_persisted_plan_apply(&document, now)?)
    } else {
        Ok(validate_persisted_plan_for_apply(&document, now)?)
    }
}

#[derive(Clone)]
struct WholeTargetSelection {
    path: PathBuf,
    evidence: TargetEvidence,
}

fn discover_selected_whole_targets(
    command: &CleanupCommand,
    scanner_options: &ScannerOptions,
) -> Result<Vec<WholeTargetSelection>, CliError> {
    let discovery_roots = whole_target_discovery_roots(command);
    let items = scan_roots(discovery_roots, scanner_options)?;
    let mut targets = Vec::new();
    let mut seen = HashSet::new();
    for item in items {
        let ScanItem::TargetCandidate(candidate) = item else {
            continue;
        };
        if candidate.kind != TargetCandidateKind::CargoTargetDir
            || !is_cleanable_cargo_target(&candidate)
        {
            continue;
        }
        if seen.insert(normalize_for_dedupe(&candidate.path)) {
            let evidence = candidate.evidence.ok_or_else(|| {
                CliError::Usage(format!(
                    "target `{}` was discovered without target evidence",
                    candidate.path.display()
                ))
            })?;
            targets.push(WholeTargetSelection {
                path: candidate.path,
                evidence,
            });
        }
    }

    if command.all {
        if targets.is_empty() {
            return Err(CliError::Usage(
                "cleanup found no target directories to delete".to_string(),
            ));
        }
        return Ok(targets);
    }

    let mut selected = Vec::new();
    for selected_path in &command.selected_targets {
        let selected_key = normalize_for_dedupe(selected_path);
        let Some(target) = targets
            .iter()
            .find(|target| normalize_for_dedupe(&target.path) == selected_key)
        else {
            return Err(CliError::Usage(format!(
                "selected target `{}` was not discovered; pass a root that contains it or the target path itself",
                selected_path.display()
            )));
        };
        if !selected
            .iter()
            .any(|entry: &WholeTargetSelection| normalize_for_dedupe(&entry.path) == selected_key)
        {
            selected.push(target.clone());
        }
    }
    Ok(selected)
}

fn whole_target_discovery_roots(command: &CleanupCommand) -> Vec<PathBuf> {
    let mut roots = command.roots.clone();
    roots.extend(command.selected_targets.iter().cloned());
    if roots.is_empty() {
        roots.push(PathBuf::from("."));
    }
    roots
}

fn selected_targets_plan(
    roots: Vec<PathBuf>,
    selected: Vec<WholeTargetSelection>,
    inventory_options: &InventoryOptions,
) -> Result<Plan, CliError> {
    let mut entries = Vec::new();
    let mut input_roots = roots;
    for target in selected {
        if input_roots.is_empty() {
            input_roots.push(target.path.clone());
        }
        let entry = PlanEntry::new(
            snapshot_path(&target.path, inventory_options)?,
            ArtifactClass::WholeTarget,
            target.evidence,
            PlanAction::Delete,
            "selected whole-target cleanup",
            false,
        )?;
        entries.push(entry);
    }
    Ok(Plan::new(PlanInput::new(input_roots)?, entries))
}

fn cleanup_usage() -> String {
    "usage: cargo-reclaim cleanup [--all|--target <path>] [--delete-target] [--yes] [OPTIONS] [ROOT ...]".to_string()
}