Skip to main content

dev_prune/commands/
run.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Handler for the `dev-prune run` command.
5//
6// Executes a full prune pass across all registered repositories.
7// Supports pre-deletion analysis, optimized ecosystem binary pre-checks,
8// interactive TUI multi-selection, progressive deletion, shell-specific
9// troubleshooting, and interactive error fallback.
10
11use anyhow::Result;
12use std::io::{self, IsTerminal, Write};
13use std::path::Path;
14
15use crate::adapters;
16use crate::config::Registry;
17use crate::constants;
18use crate::engine::{self, AdapterFilter, PruneOptions, PruneResult, PruneStatus};
19use crate::i18n;
20use crate::json;
21use crate::output;
22use crate::setup;
23use crate::tui;
24
25/// Everything `devp run` was asked to do.
26///
27/// A struct rather than nine positional parameters: the call site in `run_cli` reads as
28/// a list of names, and adding a flag does not silently shift an argument.
29pub struct RunArgs<'a> {
30    /// Optional single workspace to act on instead of the whole registry.
31    pub target_path: Option<&'a str>,
32    /// Report sizes and stop.
33    pub dry_run: bool,
34    /// Bypass the idle threshold. Lockfile verification still applies.
35    pub force: bool,
36    /// Skip the confirmation prompt.
37    pub yes: bool,
38    /// This is the scheduled background pass.
39    pub daemon: bool,
40    /// Comma-separated adapters to act on exclusively.
41    pub only: Option<&'a str>,
42    /// Comma-separated adapters to leave alone.
43    pub skip: Option<&'a str>,
44    /// Size floor in MiB, overriding the configured `min_size_mb`.
45    pub min_size_mb: Option<u64>,
46    /// Comma-separated repositories to leave completely alone this pass.
47    pub except: Option<&'a str>,
48    /// Emit one JSON document instead of the human report.
49    pub json: bool,
50    /// Explain every decision and touch nothing.
51    pub explain: bool,
52}
53
54/// Run the `run` command — prune all registered repos or a specific target directory (`devp run .`).
55///
56/// `daemon` marks the scheduled background pass; repositories that set `disable_daemon`
57/// in `.devprune.json` are excluded from it but remain pruneable by hand.
58pub fn run(args: RunArgs<'_>) -> Result<()> {
59    let filter = AdapterFilter::new(args.only, args.skip)?;
60
61    // In JSON mode there is no one to answer a prompt and no terminal to draw a selector
62    // in, so deletion has to have been authorised on the command line. Failing loudly
63    // beats either silently deleting or silently doing nothing.
64    if args.json && !args.dry_run && !args.yes {
65        return Err(anyhow::Error::new(crate::UsageError(
66            "`--json` cannot ask for confirmation. Pass `--dry-run` to analyse, or `--yes` to delete."
67                .to_string(),
68        )));
69    }
70
71    if !args.json {
72        output::print_banner();
73        if args.force {
74            print_ignore_idle_notice();
75        }
76    }
77
78    if args.explain {
79        return run_explain(&args, &filter);
80    }
81
82    if let Some(target_str) = args.target_path {
83        return run_targeted(&args, &filter, target_str);
84    }
85    run_registry(&args, &filter)
86}
87
88/// What `--ignore-idle` does and, more usefully, what it does not.
89///
90/// Printed whenever the idle check is bypassed, because that is the moment someone is
91/// most likely to be working around a problem rather than solving it — and the problem
92/// they hit is almost always one of the three below. Suppressed in JSON mode, where the
93/// document is the contract and prose on stdout would corrupt it.
94fn print_ignore_idle_notice() {
95    output::print_warning(
96        "Idle check bypassed — repositories you are working in right now are fair game.",
97    );
98    println!(
99        "  Still enforced: lockfile verification, `ignore.devprune.json`, `\"ignore\": true`,"
100    );
101    println!(
102        "  symlinked directories, and nested repositories. This flag does not turn those off."
103    );
104    println!();
105    println!("  If you reached for this because something would not prune, it is usually:");
106    println!("    • \"lockfile verification failed\"  → run the fix command printed next to it;");
107    println!("      it regenerates the lockfile so the reinstall is guaranteed to work.");
108    println!("    • nothing listed at all            → the project is deeper than `scan_depth`,");
109    println!("      or under `min_size_mb`. Try `devp status` to see what dev-prune can see.");
110    println!("    • \"could not be examined\"          → `.devprune.json` has a syntax error.");
111    println!();
112    println!("  Still stuck? Point your AI assistant at the bundled skill — `devp skill`");
113    println!("  exports a SKILL.md that teaches it this tool, exit codes and all. It has");
114    println!("  read the manual more recently than either of us.");
115    println!();
116    // The same list the skill would work from, spelled out for someone who would rather
117    // not hand their shell to a language model. Both audiences want the identical five
118    // commands, so they are printed once, here, rather than kept only in SKILL.md.
119    println!("  Or do it the old-school way — every step that skill would take, by hand:");
120    println!("    • `devp run --explain`   the verdict for every repository and directory,");
121    println!("                             and the one reason behind each of them.");
122    println!("    • `devp status`          what is registered, how idle it is, what it holds.");
123    println!("    • `devp doctor`          the install itself: hooks, scheduler, config, PATH.");
124    println!("    • `devp config show`     every setting and the value it currently has.");
125    println!("    • `devp man`             the full reference, offline.");
126    println!();
127}
128
129/// `devp run <PATH>` — one workspace, no registry, no selector.
130fn run_targeted(args: &RunArgs<'_>, filter: &AdapterFilter, target_str: &str) -> Result<()> {
131    let raw = std::path::Path::new(target_str);
132    let path = if raw.exists() {
133        raw.canonicalize().unwrap_or_else(|_| raw.to_path_buf())
134    } else {
135        raw.to_path_buf()
136    };
137
138    let clean = output::clean_path(&path);
139    if !crate::scanner::is_git_repo(&path) {
140        // Returning Ok here made `devp run <path>` exit 0 on a path it refused to
141        // touch, which is invisible to any script or CI step checking the status.
142        anyhow::bail!("{clean} is not a Git repository — dev-prune only prunes Git repos.");
143    }
144
145    // A targeted run still respects the configured idle threshold. Passing 0 here
146    // would make every repo look idle and silently defeat the guard — `--ignore-idle` is
147    // the documented way to prune a repo you are actively working in.
148    let registry = Registry::load().ok();
149    let idle_days = registry
150        .as_ref()
151        .map(|r| {
152            r.repositories
153                .get(&path)
154                .and_then(|e| e.override_idle_days)
155                .unwrap_or(r.settings.idle_days)
156        })
157        .unwrap_or(constants::DEFAULT_IDLE_DAYS);
158
159    let mut opts = PruneOptions {
160        idle_days,
161        dry_run: args.dry_run,
162        force: args.force,
163        only_dirs: None,
164        adapters: filter.clone(),
165        min_size_bytes: resolve_min_size(args, registry.as_ref()),
166        scan_depth: resolve_scan_depth(registry.as_ref()),
167        allow_manifest_rewrite: resolve_manifest_rewrite(registry.as_ref()),
168        command_timeout_secs: resolve_command_timeout(registry.as_ref()),
169        build_idle_days: resolve_build_idle_days(registry.as_ref()),
170        adapter_idle_days: resolve_adapter_idle_days(registry.as_ref()),
171    };
172
173    if !args.json {
174        output::print_header(&i18n::tf(
175            "run.header.targeted",
176            &[("path", clean.as_str())],
177        ));
178        if let Some(desc) = filter.describe() {
179            output::print_info(&format!("Adapter filter: {desc}"));
180        }
181    }
182
183    // `devp run <path>` shows what it found and asks before touching any of it — the
184    // same contract the registry pass has always had. `--yes` answers in advance,
185    // `--dry-run` never deletes, `--json` was already required at the top of `run()` to
186    // carry one of those two, and `require_confirmation false` is the standing form of
187    // the answer.
188    if !args.dry_run
189        && !args.json
190        && !args.yes
191        && registry
192            .as_ref()
193            .is_none_or(|r| r.settings.require_confirmation)
194    {
195        let preview = engine::prune_repo_with(
196            &path,
197            &PruneOptions {
198                dry_run: true,
199                ..opts.clone()
200            },
201        );
202        let candidates: Vec<PruneResult> = preview
203            .into_iter()
204            .filter(|r| matches!(r.status, PruneStatus::SkippedDryRun))
205            .collect();
206        // Nothing deletable means nothing to confirm: fall through and let the real
207        // pass report the skips and errors exactly as it always has.
208        if !candidates.is_empty() {
209            let total: u64 = candidates.iter().map(|c| c.size_freed).sum();
210            report_candidates(&candidates);
211            output::print_info(&i18n::tf(
212                "run.reclaimable",
213                &[("size", &output::format_bytes_styled(total))],
214            ));
215            output::print_info(
216                "Everything above is rebuilt from a lockfile — `devp restore` brings it back.",
217            );
218            if !io::stdin().is_terminal() {
219                anyhow::bail!(
220                    "Deleting {} directories ({}) needs confirmation, and there is no \
221                     terminal to ask on. Re-run with `--yes` to confirm, or `--dry-run` \
222                     to only analyse.",
223                    candidates.len(),
224                    output::format_bytes(total)
225                );
226            }
227            // The question goes to stderr: stdout may be a pipe, and a prompt written
228            // into one is invisible on the terminal — the command just appears to hang.
229            eprint!(
230                "Proceed with deletion of {} directories ({})? [y/N]: ",
231                candidates.len(),
232                output::format_bytes(total)
233            );
234            io::stderr().flush()?;
235            let mut input = String::new();
236            io::stdin().read_line(&mut input)?;
237            let trimmed = input.trim().to_lowercase();
238            if trimmed != "y" && trimmed != "yes" {
239                output::print_info("Prune pass aborted by user.");
240                return Ok(());
241            }
242            // The real pass deletes exactly the list the user said yes to. Without
243            // this, it re-derived candidates from scratch — and a directory that
244            // became eligible while the prompt sat open was deleted unconfirmed.
245            opts.only_dirs = Some(candidates.iter().map(|c| c.bloat_dir.clone()).collect());
246        }
247    }
248
249    let results = engine::prune_repo_with(&path, &opts);
250
251    // A directory that could not be verified or deleted is a failure of the command,
252    // whichever output mode asked for it. `devp run <path>` used to exit 0 after a
253    // lockfile or delete error, which a script or CI step has no way to notice.
254    let error_count = results
255        .iter()
256        .filter(|r| {
257            matches!(
258                r.status,
259                PruneStatus::LockfileError(_)
260                    | PruneStatus::ActivityCheckError(_)
261                    | PruneStatus::DeleteError(_)
262                    | PruneStatus::ConfigError(_)
263            )
264        })
265        .count();
266
267    // Recorded before the output branches, so `--json` and the human report leave the
268    // same registry behind. A targeted run used to update neither the lifetime totals nor
269    // anything `restore` could read: `devp run .` freed two gigabytes and `devp status`
270    // still said nothing had ever been pruned.
271    record_targeted_prune(&path, &results, args.dry_run, args.daemon);
272
273    if args.json {
274        json::emit(&json::run_document(&results, args.dry_run))?;
275        if error_count > 0 {
276            anyhow::bail!("{error_count} directories in {clean} could not be pruned.");
277        }
278        return Ok(());
279    }
280
281    if results.is_empty() {
282        output::print_info(&i18n::tf(
283            "run.nothing.bloat.targeted",
284            &[("path", clean.as_str())],
285        ));
286        return Ok(());
287    }
288
289    let mut total_freed = 0;
290    for result in results {
291        match &result.status {
292            PruneStatus::Pruned => {
293                total_freed += result.size_freed;
294                output::print_success(&format!(
295                    "{} → {} ({}) — {}{}",
296                    output::clean_path(&result.repo_path),
297                    result.bloat_dir,
298                    output::format_bytes(result.size_freed),
299                    result.adapter_name,
300                    output::shared_note(result.shared_bytes, &result.adapter_name)
301                ));
302            }
303            PruneStatus::SkippedDryRun => {
304                output::print_info(&format!(
305                    "  • {} → {} ({}) [{}] (Dry Run){}",
306                    output::clean_path(&result.repo_path),
307                    result.bloat_dir,
308                    output::format_bytes(result.size_freed),
309                    result.adapter_name,
310                    output::shared_note(result.shared_bytes, &result.adapter_name)
311                ));
312            }
313            PruneStatus::SkippedActive => {
314                output::print_info(&format!(
315                    "{clean} is currently active (not idle). Use `devp --ignore-idle run` to override."
316                ));
317            }
318            PruneStatus::SkippedAdapterWindow(days) => {
319                output::print_info(&format!(
320                    "  • {} was not examined — it waits for {days} idle days \
321                     (`build_idle_days` / `adapter_idle_days`), longer than this \
322                     repository has been idle. `--ignore-idle` overrides.",
323                    result.adapter_name
324                ));
325            }
326            PruneStatus::LockfileError(e) => report_lockfile_failure(&result, e),
327            PruneStatus::ActivityCheckError(e) => {
328                output::print_error(&format!(
329                    "{clean} skipped — its activity could not be determined:\n    {}",
330                    e.trim()
331                ));
332            }
333            PruneStatus::DeleteError(e) => {
334                output::print_error(&format!("{clean} delete error: {e}"));
335            }
336            PruneStatus::ConfigError(e) => {
337                output::print_error(&format!(
338                    "{clean} skipped — its .devprune.json could not be read:\n    {}\n    \
339                     Fix it, or run `devp config {clean} --update` to reset it.",
340                    e.trim()
341                ));
342            }
343            PruneStatus::SkippedSymlink(e) => {
344                output::print_warning(&format!("{clean} → {}", e.trim()));
345            }
346            PruneStatus::SkippedDeclaration(e) => {
347                output::print_warning(&format!("{clean} → {}", e.trim()));
348            }
349            PruneStatus::SkippedNestedRepo(e) => {
350                output::print_warning(&format!("{clean} → {}", e.trim()));
351            }
352            _ => {}
353        }
354    }
355
356    if !args.dry_run && total_freed > 0 {
357        output::print_success(&i18n::tf(
358            "run.freed.targeted",
359            &[
360                ("size", &output::format_bytes(total_freed)),
361                ("path", clean.as_str()),
362            ],
363        ));
364    }
365
366    if error_count > 0 {
367        anyhow::bail!("{error_count} directories in {clean} could not be pruned.");
368    }
369
370    Ok(())
371}
372
373/// Persist what a targeted run deleted: the lifetime totals and the `--last-run` record.
374///
375/// Silent on every failure. The directories are already gone by the time this is called,
376/// and a registry that could not be written is not a reason to report the prune itself as
377/// failed — it only costs the user `devp restore --last-run` for this one pass.
378fn record_targeted_prune(
379    path: &std::path::Path,
380    results: &[PruneResult],
381    dry_run: bool,
382    daemon: bool,
383) {
384    if dry_run {
385        return;
386    }
387
388    // A DeleteError with a non-zero size_freed is a delete that got half-way: the
389    // directory is corrupt, not intact, so `restore --last-run` must know to rebuild it.
390    let pruned: Vec<crate::config::PrunedDir> = results
391        .iter()
392        .filter(|r| {
393            matches!(r.status, PruneStatus::Pruned)
394                || (matches!(r.status, PruneStatus::DeleteError(_)) && r.size_freed > 0)
395        })
396        .map(|r| crate::config::PrunedDir {
397            repo_path: r.repo_path.clone(),
398            bloat_dir: r.bloat_dir.clone(),
399            adapter: r.adapter_name.clone(),
400            size_freed: r.size_freed,
401            runtime: r.runtime.clone(),
402        })
403        .collect();
404
405    if pruned.is_empty() {
406        return;
407    }
408
409    let freed: u64 = pruned.iter().map(|d| d.size_freed).sum();
410    // One timestamp for both records, so `devp history` and the registry agree on which
411    // pass this was rather than describing it twice a millisecond apart.
412    let pass_at = chrono::Utc::now();
413    crate::history::record(pass_at, crate::history::Trigger::for_run(daemon), &pruned);
414    if let Ok(mut registry) = Registry::load() {
415        registry.mark_pruned(path, freed);
416        registry.record_prune_progress(pass_at, pruned);
417        let _ = registry.save();
418    }
419}
420
421/// The size floor for this pass: `--min-size` if given, otherwise the global setting.
422///
423/// A per-repository `min_size_mb` still wins over both — that decision belongs to the
424/// repository and is applied inside the engine.
425fn resolve_min_size(args: &RunArgs<'_>, registry: Option<&Registry>) -> u64 {
426    let mb = args
427        .min_size_mb
428        .or_else(|| registry.map(|r| r.settings.min_size_mb))
429        .unwrap_or(constants::DEFAULT_MIN_SIZE_MB);
430    mb.saturating_mul(engine::BYTES_PER_MIB)
431}
432
433/// Repositories named by `--except`, as a set of lowercased names and path fragments.
434///
435/// Empty when the flag was not passed.
436///
437/// Each entry is tilde-expanded first, because a comma-separated list arrives as one
438/// argument and no shell expands a `~` sitting in the middle of it — not even bash.
439fn parse_except(spec: Option<&str>) -> Vec<String> {
440    spec.map(|s| {
441        s.split(',')
442            .map(|part| {
443                crate::config::expand_tilde(part.trim())
444                    .trim_end_matches(['/', '\\'])
445                    .to_lowercase()
446            })
447            .filter(|part| !part.is_empty())
448            .collect()
449    })
450    .unwrap_or_default()
451}
452
453/// Whether `--except` names this repository.
454///
455/// Matched three ways because there are three things a user reasonably types: the folder
456/// name (`api`), a path fragment (`work/api`), or the full path they see in `devp status`.
457/// Case-insensitive, and `/` and `\` are treated as the same separator, so the flag
458/// behaves the same in PowerShell and in bash.
459fn is_excepted(repo_path: &Path, except: &[String]) -> bool {
460    if except.is_empty() {
461        return false;
462    }
463    let full = output::clean_path(repo_path)
464        .to_lowercase()
465        .replace('\\', "/");
466    let name = repo_path
467        .file_name()
468        .map(|n| n.to_string_lossy().to_lowercase())
469        .unwrap_or_default();
470
471    except.iter().any(|want| {
472        let want = want.replace('\\', "/");
473        name == want || full == want || full.ends_with(&format!("/{want}"))
474    })
475}
476
477/// The global scan depth, falling back to the default when there is no registry yet.
478fn resolve_scan_depth(registry: Option<&Registry>) -> usize {
479    registry
480        .map(|r| r.settings.scan_depth)
481        .unwrap_or(constants::DEFAULT_SCAN_DEPTH)
482}
483
484/// The idle window for adapters holding compiler output, in days.
485fn resolve_build_idle_days(registry: Option<&Registry>) -> u64 {
486    registry
487        .map(|r| r.settings.build_idle_days)
488        .unwrap_or(constants::DEFAULT_BUILD_IDLE_DAYS)
489}
490
491/// The user's per-adapter idle windows, empty when there is no registry yet.
492fn resolve_adapter_idle_days(
493    registry: Option<&Registry>,
494) -> std::collections::BTreeMap<String, u64> {
495    registry
496        .map(|r| r.settings.adapter_idle_days.clone())
497        .unwrap_or_default()
498}
499
500fn resolve_command_timeout(registry: Option<&Registry>) -> u64 {
501    registry
502        .map(|r| r.settings.command_timeout_secs)
503        .unwrap_or(constants::DEFAULT_COMMAND_TIMEOUT_SECS)
504}
505
506/// Whether an adapter may run its lockfile-rewriting sync command.
507fn resolve_manifest_rewrite(registry: Option<&Registry>) -> bool {
508    registry
509        .map(|r| r.settings.allow_manifest_rewrite)
510        .unwrap_or(constants::DEFAULT_ALLOW_MANIFEST_REWRITE)
511}
512
513/// `devp run` — the full pass over every registered repository.
514fn run_registry(args: &RunArgs<'_>, filter: &AdapterFilter) -> Result<()> {
515    if !args.json {
516        if args.dry_run {
517            output::print_header(i18n::t("run.header.dry"));
518        } else {
519            output::print_header(i18n::t("run.header"));
520        }
521    }
522
523    let mut registry = Registry::load()?;
524
525    // A repository `git init` created fires no Git hook and so never registered itself.
526    // Picking it up here is what keeps `devp run` from reporting "No repositories
527    // registered" while standing inside one. See `link::adopt_enclosing_repo`.
528    let adopted = crate::commands::link::adopt_enclosing_repo(&mut registry);
529    if adopted.is_some() {
530        registry.save()?;
531    }
532    if let Some(path) = &adopted
533        && !args.json
534    {
535        crate::commands::link::report_cwd_adoption(path);
536        println!();
537    }
538
539    // Suppressed in JSON mode: the document is a contract, and a version notice printed
540    // into it would corrupt the output.
541    if !args.json && crate::commands::update::notify_if_outdated(&mut registry) {
542        let _ = registry.save();
543    }
544
545    // Only the scheduled pass, and only when asked for. A manual `devp run` walking the
546    // user's disk looking for repositories would be a surprise; the unattended pass is
547    // the one place where "you never registered it" is otherwise indistinguishable from
548    // "there is nothing to clean up", and the Git hook cannot close that gap — it fires
549    // on commit, so a repository you cloned and never committed to stays invisible
550    // forever, which is precisely the idle repository worth pruning.
551    //
552    // `DEV_PRUNE_NO_AUTO_SETUP` switches it off along with everything else unattended.
553    // The variable means "dev-prune manages nothing on this machine by itself", and a
554    // pass that walks the disk and writes rows into the registry is exactly that; it is
555    // also what keeps a test suite from ever scanning the machine running it.
556    if args.daemon && registry.settings.auto_discover && !setup::no_auto_setup_requested() {
557        let found = crate::discovery::discover(&registry)?;
558        let added = found
559            .found
560            .into_iter()
561            .filter(|repo| registry.add_repo(repo.clone()))
562            .count();
563        if added > 0 {
564            registry.save()?;
565            if !args.json {
566                output::print_info(&format!(
567                    "Discovered and registered {added} new {}.",
568                    output::plural(added, "repository", "repositories")
569                ));
570            }
571        }
572    }
573
574    if registry.repo_count() == 0 {
575        if args.json {
576            return json::emit(&json::run_document(&[], args.dry_run));
577        }
578        output::print_warning(
579            "No repositories registered. Run `devp init` here, or `devp init --auto` to find them.",
580        );
581        return Ok(());
582    }
583
584    // Validated against the registry *before* anything is analysed. A name that matches
585    // nothing is a typo, and the cost of a silent typo here is the one repository the
586    // user was trying to protect getting pruned — so it is an error, not a no-op.
587    let except = parse_except(args.except);
588    if !except.is_empty() {
589        let unmatched: Vec<&String> = except
590            .iter()
591            .filter(|want| {
592                !registry
593                    .repositories
594                    .keys()
595                    .any(|p| is_excepted(p, std::slice::from_ref(*want)))
596            })
597            .collect();
598        if !unmatched.is_empty() {
599            anyhow::bail!(
600                "`--except` names no registered repository: {}\n  \
601                 Run `devp status` to see the registered names.",
602                unmatched
603                    .iter()
604                    .map(|s| s.as_str())
605                    .collect::<Vec<_>>()
606                    .join(", ")
607            );
608        }
609    }
610
611    let min_size_bytes = resolve_min_size(args, Some(&registry));
612    let analysis = PruneOptions {
613        idle_days: 0, // replaced per repository from the registry
614        dry_run: true,
615        force: args.force,
616        only_dirs: None,
617        adapters: filter.clone(),
618        min_size_bytes,
619        scan_depth: resolve_scan_depth(Some(&registry)),
620        allow_manifest_rewrite: resolve_manifest_rewrite(Some(&registry)),
621        command_timeout_secs: resolve_command_timeout(Some(&registry)),
622        build_idle_days: resolve_build_idle_days(Some(&registry)),
623        adapter_idle_days: resolve_adapter_idle_days(Some(&registry)),
624    };
625
626    if !args.json {
627        output::print_info(&format!(
628            "Scanning {} registered repositories for prune candidates...",
629            registry.repo_count()
630        ));
631        if let Some(desc) = filter.describe() {
632            output::print_info(&format!("Adapter filter: {desc}"));
633        }
634        if min_size_bytes > 0 {
635            output::print_info(&format!(
636                "Size floor: ignoring directories under {}",
637                output::format_bytes(min_size_bytes)
638            ));
639        }
640    }
641
642    // Pre-run analysis (dry-run mode first to compute exact savings)
643    //
644    // Two lists come out of it, and both are reported. A repository the analysis refused
645    // to examine — an unreadable `.devprune.json`, most often — used to be dropped here
646    // along with every other non-candidate state, so a pass that had quietly skipped it
647    // still ended on "No idle repositories or pruneable bloat directories found." and
648    // exit 0. The execution loop further down knows how to report these states, but it
649    // only ever sees selected candidates, so it never got the chance.
650    let mut candidates: Vec<PruneResult> = Vec::new();
651    let mut blocked: Vec<PruneResult> = Vec::new();
652    let mut left_alone: Vec<PruneResult> = Vec::new();
653    let mut missing: Vec<PruneResult> = Vec::new();
654    let mut orphaned: Vec<PruneResult> = Vec::new();
655    for result in engine::prune_all_with(&mut registry, &analysis) {
656        // An excepted repository leaves the pass entirely — including its failures. The
657        // user said not to touch it, so a broken config in there is not this run's
658        // problem and must not fail an otherwise clean exit code.
659        if is_excepted(&result.repo_path, &except) {
660            continue;
661        }
662        match result.status {
663            PruneStatus::SkippedDryRun => candidates.push(result),
664            PruneStatus::ConfigError(_)
665            | PruneStatus::LockfileError(_)
666            | PruneStatus::ActivityCheckError(_)
667            | PruneStatus::DeleteError(_) => blocked.push(result),
668            // Reported, never failed on: the link is permanent and deliberate, and a
669            // "failure" here made every scheduled pass over the repo exit 1 forever.
670            // A refused declaration joins it for the same reason — it is a standing
671            // state of the repository's own config, not something this pass did wrong.
672            // So does a vendored checkout inside a bloat directory: the nested repo
673            // stays until somebody moves it, and it used to be a `DeleteError` that
674            // kept every scheduled pass red.
675            PruneStatus::SkippedSymlink(_)
676            | PruneStatus::SkippedDeclaration(_)
677            | PruneStatus::SkippedNestedRepo(_) => left_alone.push(result),
678            // Same reasoning: a deleted clone stays deleted, and failing on it would
679            // keep every scheduled pass red until the entry is unlinked.
680            PruneStatus::PathMissing => missing.push(result),
681            // The directory is still there but its `.git` is not — a standing state of
682            // the registry, exactly as permanent as a missing path, and it kept every
683            // scheduled pass red the same way back when it counted as blocked.
684            PruneStatus::NotARepo => orphaned.push(result),
685            _ => {}
686        }
687    }
688
689    if !args.json && !except.is_empty() {
690        output::print_info(&format!("Leaving alone: {}", except.join(", ")));
691    }
692
693    if args.daemon {
694        let before = candidates.len();
695        candidates.retain(|c| {
696            // An unreadable config drops the candidate. The engine already refuses such a
697            // repository outright, so this cannot fire today; if that ever changes, the
698            // unattended pass must not be the code path that guesses.
699            match crate::config::PerRepoConfig::load_with_diagnostics(&c.repo_path) {
700                Ok(Some(cfg)) => !cfg.disable_daemon,
701                Ok(None) => true,
702                Err(_) => false,
703            }
704        });
705        let skipped = before - candidates.len();
706        if skipped > 0 && !args.json {
707            output::print_info(&format!(
708                "Skipped {skipped} bloat directories in repositories that set `disable_daemon`."
709            ));
710        }
711    }
712
713    // A dry run stops here in both output modes: sizes are known, nothing was verified.
714    if args.dry_run {
715        // An empty list renders as nothing in both output modes, so switching the
716        // setting off is one branch here rather than a guard at every report site.
717        let recommendations = if registry.settings.recommendations {
718            opt_in_recommendations(&registry, &except)
719        } else {
720            Vec::new()
721        };
722        if args.json {
723            let mut doc = json::run_document(
724                &[candidates, blocked, left_alone, missing, orphaned].concat(),
725                true,
726            );
727            json::attach_recommendations(&mut doc, &recommendations);
728            json::emit(&doc)?;
729            return Ok(());
730        }
731        if candidates.is_empty()
732            && blocked.is_empty()
733            && left_alone.is_empty()
734            && missing.is_empty()
735            && orphaned.is_empty()
736        {
737            output::print_info(i18n::t("run.nothing"));
738            // The one moment this hint matters most: a machine full of Rust or Unity
739            // reads "nothing found" precisely because the adapter that would find it
740            // is off.
741            report_recommendations(&recommendations);
742            return Ok(());
743        }
744        if !candidates.is_empty() {
745            report_candidates(&candidates);
746        }
747        let total: u64 = candidates.iter().map(|c| c.size_freed).sum();
748        output::print_header(i18n::t("run.summary.dry"));
749        output::print_info(&i18n::tf(
750            "run.would_free",
751            &[
752                ("size", &output::format_bytes(total)),
753                ("count", &candidates.len().to_string()),
754            ],
755        ));
756        // Reported, but not an error: a dry run's job is to say what it found, and it
757        // found this too.
758        report_blocked(&blocked);
759        report_left_alone(&left_alone);
760        report_missing(&missing);
761        report_orphaned(&orphaned);
762        report_recommendations(&recommendations);
763        return Ok(());
764    }
765
766    if candidates.is_empty() {
767        if args.json {
768            json::emit(&json::run_document(
769                &[blocked.clone(), left_alone, missing, orphaned].concat(),
770                false,
771            ))?;
772            return fail_if_blocked(&blocked);
773        }
774        if blocked.is_empty() && left_alone.is_empty() && missing.is_empty() && orphaned.is_empty()
775        {
776            output::print_info(i18n::t("run.nothing"));
777            return Ok(());
778        }
779        output::print_info(i18n::t("run.nothing.bloat"));
780        report_blocked(&blocked);
781        report_left_alone(&left_alone);
782        report_missing(&missing);
783        report_orphaned(&orphaned);
784        return fail_if_blocked(&blocked);
785    }
786
787    let total_reclaimable: u64 = candidates.iter().map(|c| c.size_freed).sum();
788
789    if !args.json {
790        report_binaries(&candidates);
791        report_candidates(&candidates);
792        output::print_info(&i18n::tf(
793            "run.reclaimable",
794            &[("size", &output::format_bytes_styled(total_reclaimable))],
795        ));
796        report_blocked(&blocked);
797        report_left_alone(&left_alone);
798        report_missing(&missing);
799        report_orphaned(&orphaned);
800    }
801
802    // Determine target candidates to prune (either interactive TUI selection or all).
803    // `--json` short-circuits both: it was already required to carry `--yes`.
804    let target_candidates: Vec<PruneResult> = if args.json
805        || args.yes
806        || !registry.settings.require_confirmation
807    {
808        candidates
809    } else if tui::full_screen_is_usable() {
810        eprintln!();
811        eprintln!(
812            "  Loading interactive selector... (↑↓ navigate, Space toggle, Enter confirm, q cancel)"
813        );
814        eprintln!();
815        let selected = tui::selection_view::select_candidates_tui(&candidates)?;
816        if selected.is_empty() {
817            output::print_info("Prune pass cancelled by user (0 candidates selected).");
818            return Ok(());
819        }
820        selected
821    } else {
822        // Reaching here means stdout is piped or `DEV_PRUNE_NO_TUI` is set. If stdin
823        // is gone too, there is nobody to answer: the read hits EOF at once, and the
824        // old code then reported "aborted by user" about a user who was never asked.
825        // Failing with the fix beats that.
826        if !io::stdin().is_terminal() {
827            anyhow::bail!(
828                "Deleting {} directories ({}) needs confirmation, and there is no \
829                 terminal to ask on. Re-run with `--yes` to confirm, or `--dry-run` \
830                 to only analyse.",
831                candidates.len(),
832                output::format_bytes(total_reclaimable)
833            );
834        }
835        println!();
836        output::print_warning("CAUTION: Deleting bloat directories cannot be undone directly.");
837        output::print_info(
838            "Note: You can re-install missing dependencies anytime using `dev-prune restore`.",
839        );
840        // The question goes to stderr: stdout can be a pipe here, and a prompt written
841        // into a pipe is invisible on the terminal, so the command just appears to hang.
842        eprint!(
843            "Proceed with deletion of {} directories ({})? [y/N]: ",
844            candidates.len(),
845            output::format_bytes(total_reclaimable)
846        );
847        io::stderr().flush()?;
848
849        let mut input = String::new();
850        io::stdin().read_line(&mut input)?;
851        let trimmed = input.trim().to_lowercase();
852        if trimmed != "y" && trimmed != "yes" {
853            output::print_info("Prune pass aborted by user.");
854            return Ok(());
855        }
856        candidates
857    };
858
859    if !args.json {
860        let selected_total_bytes: u64 = target_candidates.iter().map(|c| c.size_freed).sum();
861        output::print_header(&i18n::tf(
862            "run.header.deleting",
863            &[
864                ("repos", &target_candidates.len().to_string()),
865                ("size", &output::format_bytes(selected_total_bytes)),
866            ],
867        ));
868    }
869
870    // Execute deletion ONLY on the selected bloat directories.
871    //
872    // The selector works per bloat directory, so group the selection by repo and pass
873    // the chosen directory names down — pruning the whole repo would delete dirs the
874    // user explicitly unticked.
875    let mut selection: Vec<(std::path::PathBuf, Vec<String>)> = Vec::new();
876    for candidate in &target_candidates {
877        match selection
878            .iter_mut()
879            .find(|(p, _)| *p == candidate.repo_path)
880        {
881            Some((_, dirs)) => dirs.push(candidate.bloat_dir.clone()),
882            None => selection.push((
883                candidate.repo_path.clone(),
884                vec![candidate.bloat_dir.clone()],
885            )),
886        }
887    }
888
889    // Seeded with what the analysis pass could not get past. Those repositories belong in
890    // the document and in the exit code exactly as much as a failure from the loop below.
891    // Left-alone directories ride along for the document only — they are not errors.
892    let mut error_count = blocked.len();
893    let mut all_results: Vec<PruneResult> = blocked;
894    all_results.extend(left_alone);
895    all_results.extend(missing);
896    all_results.extend(orphaned);
897    let mut total_freed: u64 = 0;
898    let mut pruned_count = 0;
899    let mut pruned_dirs: Vec<crate::config::PrunedDir> = Vec::new();
900    // One timestamp identifies the whole pass, so every incremental save below
901    // supersedes the previous one instead of counting as its own pass.
902    let pass_at = chrono::Utc::now();
903    let trigger = crate::history::Trigger::for_run(args.daemon);
904
905    for (repo_path, dirs) in &selection {
906        let recorded_before = pruned_dirs.len();
907        // The idle check runs again here, not just at analysis: the selector can sit
908        // open for hours, and a repository someone started working in between analysis
909        // and Enter must not be pruned on the strength of a stale answer. Only
910        // `--ignore-idle` skips it, exactly as it skipped the first check.
911        let idle_days = registry
912            .repositories
913            .get(repo_path)
914            .and_then(|e| e.override_idle_days)
915            .unwrap_or(registry.settings.idle_days);
916        let single_results = engine::prune_repo_with(
917            repo_path,
918            &PruneOptions {
919                idle_days,
920                dry_run: false,
921                force: args.force,
922                only_dirs: Some(dirs.clone()),
923                adapters: filter.clone(),
924                min_size_bytes: 0,
925                scan_depth: analysis.scan_depth,
926                allow_manifest_rewrite: analysis.allow_manifest_rewrite,
927                command_timeout_secs: analysis.command_timeout_secs,
928                build_idle_days: analysis.build_idle_days,
929                adapter_idle_days: analysis.adapter_idle_days.clone(),
930            },
931        );
932        for result in single_results {
933            match &result.status {
934                PruneStatus::Pruned => {
935                    total_freed += result.size_freed;
936                    pruned_count += 1;
937                    registry.mark_pruned(&result.repo_path, result.size_freed);
938                    pruned_dirs.push(crate::config::PrunedDir {
939                        repo_path: result.repo_path.clone(),
940                        bloat_dir: result.bloat_dir.clone(),
941                        adapter: result.adapter_name.clone(),
942                        size_freed: result.size_freed,
943                        runtime: result.runtime.clone(),
944                    });
945                    if !args.json {
946                        output::print_success(&format!(
947                            "{} → {} ({}) — {}{}",
948                            output::clean_path(&result.repo_path),
949                            result.bloat_dir,
950                            output::format_bytes(result.size_freed),
951                            result.adapter_name,
952                            output::shared_note(result.shared_bytes, &result.adapter_name)
953                        ));
954                    }
955                }
956                PruneStatus::LockfileError(e) => {
957                    error_count += 1;
958                    if !args.json {
959                        report_lockfile_failure(&result, e);
960                    }
961                }
962                PruneStatus::ActivityCheckError(e) => {
963                    error_count += 1;
964                    if !args.json {
965                        output::print_error(&format!(
966                            "{} skipped — its activity could not be determined:\n    {}",
967                            output::clean_path(&result.repo_path),
968                            e.trim()
969                        ));
970                    }
971                }
972                PruneStatus::DeleteError(e) => {
973                    error_count += 1;
974                    // A non-zero size_freed on a delete error means the delete got
975                    // half-way: the directory is corrupt, not intact. Record it so
976                    // `devp restore --last-run` knows to rebuild it — while the error
977                    // above still fails the pass.
978                    if result.size_freed > 0 {
979                        pruned_dirs.push(crate::config::PrunedDir {
980                            repo_path: result.repo_path.clone(),
981                            bloat_dir: result.bloat_dir.clone(),
982                            adapter: result.adapter_name.clone(),
983                            size_freed: result.size_freed,
984                            runtime: result.runtime.clone(),
985                        });
986                    }
987                    if !args.json {
988                        output::print_error(&format!(
989                            "{} → delete failed: {}",
990                            output::clean_path(&result.repo_path),
991                            e,
992                        ));
993                    }
994                }
995                PruneStatus::ConfigError(e) => {
996                    error_count += 1;
997                    if !args.json {
998                        let clean_p = output::clean_path(&result.repo_path);
999                        output::print_error(&format!(
1000                            "{clean_p} skipped — its .devprune.json could not be read:\n    {}",
1001                            e.trim()
1002                        ));
1003                        output::print_info(&format!(
1004                            "  Fix command:       devp config {clean_p} --update"
1005                        ));
1006                    }
1007                }
1008                // The repo saw activity between analysis and execution — the re-check
1009                // above caught it. A protective skip, not a failure.
1010                PruneStatus::SkippedActive if !args.json => {
1011                    output::print_info(&format!(
1012                        "{} became active since the analysis — left alone. \
1013                         Use `--ignore-idle` to prune it anyway.",
1014                        output::clean_path(&result.repo_path)
1015                    ));
1016                }
1017                // Already in `all_results`: the analysis pass reports every refused
1018                // declaration, and the execution pass re-emits them even under its
1019                // `only` selection (deliberately, so a refusal is never silent).
1020                // Keeping this copy too listed the same refusal twice in `--json`.
1021                PruneStatus::SkippedDeclaration(_) => continue,
1022                // A window hold is a standing state, not something this pass did: the
1023                // analysis partition already drops it (exactly as it drops
1024                // `SkippedActive`), and keeping this execution-pass copy would put it
1025                // in `--json` only for repositories that also had a candidate.
1026                // `--explain`, `status` and `doctor` are where the window is named.
1027                PruneStatus::SkippedAdapterWindow(_) => continue,
1028                _ => {}
1029            }
1030            all_results.push(result);
1031        }
1032
1033        // Persisted after every repository, not once at the end. A pass killed
1034        // half-way through used to leave the registry describing the *previous*
1035        // pass, so `devp restore --last-run` offered to reinstall directories that
1036        // were never deleted and said nothing about the ones that were. A save
1037        // failure here is silent — the final save below reports it.
1038        if pruned_dirs.len() > recorded_before {
1039            registry.record_prune_progress(pass_at, pruned_dirs.clone());
1040            crate::history::record(pass_at, trigger, &pruned_dirs);
1041            let _ = registry.save();
1042        }
1043    }
1044
1045    crate::history::record(pass_at, trigger, &pruned_dirs);
1046    registry.record_prune_progress(pass_at, pruned_dirs);
1047    // The save result is checked *after* the JSON document is out. The deletions have
1048    // already happened, and a registry that cannot be written must not swallow the
1049    // only machine-readable record of what this pass deleted.
1050    let saved = registry.save();
1051
1052    if args.json {
1053        json::emit(&json::run_document(&all_results, false))?;
1054        saved?;
1055        // The document already carries `summary.errors`; a non-zero exit keeps the
1056        // shell contract identical in both output modes.
1057        if error_count > 0 {
1058            anyhow::bail!("{error_count} repositories could not be pruned.");
1059        }
1060        return Ok(());
1061    }
1062    saved?;
1063
1064    output::print_header(i18n::t("run.summary"));
1065    output::print_success(&i18n::tf(
1066        "run.freed",
1067        &[
1068            ("size", &output::format_bytes_styled(total_freed)),
1069            ("count", &pruned_count.to_string()),
1070        ],
1071    ));
1072
1073    if error_count > 0 {
1074        output::print_warning(&i18n::tf(
1075            "run.not_pruned",
1076            &[("count", &error_count.to_string())],
1077        ));
1078
1079        // Only when a lockfile was actually the problem. `error_count` also counts
1080        // unreadable configs and failed deletions, and a lecture about lockfiles in front
1081        // of a JSON syntax error sends the user to the wrong file.
1082        if all_results
1083            .iter()
1084            .any(|r| matches!(r.status, PruneStatus::LockfileError(_)))
1085        {
1086            // Lockfile enforcement is not overridable — `--ignore-idle` only bypasses the idle
1087            // check. Without a lockfile a deleted dependency tree cannot be rebuilt, so
1088            // point at the fix instead of offering an override that does not exist.
1089            output::print_info(
1090                "Lockfile verification cannot be bypassed: without a lockfile the deleted \
1091                 dependencies could not be reinstalled. Run the fix command shown above for \
1092                 each repo, then re-run `devp run`.",
1093            );
1094        }
1095        // Exit non-zero so a scheduled or scripted run surfaces the failure.
1096        anyhow::bail!("{error_count} repositories could not be pruned.");
1097    }
1098
1099    // After the pass, never before it: an upgrade mid-run would swap the binary out
1100    // from under the work the user actually asked for.
1101    crate::commands::update::maybe_auto_update(&registry);
1102
1103    Ok(())
1104}
1105
1106/// Why a repository's activity could not be read, when the reason is one that every
1107/// affected repository shares.
1108///
1109/// Git prints its "dubious ownership" refusal as twelve lines, ten of which are word for
1110/// word identical for every repository it refuses — the same explanation, the same two
1111/// account identifiers, the same `git config` invitation. On a machine where one Windows
1112/// reinstall left twenty-one repositories with a stale owner, printing that per
1113/// repository buries the only line that differs (the path) in two hundred that do not.
1114/// One cause with one fix should read as one paragraph, however many repositories it
1115/// covers.
1116#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1117enum ActivityFailure {
1118    /// Git refuses the working tree because it is owned by another account.
1119    UntrustedOwner,
1120    /// The registered path is no longer a working tree.
1121    NotARepository,
1122    /// Anything else: reported individually, with git's own words.
1123    Individual,
1124}
1125
1126impl ActivityFailure {
1127    /// Classify one activity-check failure from Git's own stderr.
1128    ///
1129    /// Deliberately a substring match on Git's wording rather than a parse. The
1130    /// alternative is asking Git a second question per repository, and the cost of a
1131    /// wrong guess here is a message that reads slightly less well — never a wrong
1132    /// deletion, because a repository in this list is one nothing was done to.
1133    fn classify(message: &str) -> Self {
1134        let lower = message.to_lowercase();
1135        if lower.contains(constants::GIT_DUBIOUS_OWNERSHIP) {
1136            Self::UntrustedOwner
1137        } else if lower.contains(constants::GIT_NOT_A_REPOSITORY) {
1138            Self::NotARepository
1139        } else {
1140            Self::Individual
1141        }
1142    }
1143}
1144
1145/// How many paths a grouped cause lists before it stops and says how many are left.
1146///
1147/// Eight is enough to recognise a pattern — one directory tree, one old drive — without
1148/// the list becoming the thing that has to be scrolled past.
1149const GROUPED_PATHS_SHOWN: usize = 8;
1150
1151/// Report the repositories the analysis pass could not get past, with the fix for each.
1152///
1153/// Silent for an empty list, so callers do not have to guard it.
1154fn report_blocked(blocked: &[PruneResult]) {
1155    if blocked.is_empty() {
1156        return;
1157    }
1158    output::print_header(&i18n::tf(
1159        "run.header.blocked",
1160        &[("count", &blocked.len().to_string())],
1161    ));
1162
1163    let grouped = |failure: ActivityFailure| -> Vec<&PruneResult> {
1164        blocked
1165            .iter()
1166            .filter(|r| match &r.status {
1167                PruneStatus::ActivityCheckError(e) => ActivityFailure::classify(e) == failure,
1168                _ => false,
1169            })
1170            .collect()
1171    };
1172
1173    let untrusted = grouped(ActivityFailure::UntrustedOwner);
1174    if !untrusted.is_empty() {
1175        let n = untrusted.len();
1176        output::print_error(&format!(
1177            "{n} {} owned by a different account — Git will not read {}.",
1178            output::plural(n, "repository is", "repositories are"),
1179            output::plural(n, "it", "them")
1180        ));
1181        list_paths(&untrusted);
1182        output::print_wrapped(
1183            "    ",
1184            "Nothing is wrong with the repositories themselves. The owner recorded on \
1185             disk is usually one a Windows reinstall, a restored backup or a drive moved \
1186             between machines left behind.",
1187        );
1188        output::print_wrapped(
1189            "    ",
1190            "dev-prune dates a repository by its last commit, so one Git will not open \
1191             has no known age — and nothing is ever deleted from a repository whose age is \
1192             unknown.",
1193        );
1194        output::print_info(&format!(
1195            "  Fix all {n} at once:  devp trust --fix-ownership"
1196        ));
1197    }
1198
1199    let orphaned = grouped(ActivityFailure::NotARepository);
1200    if !orphaned.is_empty() {
1201        if !untrusted.is_empty() {
1202            println!();
1203        }
1204        let n = orphaned.len();
1205        output::print_error(&format!(
1206            "{n} registered {} not {} git {} any more.",
1207            output::plural(n, "path is", "paths are"),
1208            output::plural(n, "a", ""),
1209            output::plural(n, "repository", "repositories")
1210        ));
1211        list_paths(&orphaned);
1212        output::print_wrapped(
1213            "    ",
1214            "The directory is still there; its `.git` is not — a clone deleted and \
1215             recreated by hand, or a worktree `git worktree prune` has since removed. The \
1216             registry entry outlived what it pointed at.",
1217        );
1218        // Not `--missing`: that clears entries whose *directory* has gone, and these
1219        // directories are still on disk. Naming the wrong repair here would have the
1220        // user run a command that reports it removed nothing.
1221        output::print_info(&format!(
1222            "  Drop {} from the registry:  devp unlink <path>",
1223            output::plural(n, "it", "them")
1224        ));
1225        // Unlink is not the only sane answer: the directory may hold files worth
1226        // keeping. `git init` on an existing directory touches no working files, so
1227        // offering it costs nothing and saves the user working out that it is safe.
1228        output::print_info(&format!(
1229            "  Or keep {} tracked:  git init <path> makes it a repository again",
1230            output::plural(n, "it", "them")
1231        ));
1232    }
1233
1234    for result in blocked {
1235        let clean_p = output::clean_path(&result.repo_path);
1236        match &result.status {
1237            PruneStatus::ConfigError(e) => {
1238                output::print_error(&format!(
1239                    "{clean_p} skipped — its .devprune.json could not be read:
1240    {}",
1241                    e.trim()
1242                ));
1243                output::print_info(&format!(
1244                    "  Fix command:       devp config {clean_p} --update"
1245                ));
1246            }
1247            PruneStatus::LockfileError(e) => report_lockfile_failure(result, e),
1248            PruneStatus::ActivityCheckError(e)
1249                if ActivityFailure::classify(e) == ActivityFailure::Individual =>
1250            {
1251                output::print_error(&format!(
1252                    "{clean_p} skipped — its activity could not be determined:
1253    {}",
1254                    output::condense_tool_output(e, 4)
1255                ));
1256            }
1257            PruneStatus::DeleteError(e) => {
1258                output::print_error(&format!("{clean_p} → delete failed: {e}"));
1259            }
1260            // Everything else was covered by one of the grouped causes above.
1261            _ => {}
1262        }
1263    }
1264}
1265
1266/// Print the paths of one grouped cause, indented, stopping at [`GROUPED_PATHS_SHOWN`].
1267///
1268/// `--json` is named as the way to see the rest rather than a `--verbose` flag, because
1269/// it already lists every result and is the output a script would be reading anyway.
1270fn list_paths(results: &[&PruneResult]) {
1271    for result in results.iter().take(GROUPED_PATHS_SHOWN) {
1272        println!("    {}", output::styled_path(&result.repo_path));
1273    }
1274    if let Some(rest) = results
1275        .len()
1276        .checked_sub(GROUPED_PATHS_SHOWN)
1277        .filter(|n| *n > 0)
1278    {
1279        output::print_dimmed(&format!(
1280            "    … and {rest} more — `devp run --dry-run --json` lists every one."
1281        ));
1282    }
1283}
1284
1285/// Report directories that were deliberately left alone: symlinks, declarations that
1286/// did not pass their checks, and directories holding a nested git repository.
1287///
1288/// Informational only, never part of the exit code. The storage a link points at is not
1289/// this repository's to delete; a declaration dev-prune refuses is a standing fact about
1290/// the repository's own config. Both are permanent until somebody changes something, and
1291/// failing on either would turn every scheduled pass over such a repo red forever.
1292fn report_left_alone(left_alone: &[PruneResult]) {
1293    for result in left_alone {
1294        if let PruneStatus::SkippedSymlink(e)
1295        | PruneStatus::SkippedDeclaration(e)
1296        | PruneStatus::SkippedNestedRepo(e) = &result.status
1297        {
1298            output::print_warning(&format!(
1299                "{} → {}",
1300                output::clean_path(&result.repo_path),
1301                e.trim()
1302            ));
1303        }
1304    }
1305}
1306
1307/// Report registered paths that no longer exist on disk.
1308///
1309/// Informational only, never part of the exit code: the clone is already gone, the state
1310/// does not fix itself, and failing on it would keep every scheduled pass red until the
1311/// user notices. The fix is one command, so name it.
1312fn report_missing(missing: &[PruneResult]) {
1313    if missing.is_empty() {
1314        return;
1315    }
1316    println!();
1317    let n = missing.len();
1318    output::print_warning(&format!(
1319        "{n} registered {} no longer {} on disk.",
1320        output::plural(n, "path", "paths"),
1321        output::plural(n, "exists", "exist")
1322    ));
1323    // One line per path was fine for the one or two a person deletes by hand. It stopped
1324    // being fine the first time a tool that clones into a temporary directory registered
1325    // thirty of them: the report ended in thirty near-identical lines carrying one
1326    // instruction, repeated thirty times.
1327    for result in missing.iter().take(GROUPED_PATHS_SHOWN) {
1328        println!("    {}", output::styled_path(&result.repo_path));
1329    }
1330    if let Some(rest) = missing
1331        .len()
1332        .checked_sub(GROUPED_PATHS_SHOWN)
1333        .filter(|n| *n > 0)
1334    {
1335        output::print_dimmed(&format!(
1336            "    … and {rest} more — `devp run --dry-run --json` lists every one."
1337        ));
1338    }
1339    output::print_info(&format!(
1340        "  Clear {} from the registry:  devp unlink --missing",
1341        output::plural(n, "it", "them all")
1342    ));
1343}
1344
1345/// Report registered paths that still exist but no longer hold a git repository.
1346///
1347/// Informational only, never part of the exit code — same reasoning as
1348/// [`report_missing`]: the state does not fix itself, and while it counted as blocked
1349/// it kept every scheduled pass red until the user noticed. The hint is deliberately
1350/// different, though: `devp unlink --missing` clears entries whose *directory* has
1351/// gone, and these directories are still on disk — naming it here would have the user
1352/// run a command that reports it removed nothing.
1353fn report_orphaned(orphaned: &[PruneResult]) {
1354    if orphaned.is_empty() {
1355        return;
1356    }
1357    println!();
1358    let n = orphaned.len();
1359    output::print_warning(&format!(
1360        "{n} registered {} not {} git {} any more.",
1361        output::plural(n, "path is", "paths are"),
1362        output::plural(n, "a", ""),
1363        output::plural(n, "repository", "repositories")
1364    ));
1365    for result in orphaned.iter().take(GROUPED_PATHS_SHOWN) {
1366        println!("    {}", output::styled_path(&result.repo_path));
1367    }
1368    if let Some(rest) = orphaned
1369        .len()
1370        .checked_sub(GROUPED_PATHS_SHOWN)
1371        .filter(|n| *n > 0)
1372    {
1373        output::print_dimmed(&format!(
1374            "    … and {rest} more — `devp run --dry-run --json` lists every one."
1375        ));
1376    }
1377    output::print_info(&format!(
1378        "  Drop {} from the registry:  devp unlink <path>",
1379        output::plural(n, "it", "them")
1380    ));
1381    // Same reasoning as the dry-run report: `git init` on an existing directory is
1382    // non-destructive, and it is the repair for the user who wants the entry kept.
1383    output::print_info(&format!(
1384        "  Or keep {} tracked:  git init <path> makes it a repository again",
1385        output::plural(n, "it", "them")
1386    ));
1387}
1388
1389/// Count, per dormant opt-in adapter, the registered repositories that use it.
1390///
1391/// A disabled opt-in adapter never reaches the engine, so the pass above cannot have
1392/// produced a row for it; this is a second, read-only walk asking the one question that
1393/// pass could not. It skips exactly what the pass skips (disabled entries, missing
1394/// paths, the `--except` list, `ignore.devprune.json`, a per-repo `ignore`) and resolves
1395/// depth the same way, so a repository the user has opted out never generates a nag.
1396fn opt_in_recommendations(registry: &Registry, except: &[String]) -> Vec<(String, usize)> {
1397    let mut counts: std::collections::BTreeMap<&'static str, usize> =
1398        std::collections::BTreeMap::new();
1399    for (path, entry) in &registry.repositories {
1400        if !entry.enabled
1401            || !path.exists()
1402            || is_excepted(path, except)
1403            || path.join(constants::DEVPRUNE_IGNORE_FILE).exists()
1404        {
1405            continue;
1406        }
1407        let per_repo = match crate::config::PerRepoConfig::load_with_diagnostics(path) {
1408            Ok(cfg) => cfg,
1409            // The pass refuses an unreadable config; a hint must not read past it.
1410            Err(_) => continue,
1411        };
1412        if per_repo.as_ref().is_some_and(|c| c.ignore) {
1413            continue;
1414        }
1415        let depth = crate::workspace::clamp_depth(
1416            per_repo
1417                .as_ref()
1418                .and_then(|c| c.scan_depth)
1419                .unwrap_or(registry.settings.scan_depth),
1420        );
1421        let mut here: std::collections::BTreeSet<&'static str> = std::collections::BTreeSet::new();
1422        for project in crate::workspace::discover_dormant_opt_in_to_depth(path, depth) {
1423            for adapter in &project.adapters {
1424                here.insert(adapter.name());
1425            }
1426        }
1427        for name in here {
1428            *counts.entry(name).or_insert(0) += 1;
1429        }
1430    }
1431    counts
1432        .into_iter()
1433        .map(|(name, n)| (name.to_string(), n))
1434        .collect()
1435}
1436
1437/// Close the dry-run report with what being switched off is hiding.
1438///
1439/// One line per adapter with the exact command, because the alternative is a user whose
1440/// dry run says "nothing found" on a disk full of `target/` directories and no clue
1441/// that a single setting is why.
1442fn report_recommendations(recommendations: &[(String, usize)]) {
1443    if recommendations.is_empty() {
1444        return;
1445    }
1446    println!();
1447    output::print_header("Detected, but switched off");
1448    for (adapter, repos) in recommendations {
1449        output::print_info(&format!(
1450            "  {adapter}: {repos} {}. Enable with:  devp config set enable_{adapter} true",
1451            output::plural(*repos, "repository", "repositories")
1452        ));
1453    }
1454    output::print_wrapped(
1455        "  ",
1456        "These adapters claim build trees, which come back by recompiling rather than \
1457         re-downloading, so they ship disabled until you opt in. `devp config` shows \
1458         the same switches in a full-screen picker.",
1459    );
1460}
1461
1462/// Turn a non-empty blocked list into the process's failure exit.
1463///
1464/// A pass that skipped a repository the user asked it to handle has not succeeded, and a
1465/// scheduled or scripted run has to be able to see that.
1466fn fail_if_blocked(blocked: &[PruneResult]) -> Result<()> {
1467    if blocked.is_empty() {
1468        return Ok(());
1469    }
1470    anyhow::bail!("{} repositories could not be examined.", blocked.len());
1471}
1472
1473/// Report which ecosystem binaries the pass will need and whether they are present.
1474fn report_binaries(candidates: &[PruneResult]) {
1475    let adapter_names: Vec<String> = candidates.iter().map(|c| c.adapter_name.clone()).collect();
1476    let binary_statuses = adapters::scan_required_binaries(&adapter_names);
1477    if binary_statuses.is_empty() {
1478        return;
1479    }
1480    output::print_header(i18n::t("run.header.binaries"));
1481    for b in &binary_statuses {
1482        if b.available {
1483            output::print_success(&format!(
1484                "  {} — available ({})",
1485                b.name,
1486                b.version.as_deref().unwrap_or("detected")
1487            ));
1488        } else {
1489            output::print_warning(&format!(
1490                "  {} — missing (lockfile fallback active)",
1491                b.name
1492            ));
1493        }
1494    }
1495}
1496
1497fn report_candidates(candidates: &[PruneResult]) {
1498    output::print_header(i18n::t("run.header.candidates"));
1499    for candidate in candidates {
1500        output::print_info(&format!(
1501            "  • {} → {} ({}) [{}]{}",
1502            output::styled_path(&candidate.repo_path),
1503            candidate.bloat_dir,
1504            output::format_bytes_styled(candidate.size_freed),
1505            output::styled_adapter(&candidate.adapter_name),
1506            output::shared_note(candidate.shared_bytes, &candidate.adapter_name)
1507        ));
1508    }
1509}
1510
1511pub(crate) fn report_lockfile_failure(result: &PruneResult, error: &str) {
1512    // The project directory, not the repository root: a monorepo reports
1513    // `backend/.venv`, and `uv lock` at the root would not fix it.
1514    let project = output::clean_path(result.project_dir());
1515
1516    output::print_error(&format!(
1517        "{} → {} lockfile sync failed:\n    {}",
1518        project,
1519        result.adapter_name,
1520        error.trim(),
1521    ));
1522    match json::lockfile_fix_command(&result.adapter_name) {
1523        Some(sync_cmd) => {
1524            // `;` on PowerShell, `&&` on a POSIX shell — pasted, either has to work as
1525            // typed or the `cd` is decoration.
1526            #[cfg(windows)]
1527            let manual_cmd = format!("cd \"{project}\"; {sync_cmd}");
1528            #[cfg(not(windows))]
1529            let manual_cmd = format!("cd \"{project}\" && {sync_cmd}");
1530            output::print_info(&format!("  Fix command:       {manual_cmd}"));
1531        }
1532        // venv, gradle, maven and swift have no mechanical fix — saying where still
1533        // beats sending someone to the repository root to go looking.
1534        None => output::print_info(&format!("  Fix it in:         {project}")),
1535    }
1536    output::print_info(&format!(
1537        "  Troubleshooting:   {}",
1538        constants::TROUBLESHOOTING_URL
1539    ));
1540}
1541
1542/// `devp run --explain` — the decision for every repository and directory, with
1543/// nothing done.
1544///
1545/// The prune pass keeps quiet about the states that are not its job to fix — a
1546/// repository still active, one opted out, a directory under the size floor — which is
1547/// exactly what someone staring at "no candidates found" needs to hear about. This mode
1548/// runs the same analysis and reports every verdict instead of only the actionable
1549/// ones. Read-only by construction: the engine runs in dry-run mode, and the size floor
1550/// is applied here in the report rather than in the engine, so a too-small directory is
1551/// named as too small instead of silently missing.
1552fn run_explain(args: &RunArgs<'_>, filter: &AdapterFilter) -> Result<()> {
1553    output::print_header(i18n::t("run.header.reasons"));
1554    if let Some(desc) = filter.describe() {
1555        output::print_info(&format!("Adapter filter: {desc}"));
1556    }
1557
1558    if let Some(target_str) = args.target_path {
1559        let raw = Path::new(target_str);
1560        let path = if raw.exists() {
1561            raw.canonicalize().unwrap_or_else(|_| raw.to_path_buf())
1562        } else {
1563            raw.to_path_buf()
1564        };
1565        if !crate::scanner::is_git_repo(&path) {
1566            anyhow::bail!(
1567                "{} is not a Git repository — dev-prune only prunes Git repos.",
1568                output::clean_path(&path)
1569            );
1570        }
1571        let registry = Registry::load().ok();
1572        let idle_days = registry
1573            .as_ref()
1574            .map(|r| {
1575                r.repositories
1576                    .get(&path)
1577                    .and_then(|e| e.override_idle_days)
1578                    .unwrap_or(r.settings.idle_days)
1579            })
1580            .unwrap_or(constants::DEFAULT_IDLE_DAYS);
1581        let floor = resolve_min_size(args, registry.as_ref());
1582        let results = engine::prune_repo_with(
1583            &path,
1584            &PruneOptions {
1585                idle_days,
1586                dry_run: true,
1587                force: args.force,
1588                only_dirs: None,
1589                adapters: filter.clone(),
1590                min_size_bytes: 0,
1591                scan_depth: resolve_scan_depth(registry.as_ref()),
1592                allow_manifest_rewrite: resolve_manifest_rewrite(registry.as_ref()),
1593                command_timeout_secs: resolve_command_timeout(registry.as_ref()),
1594                build_idle_days: resolve_build_idle_days(registry.as_ref()),
1595                adapter_idle_days: resolve_adapter_idle_days(registry.as_ref()),
1596            },
1597        );
1598        let refs: Vec<&PruneResult> = results.iter().collect();
1599        explain_repo(&path, &refs, floor, idle_days);
1600        print_explain_footer();
1601        return Ok(());
1602    }
1603
1604    let mut registry = Registry::load()?;
1605    if registry.repo_count() == 0 {
1606        output::print_warning("No repositories registered. Run `dev-prune init` first.");
1607        return Ok(());
1608    }
1609
1610    let except = parse_except(args.except);
1611    let global_floor = resolve_min_size(args, Some(&registry));
1612    let analysis = PruneOptions {
1613        idle_days: 0, // replaced per repository from the registry
1614        dry_run: true,
1615        force: args.force,
1616        only_dirs: None,
1617        adapters: filter.clone(),
1618        min_size_bytes: 0,
1619        scan_depth: resolve_scan_depth(Some(&registry)),
1620        allow_manifest_rewrite: resolve_manifest_rewrite(Some(&registry)),
1621        command_timeout_secs: resolve_command_timeout(Some(&registry)),
1622        build_idle_days: resolve_build_idle_days(Some(&registry)),
1623        adapter_idle_days: resolve_adapter_idle_days(Some(&registry)),
1624    };
1625    let results = engine::prune_all_with(&mut registry, &analysis);
1626
1627    let mut by_repo: std::collections::HashMap<&Path, Vec<&PruneResult>> =
1628        std::collections::HashMap::new();
1629    for r in &results {
1630        by_repo.entry(r.repo_path.as_path()).or_default().push(r);
1631    }
1632
1633    let mut repos: Vec<&std::path::PathBuf> = registry.repositories.keys().collect();
1634    repos.sort();
1635    for path in repos {
1636        if is_excepted(path, &except) {
1637            println!();
1638            output::print_info(&output::clean_path(path));
1639            println!("  • left completely alone this pass (`--except`)");
1640            continue;
1641        }
1642        let idle_days = registry
1643            .repositories
1644            .get(path)
1645            .and_then(|e| e.override_idle_days)
1646            .unwrap_or(registry.settings.idle_days);
1647        let empty = Vec::new();
1648        let repo_results = by_repo.get(path.as_path()).unwrap_or(&empty);
1649        explain_repo(path, repo_results, global_floor, idle_days);
1650    }
1651    print_explain_footer();
1652    Ok(())
1653}
1654
1655/// One repository's verdicts, one line per decision.
1656fn explain_repo(path: &Path, results: &[&PruneResult], floor: u64, idle_days: u64) {
1657    println!();
1658    output::print_info(&output::clean_path(path));
1659
1660    if results.is_empty() {
1661        println!(
1662            "  • idle, but no known bloat directories were found. A project deeper than \
1663             `scan_depth` is not examined — `devp status` shows what dev-prune can see."
1664        );
1665        return;
1666    }
1667
1668    for r in results {
1669        match &r.status {
1670            PruneStatus::SkippedDryRun => {
1671                if r.size_freed >= floor {
1672                    output::print_success(&format!(
1673                        "would prune {} ({}) [{}]{}",
1674                        r.bloat_dir,
1675                        output::format_bytes(r.size_freed),
1676                        r.adapter_name,
1677                        output::shared_note(r.shared_bytes, &r.adapter_name)
1678                    ));
1679                } else {
1680                    println!(
1681                        "  • {} ({}) is under the size floor of {} — the reinstall would \
1682                         cost more than the space is worth. `--min-size 0` includes it.",
1683                        r.bloat_dir,
1684                        output::format_bytes(r.size_freed),
1685                        output::format_bytes(floor)
1686                    );
1687                }
1688            }
1689            PruneStatus::SkippedActive => {
1690                let age = crate::scanner::git::get_last_activity(path)
1691                    .ok()
1692                    .flatten()
1693                    .and_then(|t| std::time::SystemTime::now().duration_since(t).ok())
1694                    .map(|d| d.as_secs() / 86_400);
1695                match age {
1696                    Some(0) => println!(
1697                        "  • active — there was activity today, and the idle \
1698                         threshold is {idle_days} days. `--ignore-idle` overrides."
1699                    ),
1700                    Some(days) => println!(
1701                        "  • active — last activity {days} day{} ago, and the idle \
1702                         threshold is {idle_days} days. `--ignore-idle` overrides.",
1703                        if days == 1 { "" } else { "s" }
1704                    ),
1705                    None => println!(
1706                        "  • active (not idle for {idle_days} days yet). \
1707                         `--ignore-idle` overrides."
1708                    ),
1709                }
1710            }
1711            PruneStatus::SkippedAdapterWindow(days) => println!(
1712                "  • {}: not examined — this adapter waits for {days} idle days \
1713                 (`build_idle_days` / `adapter_idle_days`), and the repository is not \
1714                 idle that long yet. `--ignore-idle` overrides.",
1715                r.adapter_name
1716            ),
1717            other => println!("  • {other}"),
1718        }
1719    }
1720}
1721
1722/// The one-line contract of `--explain`, printed after the verdicts.
1723fn print_explain_footer() {
1724    println!();
1725    output::print_info(
1726        "Nothing was verified or deleted. `devp run --dry-run` verifies candidates; \
1727         `devp run` prunes.",
1728    );
1729}
1730
1731#[cfg(test)]
1732mod tests {
1733    use super::*;
1734
1735    #[test]
1736    fn gits_ownership_refusal_is_recognised_whatever_the_path() {
1737        // The whole grouped report hangs off this substring. If Git ever reworded the
1738        // message, twenty-one repositories would silently go back to printing twelve
1739        // lines each, and nothing else in the suite would notice.
1740        let message = "git could not read `V:/x`: fatal: detected dubious ownership in repository \
1741                       at 'V:/x'";
1742        assert_eq!(
1743            ActivityFailure::classify(message),
1744            ActivityFailure::UntrustedOwner
1745        );
1746    }
1747
1748    #[test]
1749    fn a_path_that_lost_its_git_directory_is_its_own_cause() {
1750        // Deliberately distinct from UntrustedOwner: the two have different fixes, and
1751        // pointing the user at `devp unlink --missing` for a directory that still exists
1752        // is a command that reports it removed nothing.
1753        let message = "fatal: not a git repository (or any of the parent directories): .git";
1754        assert_eq!(
1755            ActivityFailure::classify(message),
1756            ActivityFailure::NotARepository
1757        );
1758    }
1759
1760    #[test]
1761    fn an_unfamiliar_failure_is_still_printed_in_full() {
1762        assert_eq!(
1763            ActivityFailure::classify("fatal: unable to read tree"),
1764            ActivityFailure::Individual
1765        );
1766    }
1767}