dev_prune/commands/status.rs
1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Handler for the `dev-prune status` command.
5//
6// Displays a rich overview of all registered repositories: status, skip
7// reason, last activity, last pruned date, adapters, and reclaimable space.
8// Also allows launching a prune pass directly from the status view.
9
10use anyhow::Result;
11
12use crate::adapters::DriftReport;
13use crate::commands::hook::HookState;
14use crate::config::Registry;
15use crate::engine::{self, PruneStatus};
16use crate::i18n;
17use crate::output;
18use crate::tui::status_view;
19use crate::workspace;
20
21/// One project's lockfile drift, located: which repository, which project inside it,
22/// which adapter found it, and what it found.
23pub struct ProjectDrift {
24 /// The registered repository the project lives in.
25 pub repository: std::path::PathBuf,
26 /// Project path relative to the repository root, `/`-separated; `"."` is the root.
27 pub project: String,
28 /// The adapter that made the comparison.
29 pub adapter: &'static str,
30 /// The drifted directory, the unrecorded packages, and the command that records them.
31 pub report: DriftReport,
32}
33
34/// Run the `status` command.
35///
36/// `json` replaces the dashboard with one machine-readable document — no banner, no
37/// TUI, no prompt to prune. It deletes nothing, which is what makes it safe to hand to
38/// an agent or a monitoring job. It may still *register* the repository the caller is
39/// standing in, on both paths and deliberately: an agent that asks about a repository
40/// and a human who asks about the same one must not get different answers.
41///
42/// `top` trims the repository list to the biggest reclaims. It never changes the totals:
43/// those are computed over every registered repository, so `--top 5` cannot make a
44/// machine look tidier than it is.
45///
46/// `drift` replaces the dashboard with the lockfile-drift report — the environments
47/// holding packages their lockfile never recorded, found before a prune would refuse
48/// on them.
49pub fn run(top: Option<usize>, drift: bool, json_output: bool) -> Result<()> {
50 if drift {
51 return run_drift(json_output);
52 }
53 let mut registry = Registry::load()?;
54
55 // Before anything is reported: the repository the user is standing in may be one
56 // `git init` created, which fires no Git hook and so has never registered itself.
57 // Asking `devp status` about it is the most likely way to notice, so answer it here
58 // rather than showing a dashboard that is missing the one repository being asked
59 // about. See `link::adopt_enclosing_repo` for the guards.
60 let adopted = crate::commands::link::adopt_enclosing_repo(&mut registry);
61 if adopted.is_some() {
62 registry.save()?;
63 }
64
65 let daemon_st = crate::daemon::daemon_status()
66 .map(|s| s.to_string())
67 .unwrap_or_else(|_| "Unknown".to_string());
68 // Both halves of the hook installation, not just the files. Hook scripts on disk with
69 // `core.hooksPath` pointing at another tool never run, and reporting that as "Active"
70 // is the difference between "my repos register themselves" and silently not.
71 let hook_st = match crate::commands::hook::state() {
72 Ok(HookState::Active) => "Active (post-commit, post-checkout, post-merge)".to_string(),
73 Ok(HookState::Chained { previous, drifted }) if drifted.is_empty() => {
74 format!("Active, chained to {previous}")
75 }
76 Ok(HookState::Chained { previous, drifted }) => format!(
77 "Active, chained to {previous} ({} hook(s) not forwarded)",
78 drifted.len()
79 ),
80 Ok(HookState::Foreign(path)) => format!("Inactive (core.hooksPath belongs to {path})"),
81 Ok(HookState::Absent) | Err(_) => "Inactive".to_string(),
82 };
83
84 if json_output {
85 let repos = engine::get_full_status(®istry);
86 return crate::json::emit(&crate::json::status_document(
87 ®istry, &repos, &daemon_st, &hook_st, top,
88 ));
89 }
90
91 output::print_banner();
92
93 if let Some(path) = &adopted {
94 crate::commands::link::report_cwd_adoption(path);
95 println!();
96 }
97
98 // Only on the human path: JSON output is a contract, and a version notice printed
99 // into it would corrupt the document.
100 if crate::commands::update::notify_if_outdated(&mut registry) {
101 let _ = registry.save();
102 }
103
104 let reg_path = Registry::registry_path()
105 .map(|p| output::clean_path(&p))
106 .unwrap_or_else(|_| "unknown".to_string());
107
108 output::print_info(&format!("Global Config Location: {}", reg_path));
109 output::print_info(&format!("Background OS Daemon: {}", daemon_st));
110 output::print_info(&format!("Background Git Hooks: {}", hook_st));
111 // The minutes are derived, not a hardcoded "(10m)" — that read as the default even
112 // after `devp config set command_timeout_secs 60`.
113 let timeout = registry.settings.command_timeout_secs;
114 output::print_info(&format!(
115 "Global Command Timeout: {timeout}s ({})",
116 format_duration(timeout)
117 ));
118 if registry.settings.min_size_mb > 0 {
119 output::print_info(&format!(
120 "Minimum Directory Size: {} MiB (smaller ones are left alone)",
121 registry.settings.min_size_mb
122 ));
123 }
124 output::print_info(&format!(
125 "Tracked Repositories: {}",
126 registry.repo_count()
127 ));
128 output::print_info(&format!(
129 "Historical Space Saved: {} across {} prune {}",
130 output::format_bytes_styled(registry.total_freed_bytes),
131 registry.total_pruned_count,
132 output::plural(registry.total_pruned_count as usize, "pass", "passes")
133 ));
134 if let Some(n) = top {
135 output::print_info(&format!(
136 "Showing: the {n} {} with the most reclaimable space",
137 output::plural(n, "repository", "repositories")
138 ));
139 }
140 println!();
141
142 // Nothing registered is the first-run state, not an error — but an empty dashboard
143 // with no explanation reads as "the tool is broken", so say how to fill it instead.
144 if registry.repositories.is_empty() {
145 output::print_info(
146 "No repositories are registered yet. `devp init <folder>` scans a folder and \
147 registers every Git repository in it; `devp link .` registers just one.",
148 );
149 return Ok(());
150 }
151
152 // Gather full per-repo detail for ALL registered repositories, then trim the list —
153 // after the totals above, which are deliberately computed over all of them.
154 //
155 // Never on the `--json` path: the bar writes to stderr, but a machine-readable mode
156 // should produce one document and nothing else, and a progress bar in a log capture
157 // is noise a script has to learn to ignore.
158 let scan_bar = (!json_output).then(|| {
159 output::create_progress_bar("Scanning repositories", registry.repositories.len() as u64)
160 });
161 let scanned = engine::get_full_status_reporting(®istry, &|done, _total| {
162 if let Some(pb) = &scan_bar {
163 pb.set_position(done as u64);
164 }
165 });
166 // Over every repository, before `--top` trims the list, for the same reason the
167 // totals above are: `--top 5` must not make the machine look cheaper to undo than
168 // it is.
169 let estimate = restore_estimate_line(®istry, &scanned);
170 let repos = engine::take_top(&scanned, top);
171 if let Some(pb) = scan_bar {
172 // `finish_and_clear`, not `finish`: the dashboard is what the user asked for, and
173 // a completed progress bar left above it is scaffolding.
174 pb.finish_and_clear();
175 }
176
177 if let Some(line) = estimate {
178 output::print_info(&line);
179 println!();
180 }
181
182 if crate::tui::full_screen_is_usable() {
183 // Interactive TUI — pass a loader closure so the TUI can reload after
184 // the user toggles ignore config in .devprune.json or presence of ignore.devprune.json on any repo.
185 // It applies the same trim, so the indices it hands back still address `repos`.
186 let registry_ref = ®istry;
187 match status_view::render_status_tui(&|| {
188 engine::take_top(&engine::get_full_status(registry_ref), top)
189 }) {
190 Ok(Some(candidates)) if !candidates.is_empty() => {
191 // User confirmed a prune from within the status view. The TUI hands
192 // back paths, not indices — an `i` toggle reloads its list, and
193 // indices into the reloaded list do not address `repos` above.
194 output::print_header(i18n::t("status.header.pruning"));
195
196 let mut total_freed: u64 = 0;
197 let mut pruned_count = 0;
198 let mut error_count = 0;
199 // A prune is a prune wherever it was started from. Without this the
200 // dashboard's own pass left no record, so `devp restore --last-run`
201 // silently restored an *older* one.
202 let mut pruned_dirs: Vec<crate::config::PrunedDir> = Vec::new();
203 let pass_at = chrono::Utc::now();
204
205 // `force` here means the idle check is the user's to make, not a
206 // bypass of anything else: the dashboard shows how long each repository
207 // has been idle and they picked these rows off that screen, so asking
208 // the engine the same question again would only refuse the active ones
209 // they deliberately checked. It gates nothing but the two idle
210 // thresholds — lockfile verification still runs on every directory, and
211 // a repository whose lockfile cannot be trusted is refused below.
212 //
213 // Everything else follows the user's settings, exactly as `devp run`
214 // resolves them. The bare `prune_repo` defaults used here before ignored
215 // the configured scan depth, command timeout and manifest-rewrite policy.
216 let opts = engine::PruneOptions {
217 idle_days: 0,
218 dry_run: false,
219 force: true,
220 only_dirs: None,
221 adapters: engine::AdapterFilter::default(),
222 min_size_bytes: registry
223 .settings
224 .min_size_mb
225 .saturating_mul(engine::BYTES_PER_MIB),
226 scan_depth: registry.settings.scan_depth,
227 allow_manifest_rewrite: registry.settings.allow_manifest_rewrite,
228 command_timeout_secs: registry.settings.command_timeout_secs,
229 build_idle_days: registry.settings.build_idle_days,
230 adapter_idle_days: registry.settings.adapter_idle_days.clone(),
231 };
232
233 for path in &candidates {
234 let recorded_before = pruned_dirs.len();
235 let results = engine::prune_repo_with(path, &opts);
236 for result in results {
237 match &result.status {
238 PruneStatus::Pruned => {
239 total_freed += result.size_freed;
240 pruned_count += 1;
241 registry.mark_pruned(&result.repo_path, result.size_freed);
242 pruned_dirs.push(crate::config::PrunedDir {
243 repo_path: result.repo_path.clone(),
244 bloat_dir: result.bloat_dir.clone(),
245 adapter: result.adapter_name.clone(),
246 size_freed: result.size_freed,
247 runtime: result.runtime.clone(),
248 });
249 output::print_success(&format!(
250 "{} → {} ({}) — {}",
251 output::clean_path(&result.repo_path),
252 result.bloat_dir,
253 output::format_bytes(result.size_freed),
254 result.adapter_name,
255 ));
256 }
257 PruneStatus::LockfileError(e) => {
258 error_count += 1;
259 crate::commands::run::report_lockfile_failure(&result, e);
260 }
261 PruneStatus::DeleteError(e) => {
262 error_count += 1;
263 // A non-zero size_freed on a delete error means the
264 // delete got half-way: the directory is corrupt, not
265 // intact. Record it so `devp restore --last-run` can
266 // rebuild it — the error still fails the pass.
267 if result.size_freed > 0 {
268 pruned_dirs.push(crate::config::PrunedDir {
269 repo_path: result.repo_path.clone(),
270 bloat_dir: result.bloat_dir.clone(),
271 adapter: result.adapter_name.clone(),
272 size_freed: result.size_freed,
273 runtime: result.runtime.clone(),
274 });
275 }
276 output::print_error(&format!(
277 "{} delete failed: {}",
278 output::clean_path(&result.repo_path),
279 e,
280 ));
281 }
282 PruneStatus::ConfigError(e) => {
283 error_count += 1;
284 output::print_error(&format!(
285 "{} skipped — unreadable .devprune.json: {}",
286 output::clean_path(&result.repo_path),
287 e,
288 ));
289 }
290 // A warning, not an error: linked storage and a refused
291 // declaration are both deliberately left alone and must
292 // not fail the pass.
293 PruneStatus::SkippedSymlink(e)
294 | PruneStatus::SkippedDeclaration(e)
295 | PruneStatus::SkippedNestedRepo(e) => {
296 output::print_warning(&format!(
297 "{} → {}",
298 output::clean_path(&result.repo_path),
299 e.trim(),
300 ));
301 }
302 _ => {}
303 }
304 }
305
306 // Persisted after every repository, same as `devp run`: a pass
307 // killed half-way through must not leave `--last-run` describing
308 // the previous one. A save failure here is silent — the final
309 // save below reports it.
310 if pruned_dirs.len() > recorded_before {
311 registry.record_prune_progress(pass_at, pruned_dirs.clone());
312 crate::history::record(
313 pass_at,
314 crate::history::Trigger::Dashboard,
315 &pruned_dirs,
316 );
317 let _ = registry.save();
318 }
319 }
320
321 crate::history::record(pass_at, crate::history::Trigger::Dashboard, &pruned_dirs);
322 registry.record_prune_progress(pass_at, pruned_dirs);
323 registry.save()?;
324
325 output::print_header(i18n::t("run.summary"));
326 output::print_success(&i18n::tf(
327 "run.freed",
328 &[
329 ("size", &output::format_bytes(total_freed)),
330 ("count", &pruned_count.to_string()),
331 ],
332 ));
333 // Same contract as `devp run`: a prune that failed exits non-zero,
334 // whether it was started from the dashboard or from the command line.
335 if error_count > 0 {
336 anyhow::bail!("{error_count} directories could not be pruned.");
337 }
338 }
339 Ok(_) => {
340 // User quit without pruning — nothing to do
341 }
342 Err(e) => {
343 // Not necessarily a terminal that cannot do raw mode: toggling ignore
344 // with `i` also ends the view if the config write fails. `{e}` carries
345 // the real reason, so this line does not guess at one.
346 output::print_warning(&format!("Interactive view ended: {e:#}"));
347 status_view::render_status_plain(&repos);
348 }
349 }
350 } else {
351 // Non-TTY: plain text table
352 status_view::render_status_plain(&repos);
353 }
354
355 Ok(())
356}
357
358/// The `--drift` mode: every registered repository, checked for installed-but-unrecorded
359/// packages.
360///
361/// This is the same comparison a prune refuses on, run early and as a pure read — no
362/// package manager is executed and nothing is written. Only the adapters that can
363/// compare an environment against its lockfile from files alone take part (npm, uv,
364/// venv); the others have nothing cheap to say and stay silent rather than guessing.
365fn run_drift(json_output: bool) -> Result<()> {
366 let registry = Registry::load()?;
367
368 let pb = (!json_output)
369 .then(|| output::create_spinner("Comparing environments against lockfiles..."));
370
371 let mut findings: Vec<ProjectDrift> = Vec::new();
372 for path in registry.repositories.keys() {
373 if !path.exists() {
374 continue;
375 }
376 let depth = workspace::resolve_depth(path, registry.settings.scan_depth);
377 for project in workspace::discover_to_depth(path, depth) {
378 for adapter in &project.adapters {
379 for report in adapter.drift(&project.path) {
380 findings.push(ProjectDrift {
381 repository: path.clone(),
382 project: project.relative.clone(),
383 adapter: adapter.name(),
384 report,
385 });
386 }
387 }
388 }
389 }
390 // The registry is a HashMap; without this the same machine lists its drift in a
391 // different order on every run, which reads like the drift itself changed.
392 findings.sort_by(|a, b| {
393 (&a.repository, &a.project, a.adapter, &a.report.directory).cmp(&(
394 &b.repository,
395 &b.project,
396 b.adapter,
397 &b.report.directory,
398 ))
399 });
400
401 if let Some(pb) = pb {
402 pb.finish_and_clear();
403 }
404
405 if json_output {
406 return crate::json::emit(&crate::json::drift_document(&findings));
407 }
408
409 output::print_header(i18n::t("status.header.drift"));
410 println!();
411
412 if findings.is_empty() {
413 output::print_success(
414 "No drift found: nothing is installed that the lockfiles do not record.",
415 );
416 output::print_info(
417 "Checked where a cheap file-level comparison exists: node_modules against \
418 package-lock.json (npm), .venv against uv.lock (uv), and every virtual \
419 environment against requirements.txt (venv).",
420 );
421 return Ok(());
422 }
423
424 let mut last_repo: Option<&std::path::Path> = None;
425 for f in &findings {
426 if last_repo != Some(f.repository.as_path()) {
427 println!(" {}", output::clean_path(&f.repository));
428 last_repo = Some(f.repository.as_path());
429 }
430 let location = if f.project == "." {
431 f.report.directory.clone()
432 } else {
433 format!("{}/{}", f.project, f.report.directory)
434 };
435 let shown = f
436 .report
437 .unrecorded
438 .iter()
439 .take(10)
440 .map(String::as_str)
441 .collect::<Vec<_>>()
442 .join(", ");
443 let suffix = if f.report.unrecorded.len() > 10 {
444 format!(", … and {} more", f.report.unrecorded.len() - 10)
445 } else {
446 String::new()
447 };
448 println!(
449 " {} ({}): {} unrecorded {} — {shown}{suffix}",
450 location,
451 f.adapter,
452 f.report.unrecorded.len(),
453 output::plural(f.report.unrecorded.len(), "package", "packages"),
454 );
455 println!(" record them: {}", f.report.record_command);
456 println!();
457 }
458
459 output::print_info(
460 "A prune refuses to delete these environments as they are — the unrecorded \
461 packages would be lost with no way back. Record them with the command shown, \
462 or uninstall them, and the refusal goes away.",
463 );
464 Ok(())
465}
466
467/// "How long is this to undo?", answered only when this machine has measured enough to
468/// answer it.
469///
470/// The question `devp status` could not answer before. Space it already reports; what
471/// people hesitate over is the reinstall, and every number in this line comes from
472/// restores timed on this machine by `devp restore --last-run` — never from a table of
473/// typical speeds, which would be a number about somebody else's laptop. An adapter that
474/// has never been timed here contributes nothing and is subtracted from the coverage,
475/// so a partial answer says it is partial instead of reading as a whole one.
476fn restore_estimate_line(registry: &Registry, repos: &[engine::RepoStatusEntry]) -> Option<String> {
477 let mut by_adapter: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
478 for repo in repos {
479 for (adapter, bytes) in &repo.reclaimable_by_adapter {
480 *by_adapter.entry(adapter.clone()).or_default() += bytes;
481 }
482 }
483 let total: u64 = by_adapter.values().sum();
484 let tallied: Vec<(String, u64)> = by_adapter.into_iter().collect();
485 let (secs, covered) = registry.estimate_restore(&tallied)?;
486
487 let samples: usize = registry
488 .restore_rates
489 .values()
490 .map(|r| r.samples as usize)
491 .sum();
492 let mut line = format!(
493 "Estimated Restore Cost: ~{} to put it all back, from {} timed {} on this machine",
494 output::format_seconds(secs.round() as u64),
495 samples,
496 output::plural(samples, "restore", "restores"),
497 );
498 if covered < total {
499 line.push_str(&format!(
500 " (covers {} of {} — the rest has never been restored here)",
501 output::format_bytes(covered),
502 output::format_bytes(total),
503 ));
504 }
505 Some(line)
506}
507
508/// A seconds count as the unit a human would have typed it in.
509fn format_duration(secs: u64) -> String {
510 match secs {
511 s if s > 0 && s % 3600 == 0 => format!("{}h", s / 3600),
512 s if s > 0 && s % 60 == 0 => format!("{}m", s / 60),
513 s => format!("{s}s"),
514 }
515}
516
517#[cfg(test)]
518mod tests {
519 use super::*;
520
521 #[test]
522 fn the_timeout_is_described_in_whatever_unit_fits_it() {
523 // The old line hardcoded "(10m)", so every value looked like the default.
524 assert_eq!(format_duration(600), "10m");
525 assert_eq!(format_duration(3600), "1h");
526 assert_eq!(format_duration(90), "90s");
527 assert_eq!(format_duration(0), "0s");
528 }
529}