1use 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
25pub struct RunArgs<'a> {
30 pub target_path: Option<&'a str>,
32 pub dry_run: bool,
34 pub force: bool,
36 pub yes: bool,
38 pub daemon: bool,
40 pub only: Option<&'a str>,
42 pub skip: Option<&'a str>,
44 pub min_size_mb: Option<u64>,
46 pub except: Option<&'a str>,
48 pub json: bool,
50 pub explain: bool,
52}
53
54pub fn run(args: RunArgs<'_>) -> Result<()> {
59 let filter = AdapterFilter::new(args.only, args.skip)?;
60
61 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
88fn 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 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
129fn 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 anyhow::bail!("{clean} is not a Git repository — dev-prune only prunes Git repos.");
143 }
144
145 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 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 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 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 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 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 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
373fn 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 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 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
421fn 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
433fn 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
453fn 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
477fn 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
484fn 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
491fn 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
506fn 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
513fn 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 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 if !args.json && crate::commands::update::notify_if_outdated(&mut registry) {
542 let _ = registry.save();
543 }
544
545 if args.daemon && registry.settings.auto_discover && !setup::no_auto_setup_requested() {
557 let found = crate::discovery::discover(®istry)?;
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 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(®istry));
612 let analysis = PruneOptions {
613 idle_days: 0, 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(®istry)),
620 allow_manifest_rewrite: resolve_manifest_rewrite(Some(®istry)),
621 command_timeout_secs: resolve_command_timeout(Some(®istry)),
622 build_idle_days: resolve_build_idle_days(Some(®istry)),
623 adapter_idle_days: resolve_adapter_idle_days(Some(®istry)),
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 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 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 PruneStatus::SkippedSymlink(_)
676 | PruneStatus::SkippedDeclaration(_)
677 | PruneStatus::SkippedNestedRepo(_) => left_alone.push(result),
678 PruneStatus::PathMissing => missing.push(result),
681 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 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 if args.dry_run {
715 if args.json {
716 json::emit(&json::run_document(
717 &[candidates, blocked, left_alone, missing, orphaned].concat(),
718 true,
719 ))?;
720 return Ok(());
721 }
722 if candidates.is_empty()
723 && blocked.is_empty()
724 && left_alone.is_empty()
725 && missing.is_empty()
726 && orphaned.is_empty()
727 {
728 output::print_info(i18n::t("run.nothing"));
729 return Ok(());
730 }
731 if !candidates.is_empty() {
732 report_candidates(&candidates);
733 }
734 let total: u64 = candidates.iter().map(|c| c.size_freed).sum();
735 output::print_header(i18n::t("run.summary.dry"));
736 output::print_info(&i18n::tf(
737 "run.would_free",
738 &[
739 ("size", &output::format_bytes(total)),
740 ("count", &candidates.len().to_string()),
741 ],
742 ));
743 report_blocked(&blocked);
746 report_left_alone(&left_alone);
747 report_missing(&missing);
748 report_orphaned(&orphaned);
749 return Ok(());
750 }
751
752 if candidates.is_empty() {
753 if args.json {
754 json::emit(&json::run_document(
755 &[blocked.clone(), left_alone, missing, orphaned].concat(),
756 false,
757 ))?;
758 return fail_if_blocked(&blocked);
759 }
760 if blocked.is_empty() && left_alone.is_empty() && missing.is_empty() && orphaned.is_empty()
761 {
762 output::print_info(i18n::t("run.nothing"));
763 return Ok(());
764 }
765 output::print_info(i18n::t("run.nothing.bloat"));
766 report_blocked(&blocked);
767 report_left_alone(&left_alone);
768 report_missing(&missing);
769 report_orphaned(&orphaned);
770 return fail_if_blocked(&blocked);
771 }
772
773 let total_reclaimable: u64 = candidates.iter().map(|c| c.size_freed).sum();
774
775 if !args.json {
776 report_binaries(&candidates);
777 report_candidates(&candidates);
778 output::print_info(&i18n::tf(
779 "run.reclaimable",
780 &[("size", &output::format_bytes_styled(total_reclaimable))],
781 ));
782 report_blocked(&blocked);
783 report_left_alone(&left_alone);
784 report_missing(&missing);
785 report_orphaned(&orphaned);
786 }
787
788 let target_candidates: Vec<PruneResult> = if args.json
791 || args.yes
792 || !registry.settings.require_confirmation
793 {
794 candidates
795 } else if io::stdout().is_terminal() && io::stdin().is_terminal() {
796 eprintln!();
797 eprintln!(
798 " Loading interactive selector... (↑↓ navigate, Space toggle, Enter confirm, q cancel)"
799 );
800 eprintln!();
801 let selected = tui::selection_view::select_candidates_tui(&candidates)?;
802 if selected.is_empty() {
803 output::print_info("Prune pass cancelled by user (0 candidates selected).");
804 return Ok(());
805 }
806 selected
807 } else {
808 if !io::stdin().is_terminal() {
812 anyhow::bail!(
813 "Deleting {} directories ({}) needs confirmation, and there is no \
814 terminal to ask on. Re-run with `--yes` to confirm, or `--dry-run` \
815 to only analyse.",
816 candidates.len(),
817 output::format_bytes(total_reclaimable)
818 );
819 }
820 println!();
821 output::print_warning("CAUTION: Deleting bloat directories cannot be undone directly.");
822 output::print_info(
823 "Note: You can re-install missing dependencies anytime using `dev-prune restore`.",
824 );
825 eprint!(
828 "Proceed with deletion of {} directories ({})? [y/N]: ",
829 candidates.len(),
830 output::format_bytes(total_reclaimable)
831 );
832 io::stderr().flush()?;
833
834 let mut input = String::new();
835 io::stdin().read_line(&mut input)?;
836 let trimmed = input.trim().to_lowercase();
837 if trimmed != "y" && trimmed != "yes" {
838 output::print_info("Prune pass aborted by user.");
839 return Ok(());
840 }
841 candidates
842 };
843
844 if !args.json {
845 let selected_total_bytes: u64 = target_candidates.iter().map(|c| c.size_freed).sum();
846 output::print_header(&i18n::tf(
847 "run.header.deleting",
848 &[
849 ("repos", &target_candidates.len().to_string()),
850 ("size", &output::format_bytes(selected_total_bytes)),
851 ],
852 ));
853 }
854
855 let mut selection: Vec<(std::path::PathBuf, Vec<String>)> = Vec::new();
861 for candidate in &target_candidates {
862 match selection
863 .iter_mut()
864 .find(|(p, _)| *p == candidate.repo_path)
865 {
866 Some((_, dirs)) => dirs.push(candidate.bloat_dir.clone()),
867 None => selection.push((
868 candidate.repo_path.clone(),
869 vec![candidate.bloat_dir.clone()],
870 )),
871 }
872 }
873
874 let mut error_count = blocked.len();
878 let mut all_results: Vec<PruneResult> = blocked;
879 all_results.extend(left_alone);
880 all_results.extend(missing);
881 all_results.extend(orphaned);
882 let mut total_freed: u64 = 0;
883 let mut pruned_count = 0;
884 let mut pruned_dirs: Vec<crate::config::PrunedDir> = Vec::new();
885 let pass_at = chrono::Utc::now();
888 let trigger = crate::history::Trigger::for_run(args.daemon);
889
890 for (repo_path, dirs) in &selection {
891 let recorded_before = pruned_dirs.len();
892 let idle_days = registry
897 .repositories
898 .get(repo_path)
899 .and_then(|e| e.override_idle_days)
900 .unwrap_or(registry.settings.idle_days);
901 let single_results = engine::prune_repo_with(
902 repo_path,
903 &PruneOptions {
904 idle_days,
905 dry_run: false,
906 force: args.force,
907 only_dirs: Some(dirs.clone()),
908 adapters: filter.clone(),
909 min_size_bytes: 0,
910 scan_depth: analysis.scan_depth,
911 allow_manifest_rewrite: analysis.allow_manifest_rewrite,
912 command_timeout_secs: analysis.command_timeout_secs,
913 build_idle_days: analysis.build_idle_days,
914 adapter_idle_days: analysis.adapter_idle_days.clone(),
915 },
916 );
917 for result in single_results {
918 match &result.status {
919 PruneStatus::Pruned => {
920 total_freed += result.size_freed;
921 pruned_count += 1;
922 registry.mark_pruned(&result.repo_path, result.size_freed);
923 pruned_dirs.push(crate::config::PrunedDir {
924 repo_path: result.repo_path.clone(),
925 bloat_dir: result.bloat_dir.clone(),
926 adapter: result.adapter_name.clone(),
927 size_freed: result.size_freed,
928 runtime: result.runtime.clone(),
929 });
930 if !args.json {
931 output::print_success(&format!(
932 "{} → {} ({}) — {}{}",
933 output::clean_path(&result.repo_path),
934 result.bloat_dir,
935 output::format_bytes(result.size_freed),
936 result.adapter_name,
937 output::shared_note(result.shared_bytes, &result.adapter_name)
938 ));
939 }
940 }
941 PruneStatus::LockfileError(e) => {
942 error_count += 1;
943 if !args.json {
944 report_lockfile_failure(&result, e);
945 }
946 }
947 PruneStatus::ActivityCheckError(e) => {
948 error_count += 1;
949 if !args.json {
950 output::print_error(&format!(
951 "{} skipped — its activity could not be determined:\n {}",
952 output::clean_path(&result.repo_path),
953 e.trim()
954 ));
955 }
956 }
957 PruneStatus::DeleteError(e) => {
958 error_count += 1;
959 if result.size_freed > 0 {
964 pruned_dirs.push(crate::config::PrunedDir {
965 repo_path: result.repo_path.clone(),
966 bloat_dir: result.bloat_dir.clone(),
967 adapter: result.adapter_name.clone(),
968 size_freed: result.size_freed,
969 runtime: result.runtime.clone(),
970 });
971 }
972 if !args.json {
973 output::print_error(&format!(
974 "{} → delete failed: {}",
975 output::clean_path(&result.repo_path),
976 e,
977 ));
978 }
979 }
980 PruneStatus::ConfigError(e) => {
981 error_count += 1;
982 if !args.json {
983 let clean_p = output::clean_path(&result.repo_path);
984 output::print_error(&format!(
985 "{clean_p} skipped — its .devprune.json could not be read:\n {}",
986 e.trim()
987 ));
988 output::print_info(&format!(
989 " Fix command: devp config {clean_p} --update"
990 ));
991 }
992 }
993 PruneStatus::SkippedActive if !args.json => {
996 output::print_info(&format!(
997 "{} became active since the analysis — left alone. \
998 Use `--ignore-idle` to prune it anyway.",
999 output::clean_path(&result.repo_path)
1000 ));
1001 }
1002 PruneStatus::SkippedDeclaration(_) => continue,
1007 PruneStatus::SkippedAdapterWindow(_) => continue,
1013 _ => {}
1014 }
1015 all_results.push(result);
1016 }
1017
1018 if pruned_dirs.len() > recorded_before {
1024 registry.record_prune_progress(pass_at, pruned_dirs.clone());
1025 crate::history::record(pass_at, trigger, &pruned_dirs);
1026 let _ = registry.save();
1027 }
1028 }
1029
1030 crate::history::record(pass_at, trigger, &pruned_dirs);
1031 registry.record_prune_progress(pass_at, pruned_dirs);
1032 let saved = registry.save();
1036
1037 if args.json {
1038 json::emit(&json::run_document(&all_results, false))?;
1039 saved?;
1040 if error_count > 0 {
1043 anyhow::bail!("{error_count} repositories could not be pruned.");
1044 }
1045 return Ok(());
1046 }
1047 saved?;
1048
1049 output::print_header(i18n::t("run.summary"));
1050 output::print_success(&i18n::tf(
1051 "run.freed",
1052 &[
1053 ("size", &output::format_bytes_styled(total_freed)),
1054 ("count", &pruned_count.to_string()),
1055 ],
1056 ));
1057
1058 if error_count > 0 {
1059 output::print_warning(&i18n::tf(
1060 "run.not_pruned",
1061 &[("count", &error_count.to_string())],
1062 ));
1063
1064 if all_results
1068 .iter()
1069 .any(|r| matches!(r.status, PruneStatus::LockfileError(_)))
1070 {
1071 output::print_info(
1075 "Lockfile verification cannot be bypassed: without a lockfile the deleted \
1076 dependencies could not be reinstalled. Run the fix command shown above for \
1077 each repo, then re-run `devp run`.",
1078 );
1079 }
1080 anyhow::bail!("{error_count} repositories could not be pruned.");
1082 }
1083
1084 crate::commands::update::maybe_auto_update(®istry);
1087
1088 Ok(())
1089}
1090
1091#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1102enum ActivityFailure {
1103 UntrustedOwner,
1105 NotARepository,
1107 Individual,
1109}
1110
1111impl ActivityFailure {
1112 fn classify(message: &str) -> Self {
1119 let lower = message.to_lowercase();
1120 if lower.contains(constants::GIT_DUBIOUS_OWNERSHIP) {
1121 Self::UntrustedOwner
1122 } else if lower.contains(constants::GIT_NOT_A_REPOSITORY) {
1123 Self::NotARepository
1124 } else {
1125 Self::Individual
1126 }
1127 }
1128}
1129
1130const GROUPED_PATHS_SHOWN: usize = 8;
1135
1136fn report_blocked(blocked: &[PruneResult]) {
1140 if blocked.is_empty() {
1141 return;
1142 }
1143 output::print_header(&i18n::tf(
1144 "run.header.blocked",
1145 &[("count", &blocked.len().to_string())],
1146 ));
1147
1148 let grouped = |failure: ActivityFailure| -> Vec<&PruneResult> {
1149 blocked
1150 .iter()
1151 .filter(|r| match &r.status {
1152 PruneStatus::ActivityCheckError(e) => ActivityFailure::classify(e) == failure,
1153 _ => false,
1154 })
1155 .collect()
1156 };
1157
1158 let untrusted = grouped(ActivityFailure::UntrustedOwner);
1159 if !untrusted.is_empty() {
1160 let n = untrusted.len();
1161 output::print_error(&format!(
1162 "{n} {} owned by a different account — Git will not read {}.",
1163 output::plural(n, "repository is", "repositories are"),
1164 output::plural(n, "it", "them")
1165 ));
1166 list_paths(&untrusted);
1167 output::print_wrapped(
1168 " ",
1169 "Nothing is wrong with the repositories themselves. The owner recorded on \
1170 disk is usually one a Windows reinstall, a restored backup or a drive moved \
1171 between machines left behind.",
1172 );
1173 output::print_wrapped(
1174 " ",
1175 "dev-prune dates a repository by its last commit, so one Git will not open \
1176 has no known age — and nothing is ever deleted from a repository whose age is \
1177 unknown.",
1178 );
1179 output::print_info(&format!(
1180 " Fix all {n} at once: devp trust --fix-ownership"
1181 ));
1182 }
1183
1184 let orphaned = grouped(ActivityFailure::NotARepository);
1185 if !orphaned.is_empty() {
1186 if !untrusted.is_empty() {
1187 println!();
1188 }
1189 let n = orphaned.len();
1190 output::print_error(&format!(
1191 "{n} registered {} not {} git {} any more.",
1192 output::plural(n, "path is", "paths are"),
1193 output::plural(n, "a", ""),
1194 output::plural(n, "repository", "repositories")
1195 ));
1196 list_paths(&orphaned);
1197 output::print_wrapped(
1198 " ",
1199 "The directory is still there; its `.git` is not — a clone deleted and \
1200 recreated by hand, or a worktree `git worktree prune` has since removed. The \
1201 registry entry outlived what it pointed at.",
1202 );
1203 output::print_info(&format!(
1207 " Drop {} from the registry: devp unlink <path>",
1208 output::plural(n, "it", "them")
1209 ));
1210 }
1211
1212 for result in blocked {
1213 let clean_p = output::clean_path(&result.repo_path);
1214 match &result.status {
1215 PruneStatus::ConfigError(e) => {
1216 output::print_error(&format!(
1217 "{clean_p} skipped — its .devprune.json could not be read:
1218 {}",
1219 e.trim()
1220 ));
1221 output::print_info(&format!(
1222 " Fix command: devp config {clean_p} --update"
1223 ));
1224 }
1225 PruneStatus::LockfileError(e) => report_lockfile_failure(result, e),
1226 PruneStatus::ActivityCheckError(e)
1227 if ActivityFailure::classify(e) == ActivityFailure::Individual =>
1228 {
1229 output::print_error(&format!(
1230 "{clean_p} skipped — its activity could not be determined:
1231 {}",
1232 output::condense_tool_output(e, 4)
1233 ));
1234 }
1235 PruneStatus::DeleteError(e) => {
1236 output::print_error(&format!("{clean_p} → delete failed: {e}"));
1237 }
1238 _ => {}
1240 }
1241 }
1242}
1243
1244fn list_paths(results: &[&PruneResult]) {
1249 for result in results.iter().take(GROUPED_PATHS_SHOWN) {
1250 println!(" {}", output::styled_path(&result.repo_path));
1251 }
1252 if let Some(rest) = results
1253 .len()
1254 .checked_sub(GROUPED_PATHS_SHOWN)
1255 .filter(|n| *n > 0)
1256 {
1257 output::print_dimmed(&format!(
1258 " … and {rest} more — `devp run --dry-run --json` lists every one."
1259 ));
1260 }
1261}
1262
1263fn report_left_alone(left_alone: &[PruneResult]) {
1271 for result in left_alone {
1272 if let PruneStatus::SkippedSymlink(e)
1273 | PruneStatus::SkippedDeclaration(e)
1274 | PruneStatus::SkippedNestedRepo(e) = &result.status
1275 {
1276 output::print_warning(&format!(
1277 "{} → {}",
1278 output::clean_path(&result.repo_path),
1279 e.trim()
1280 ));
1281 }
1282 }
1283}
1284
1285fn report_missing(missing: &[PruneResult]) {
1291 if missing.is_empty() {
1292 return;
1293 }
1294 println!();
1295 let n = missing.len();
1296 output::print_warning(&format!(
1297 "{n} registered {} no longer {} on disk.",
1298 output::plural(n, "path", "paths"),
1299 output::plural(n, "exists", "exist")
1300 ));
1301 for result in missing.iter().take(GROUPED_PATHS_SHOWN) {
1306 println!(" {}", output::styled_path(&result.repo_path));
1307 }
1308 if let Some(rest) = missing
1309 .len()
1310 .checked_sub(GROUPED_PATHS_SHOWN)
1311 .filter(|n| *n > 0)
1312 {
1313 output::print_dimmed(&format!(
1314 " … and {rest} more — `devp run --dry-run --json` lists every one."
1315 ));
1316 }
1317 output::print_info(&format!(
1318 " Clear {} from the registry: devp unlink --missing",
1319 output::plural(n, "it", "them all")
1320 ));
1321}
1322
1323fn report_orphaned(orphaned: &[PruneResult]) {
1332 if orphaned.is_empty() {
1333 return;
1334 }
1335 println!();
1336 let n = orphaned.len();
1337 output::print_warning(&format!(
1338 "{n} registered {} not {} git {} any more.",
1339 output::plural(n, "path is", "paths are"),
1340 output::plural(n, "a", ""),
1341 output::plural(n, "repository", "repositories")
1342 ));
1343 for result in orphaned.iter().take(GROUPED_PATHS_SHOWN) {
1344 println!(" {}", output::styled_path(&result.repo_path));
1345 }
1346 if let Some(rest) = orphaned
1347 .len()
1348 .checked_sub(GROUPED_PATHS_SHOWN)
1349 .filter(|n| *n > 0)
1350 {
1351 output::print_dimmed(&format!(
1352 " … and {rest} more — `devp run --dry-run --json` lists every one."
1353 ));
1354 }
1355 output::print_info(&format!(
1356 " Drop {} from the registry: devp unlink <path>",
1357 output::plural(n, "it", "them")
1358 ));
1359}
1360
1361fn fail_if_blocked(blocked: &[PruneResult]) -> Result<()> {
1366 if blocked.is_empty() {
1367 return Ok(());
1368 }
1369 anyhow::bail!("{} repositories could not be examined.", blocked.len());
1370}
1371
1372fn report_binaries(candidates: &[PruneResult]) {
1374 let adapter_names: Vec<String> = candidates.iter().map(|c| c.adapter_name.clone()).collect();
1375 let binary_statuses = adapters::scan_required_binaries(&adapter_names);
1376 if binary_statuses.is_empty() {
1377 return;
1378 }
1379 output::print_header(i18n::t("run.header.binaries"));
1380 for b in &binary_statuses {
1381 if b.available {
1382 output::print_success(&format!(
1383 " {} — available ({})",
1384 b.name,
1385 b.version.as_deref().unwrap_or("detected")
1386 ));
1387 } else {
1388 output::print_warning(&format!(
1389 " {} — missing (lockfile fallback active)",
1390 b.name
1391 ));
1392 }
1393 }
1394}
1395
1396fn report_candidates(candidates: &[PruneResult]) {
1397 output::print_header(i18n::t("run.header.candidates"));
1398 for candidate in candidates {
1399 output::print_info(&format!(
1400 " • {} → {} ({}) [{}]{}",
1401 output::styled_path(&candidate.repo_path),
1402 candidate.bloat_dir,
1403 output::format_bytes_styled(candidate.size_freed),
1404 output::styled_adapter(&candidate.adapter_name),
1405 output::shared_note(candidate.shared_bytes, &candidate.adapter_name)
1406 ));
1407 }
1408}
1409
1410pub(crate) fn report_lockfile_failure(result: &PruneResult, error: &str) {
1411 let project = output::clean_path(result.project_dir());
1414
1415 output::print_error(&format!(
1416 "{} → {} lockfile sync failed:\n {}",
1417 project,
1418 result.adapter_name,
1419 error.trim(),
1420 ));
1421 match json::lockfile_fix_command(&result.adapter_name) {
1422 Some(sync_cmd) => {
1423 #[cfg(windows)]
1426 let manual_cmd = format!("cd \"{project}\"; {sync_cmd}");
1427 #[cfg(not(windows))]
1428 let manual_cmd = format!("cd \"{project}\" && {sync_cmd}");
1429 output::print_info(&format!(" Fix command: {manual_cmd}"));
1430 }
1431 None => output::print_info(&format!(" Fix it in: {project}")),
1434 }
1435 output::print_info(&format!(
1436 " Troubleshooting: {}",
1437 constants::TROUBLESHOOTING_URL
1438 ));
1439}
1440
1441fn run_explain(args: &RunArgs<'_>, filter: &AdapterFilter) -> Result<()> {
1452 output::print_header(i18n::t("run.header.reasons"));
1453 if let Some(desc) = filter.describe() {
1454 output::print_info(&format!("Adapter filter: {desc}"));
1455 }
1456
1457 if let Some(target_str) = args.target_path {
1458 let raw = Path::new(target_str);
1459 let path = if raw.exists() {
1460 raw.canonicalize().unwrap_or_else(|_| raw.to_path_buf())
1461 } else {
1462 raw.to_path_buf()
1463 };
1464 if !crate::scanner::is_git_repo(&path) {
1465 anyhow::bail!(
1466 "{} is not a Git repository — dev-prune only prunes Git repos.",
1467 output::clean_path(&path)
1468 );
1469 }
1470 let registry = Registry::load().ok();
1471 let idle_days = registry
1472 .as_ref()
1473 .map(|r| {
1474 r.repositories
1475 .get(&path)
1476 .and_then(|e| e.override_idle_days)
1477 .unwrap_or(r.settings.idle_days)
1478 })
1479 .unwrap_or(constants::DEFAULT_IDLE_DAYS);
1480 let floor = resolve_min_size(args, registry.as_ref());
1481 let results = engine::prune_repo_with(
1482 &path,
1483 &PruneOptions {
1484 idle_days,
1485 dry_run: true,
1486 force: args.force,
1487 only_dirs: None,
1488 adapters: filter.clone(),
1489 min_size_bytes: 0,
1490 scan_depth: resolve_scan_depth(registry.as_ref()),
1491 allow_manifest_rewrite: resolve_manifest_rewrite(registry.as_ref()),
1492 command_timeout_secs: resolve_command_timeout(registry.as_ref()),
1493 build_idle_days: resolve_build_idle_days(registry.as_ref()),
1494 adapter_idle_days: resolve_adapter_idle_days(registry.as_ref()),
1495 },
1496 );
1497 let refs: Vec<&PruneResult> = results.iter().collect();
1498 explain_repo(&path, &refs, floor, idle_days);
1499 print_explain_footer();
1500 return Ok(());
1501 }
1502
1503 let mut registry = Registry::load()?;
1504 if registry.repo_count() == 0 {
1505 output::print_warning("No repositories registered. Run `dev-prune init` first.");
1506 return Ok(());
1507 }
1508
1509 let except = parse_except(args.except);
1510 let global_floor = resolve_min_size(args, Some(®istry));
1511 let analysis = PruneOptions {
1512 idle_days: 0, dry_run: true,
1514 force: args.force,
1515 only_dirs: None,
1516 adapters: filter.clone(),
1517 min_size_bytes: 0,
1518 scan_depth: resolve_scan_depth(Some(®istry)),
1519 allow_manifest_rewrite: resolve_manifest_rewrite(Some(®istry)),
1520 command_timeout_secs: resolve_command_timeout(Some(®istry)),
1521 build_idle_days: resolve_build_idle_days(Some(®istry)),
1522 adapter_idle_days: resolve_adapter_idle_days(Some(®istry)),
1523 };
1524 let results = engine::prune_all_with(&mut registry, &analysis);
1525
1526 let mut by_repo: std::collections::HashMap<&Path, Vec<&PruneResult>> =
1527 std::collections::HashMap::new();
1528 for r in &results {
1529 by_repo.entry(r.repo_path.as_path()).or_default().push(r);
1530 }
1531
1532 let mut repos: Vec<&std::path::PathBuf> = registry.repositories.keys().collect();
1533 repos.sort();
1534 for path in repos {
1535 if is_excepted(path, &except) {
1536 println!();
1537 output::print_info(&output::clean_path(path));
1538 println!(" • left completely alone this pass (`--except`)");
1539 continue;
1540 }
1541 let idle_days = registry
1542 .repositories
1543 .get(path)
1544 .and_then(|e| e.override_idle_days)
1545 .unwrap_or(registry.settings.idle_days);
1546 let empty = Vec::new();
1547 let repo_results = by_repo.get(path.as_path()).unwrap_or(&empty);
1548 explain_repo(path, repo_results, global_floor, idle_days);
1549 }
1550 print_explain_footer();
1551 Ok(())
1552}
1553
1554fn explain_repo(path: &Path, results: &[&PruneResult], floor: u64, idle_days: u64) {
1556 println!();
1557 output::print_info(&output::clean_path(path));
1558
1559 if results.is_empty() {
1560 println!(
1561 " • idle, but no known bloat directories were found. A project deeper than \
1562 `scan_depth` is not examined — `devp status` shows what dev-prune can see."
1563 );
1564 return;
1565 }
1566
1567 for r in results {
1568 match &r.status {
1569 PruneStatus::SkippedDryRun => {
1570 if r.size_freed >= floor {
1571 output::print_success(&format!(
1572 "would prune {} ({}) [{}]{}",
1573 r.bloat_dir,
1574 output::format_bytes(r.size_freed),
1575 r.adapter_name,
1576 output::shared_note(r.shared_bytes, &r.adapter_name)
1577 ));
1578 } else {
1579 println!(
1580 " • {} ({}) is under the size floor of {} — the reinstall would \
1581 cost more than the space is worth. `--min-size 0` includes it.",
1582 r.bloat_dir,
1583 output::format_bytes(r.size_freed),
1584 output::format_bytes(floor)
1585 );
1586 }
1587 }
1588 PruneStatus::SkippedActive => {
1589 let age = crate::scanner::git::get_last_activity(path)
1590 .ok()
1591 .flatten()
1592 .and_then(|t| std::time::SystemTime::now().duration_since(t).ok())
1593 .map(|d| d.as_secs() / 86_400);
1594 match age {
1595 Some(0) => println!(
1596 " • active — there was activity today, and the idle \
1597 threshold is {idle_days} days. `--ignore-idle` overrides."
1598 ),
1599 Some(days) => println!(
1600 " • active — last activity {days} day{} ago, and the idle \
1601 threshold is {idle_days} days. `--ignore-idle` overrides.",
1602 if days == 1 { "" } else { "s" }
1603 ),
1604 None => println!(
1605 " • active (not idle for {idle_days} days yet). \
1606 `--ignore-idle` overrides."
1607 ),
1608 }
1609 }
1610 PruneStatus::SkippedAdapterWindow(days) => println!(
1611 " • {}: not examined — this adapter waits for {days} idle days \
1612 (`build_idle_days` / `adapter_idle_days`), and the repository is not \
1613 idle that long yet. `--ignore-idle` overrides.",
1614 r.adapter_name
1615 ),
1616 other => println!(" • {other}"),
1617 }
1618 }
1619}
1620
1621fn print_explain_footer() {
1623 println!();
1624 output::print_info(
1625 "Nothing was verified or deleted. `devp run --dry-run` verifies candidates; \
1626 `devp run` prunes.",
1627 );
1628}
1629
1630#[cfg(test)]
1631mod tests {
1632 use super::*;
1633
1634 #[test]
1635 fn gits_ownership_refusal_is_recognised_whatever_the_path() {
1636 let message = "git could not read `V:/x`: fatal: detected dubious ownership in repository \
1640 at 'V:/x'";
1641 assert_eq!(
1642 ActivityFailure::classify(message),
1643 ActivityFailure::UntrustedOwner
1644 );
1645 }
1646
1647 #[test]
1648 fn a_path_that_lost_its_git_directory_is_its_own_cause() {
1649 let message = "fatal: not a git repository (or any of the parent directories): .git";
1653 assert_eq!(
1654 ActivityFailure::classify(message),
1655 ActivityFailure::NotARepository
1656 );
1657 }
1658
1659 #[test]
1660 fn an_unfamiliar_failure_is_still_printed_in_full() {
1661 assert_eq!(
1662 ActivityFailure::classify("fatal: unable to read tree"),
1663 ActivityFailure::Individual
1664 );
1665 }
1666}