Skip to main content

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;
11use std::io::{self, IsTerminal};
12
13use crate::adapters::DriftReport;
14use crate::commands::hook::HookState;
15use crate::config::Registry;
16use crate::engine::{self, PruneStatus};
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 is a pure read of state, which is what makes it safe to
38/// hand to an agent or a monitoring job.
39///
40/// `top` trims the repository list to the biggest reclaims. It never changes the totals:
41/// those are computed over every registered repository, so `--top 5` cannot make a
42/// machine look tidier than it is.
43///
44/// `drift` replaces the dashboard with the lockfile-drift report — the environments
45/// holding packages their lockfile never recorded, found before a prune would refuse
46/// on them.
47pub fn run(top: Option<usize>, drift: bool, json_output: bool) -> Result<()> {
48    if drift {
49        return run_drift(json_output);
50    }
51    let mut registry = Registry::load()?;
52
53    let daemon_st = crate::daemon::daemon_status()
54        .map(|s| s.to_string())
55        .unwrap_or_else(|_| "Unknown".to_string());
56    // Both halves of the hook installation, not just the files. Hook scripts on disk with
57    // `core.hooksPath` pointing at another tool never run, and reporting that as "Active"
58    // is the difference between "my repos register themselves" and silently not.
59    let hook_st = match crate::commands::hook::state() {
60        Ok(HookState::Active) => "Active (post-commit, post-checkout, post-merge)".to_string(),
61        Ok(HookState::Chained { previous, drifted }) if drifted.is_empty() => {
62            format!("Active, chained to {previous}")
63        }
64        Ok(HookState::Chained { previous, drifted }) => format!(
65            "Active, chained to {previous} ({} hook(s) not forwarded)",
66            drifted.len()
67        ),
68        Ok(HookState::Foreign(path)) => format!("Inactive (core.hooksPath belongs to {path})"),
69        Ok(HookState::Absent) | Err(_) => "Inactive".to_string(),
70    };
71
72    if json_output {
73        let repos = engine::get_full_status(&registry);
74        return crate::json::emit(&crate::json::status_document(
75            &registry, &repos, &daemon_st, &hook_st, top,
76        ));
77    }
78
79    output::print_banner();
80
81    // Only on the human path: JSON output is a contract, and a version notice printed
82    // into it would corrupt the document.
83    if crate::commands::update::notify_if_outdated(&mut registry) {
84        let _ = registry.save();
85    }
86
87    let reg_path = Registry::registry_path()
88        .map(|p| output::clean_path(&p))
89        .unwrap_or_else(|_| "unknown".to_string());
90
91    output::print_info(&format!("Global Config Location: {}", reg_path));
92    output::print_info(&format!("Background OS Daemon:   {}", daemon_st));
93    output::print_info(&format!("Background Git Hooks:   {}", hook_st));
94    // The minutes are derived, not a hardcoded "(10m)" — that read as the default even
95    // after `devp config set command_timeout_secs 60`.
96    let timeout = registry.settings.command_timeout_secs;
97    output::print_info(&format!(
98        "Global Command Timeout: {timeout}s ({})",
99        format_duration(timeout)
100    ));
101    if registry.settings.min_size_mb > 0 {
102        output::print_info(&format!(
103            "Minimum Directory Size: {} MiB (smaller ones are left alone)",
104            registry.settings.min_size_mb
105        ));
106    }
107    output::print_info(&format!(
108        "Tracked Repositories:   {}",
109        registry.repo_count()
110    ));
111    output::print_info(&format!(
112        "Historical Space Saved: {} across {} prune {}",
113        output::format_bytes_styled(registry.total_freed_bytes),
114        registry.total_pruned_count,
115        output::plural(registry.total_pruned_count as usize, "pass", "passes")
116    ));
117    if let Some(n) = top {
118        output::print_info(&format!(
119            "Showing:                the {n} {} with the most reclaimable space",
120            output::plural(n, "repository", "repositories")
121        ));
122    }
123    println!();
124
125    // Nothing registered is the first-run state, not an error — but an empty dashboard
126    // with no explanation reads as "the tool is broken", so say how to fill it instead.
127    if registry.repositories.is_empty() {
128        output::print_info(
129            "No repositories are registered yet. `devp init <folder>` scans a folder and \
130             registers every Git repository in it; `devp link .` registers just one.",
131        );
132        return Ok(());
133    }
134
135    // Gather full per-repo detail for ALL registered repositories, then trim the list —
136    // after the totals above, which are deliberately computed over all of them.
137    //
138    // Never on the `--json` path: the bar writes to stderr, but a machine-readable mode
139    // should produce one document and nothing else, and a progress bar in a log capture
140    // is noise a script has to learn to ignore.
141    let scan_bar = (!json_output).then(|| {
142        output::create_progress_bar("Scanning repositories", registry.repositories.len() as u64)
143    });
144    let repos = engine::take_top(
145        &engine::get_full_status_reporting(&registry, &|done, _total| {
146            if let Some(pb) = &scan_bar {
147                pb.set_position(done as u64);
148            }
149        }),
150        top,
151    );
152    if let Some(pb) = scan_bar {
153        // `finish_and_clear`, not `finish`: the dashboard is what the user asked for, and
154        // a completed progress bar left above it is scaffolding.
155        pb.finish_and_clear();
156    }
157
158    // Both ends: the dashboard draws on stdout but reads keys from stdin, and with
159    // stdin redirected it would open on a screen no keypress can ever leave.
160    if io::stdout().is_terminal() && io::stdin().is_terminal() {
161        // Interactive TUI — pass a loader closure so the TUI can reload after
162        // the user toggles ignore config in .devprune.json or presence of ignore.devprune.json on any repo.
163        // It applies the same trim, so the indices it hands back still address `repos`.
164        let registry_ref = &registry;
165        match status_view::render_status_tui(&|| {
166            engine::take_top(&engine::get_full_status(registry_ref), top)
167        }) {
168            Ok(Some(candidates)) if !candidates.is_empty() => {
169                // User confirmed a prune from within the status view. The TUI hands
170                // back paths, not indices — an `i` toggle reloads its list, and
171                // indices into the reloaded list do not address `repos` above.
172                output::print_header("Pruning Selected Repositories");
173
174                let mut total_freed: u64 = 0;
175                let mut pruned_count = 0;
176                let mut error_count = 0;
177                // A prune is a prune wherever it was started from. Without this the
178                // dashboard's own pass left no record, so `devp restore --last-run`
179                // silently restored an *older* one.
180                let mut pruned_dirs: Vec<crate::config::PrunedDir> = Vec::new();
181                let pass_at = chrono::Utc::now();
182
183                // The dashboard offered only repositories its own analysis classed as
184                // candidates, so the idle check is settled; everything else follows
185                // the user's settings, exactly as `devp run` resolves them. The bare
186                // `prune_repo` defaults used here before ignored the configured scan
187                // depth, command timeout and manifest-rewrite policy.
188                let opts = engine::PruneOptions {
189                    idle_days: 0,
190                    dry_run: false,
191                    force: true,
192                    only_dirs: None,
193                    adapters: engine::AdapterFilter::default(),
194                    min_size_bytes: registry
195                        .settings
196                        .min_size_mb
197                        .saturating_mul(engine::BYTES_PER_MIB),
198                    scan_depth: registry.settings.scan_depth,
199                    allow_manifest_rewrite: registry.settings.allow_manifest_rewrite,
200                    command_timeout_secs: registry.settings.command_timeout_secs,
201                    build_idle_days: registry.settings.build_idle_days,
202                };
203
204                for path in &candidates {
205                    let recorded_before = pruned_dirs.len();
206                    let results = engine::prune_repo_with(path, &opts);
207                    for result in results {
208                        match &result.status {
209                            PruneStatus::Pruned => {
210                                total_freed += result.size_freed;
211                                pruned_count += 1;
212                                registry.mark_pruned(&result.repo_path, result.size_freed);
213                                pruned_dirs.push(crate::config::PrunedDir {
214                                    repo_path: result.repo_path.clone(),
215                                    bloat_dir: result.bloat_dir.clone(),
216                                    adapter: result.adapter_name.clone(),
217                                    size_freed: result.size_freed,
218                                    runtime: result.runtime.clone(),
219                                });
220                                output::print_success(&format!(
221                                    "{} → {} ({}) — {}",
222                                    output::clean_path(&result.repo_path),
223                                    result.bloat_dir,
224                                    output::format_bytes(result.size_freed),
225                                    result.adapter_name,
226                                ));
227                            }
228                            PruneStatus::LockfileError(e) => {
229                                error_count += 1;
230                                crate::commands::run::report_lockfile_failure(&result, e);
231                            }
232                            PruneStatus::DeleteError(e) => {
233                                error_count += 1;
234                                // A non-zero size_freed on a delete error means the
235                                // delete got half-way: the directory is corrupt, not
236                                // intact. Record it so `devp restore --last-run` can
237                                // rebuild it — the error still fails the pass.
238                                if result.size_freed > 0 {
239                                    pruned_dirs.push(crate::config::PrunedDir {
240                                        repo_path: result.repo_path.clone(),
241                                        bloat_dir: result.bloat_dir.clone(),
242                                        adapter: result.adapter_name.clone(),
243                                        size_freed: result.size_freed,
244                                        runtime: result.runtime.clone(),
245                                    });
246                                }
247                                output::print_error(&format!(
248                                    "{} delete failed: {}",
249                                    output::clean_path(&result.repo_path),
250                                    e,
251                                ));
252                            }
253                            PruneStatus::ConfigError(e) => {
254                                error_count += 1;
255                                output::print_error(&format!(
256                                    "{} skipped — unreadable .devprune.json: {}",
257                                    output::clean_path(&result.repo_path),
258                                    e,
259                                ));
260                            }
261                            // A warning, not an error: linked storage is deliberately
262                            // left alone and must not fail the pass.
263                            PruneStatus::SkippedSymlink(e) => {
264                                output::print_warning(&format!(
265                                    "{} → {}",
266                                    output::clean_path(&result.repo_path),
267                                    e.trim(),
268                                ));
269                            }
270                            _ => {}
271                        }
272                    }
273
274                    // Persisted after every repository, same as `devp run`: a pass
275                    // killed half-way through must not leave `--last-run` describing
276                    // the previous one. A save failure here is silent — the final
277                    // save below reports it.
278                    if pruned_dirs.len() > recorded_before {
279                        registry.record_prune_progress(pass_at, pruned_dirs.clone());
280                        let _ = registry.save();
281                    }
282                }
283
284                registry.record_prune_progress(pass_at, pruned_dirs);
285                registry.save()?;
286
287                output::print_header("Summary");
288                output::print_success(&format!(
289                    "Freed: {} across {pruned_count} directories",
290                    output::format_bytes(total_freed)
291                ));
292                // Same contract as `devp run`: a prune that failed exits non-zero,
293                // whether it was started from the dashboard or from the command line.
294                if error_count > 0 {
295                    anyhow::bail!("{error_count} directories could not be pruned.");
296                }
297            }
298            Ok(_) => {
299                // User quit without pruning — nothing to do
300            }
301            Err(e) => {
302                // Not necessarily a terminal that cannot do raw mode: toggling ignore
303                // with `i` also ends the view if the config write fails. `{e}` carries
304                // the real reason, so this line does not guess at one.
305                output::print_warning(&format!("Interactive view ended: {e:#}"));
306                status_view::render_status_plain(&repos);
307            }
308        }
309    } else {
310        // Non-TTY: plain text table
311        status_view::render_status_plain(&repos);
312    }
313
314    Ok(())
315}
316
317/// The `--drift` mode: every registered repository, checked for installed-but-unrecorded
318/// packages.
319///
320/// This is the same comparison a prune refuses on, run early and as a pure read — no
321/// package manager is executed and nothing is written. Only the adapters that can
322/// compare an environment against its lockfile from files alone take part (npm, uv,
323/// venv); the others have nothing cheap to say and stay silent rather than guessing.
324fn run_drift(json_output: bool) -> Result<()> {
325    let registry = Registry::load()?;
326
327    let pb = (!json_output)
328        .then(|| output::create_spinner("Comparing environments against lockfiles..."));
329
330    let mut findings: Vec<ProjectDrift> = Vec::new();
331    for path in registry.repositories.keys() {
332        if !path.exists() {
333            continue;
334        }
335        let depth = workspace::resolve_depth(path, registry.settings.scan_depth);
336        for project in workspace::discover_to_depth(path, depth) {
337            for adapter in &project.adapters {
338                for report in adapter.drift(&project.path) {
339                    findings.push(ProjectDrift {
340                        repository: path.clone(),
341                        project: project.relative.clone(),
342                        adapter: adapter.name(),
343                        report,
344                    });
345                }
346            }
347        }
348    }
349    // The registry is a HashMap; without this the same machine lists its drift in a
350    // different order on every run, which reads like the drift itself changed.
351    findings.sort_by(|a, b| {
352        (&a.repository, &a.project, a.adapter, &a.report.directory).cmp(&(
353            &b.repository,
354            &b.project,
355            b.adapter,
356            &b.report.directory,
357        ))
358    });
359
360    if let Some(pb) = pb {
361        pb.finish_and_clear();
362    }
363
364    if json_output {
365        return crate::json::emit(&crate::json::drift_document(&findings));
366    }
367
368    output::print_header("Lockfile drift");
369    println!();
370
371    if findings.is_empty() {
372        output::print_success(
373            "No drift found: nothing is installed that the lockfiles do not record.",
374        );
375        output::print_info(
376            "Checked where a cheap file-level comparison exists: node_modules against \
377             package-lock.json (npm), .venv against uv.lock (uv), and every virtual \
378             environment against requirements.txt (venv).",
379        );
380        return Ok(());
381    }
382
383    let mut last_repo: Option<&std::path::Path> = None;
384    for f in &findings {
385        if last_repo != Some(f.repository.as_path()) {
386            println!("  {}", output::clean_path(&f.repository));
387            last_repo = Some(f.repository.as_path());
388        }
389        let location = if f.project == "." {
390            f.report.directory.clone()
391        } else {
392            format!("{}/{}", f.project, f.report.directory)
393        };
394        let shown = f
395            .report
396            .unrecorded
397            .iter()
398            .take(10)
399            .map(String::as_str)
400            .collect::<Vec<_>>()
401            .join(", ");
402        let suffix = if f.report.unrecorded.len() > 10 {
403            format!(", … and {} more", f.report.unrecorded.len() - 10)
404        } else {
405            String::new()
406        };
407        println!(
408            "    {} ({}): {} unrecorded {} — {shown}{suffix}",
409            location,
410            f.adapter,
411            f.report.unrecorded.len(),
412            output::plural(f.report.unrecorded.len(), "package", "packages"),
413        );
414        println!("      record them: {}", f.report.record_command);
415        println!();
416    }
417
418    output::print_info(
419        "A prune refuses to delete these environments as they are — the unrecorded \
420         packages would be lost with no way back. Record them with the command shown, \
421         or uninstall them, and the refusal goes away.",
422    );
423    Ok(())
424}
425
426/// A seconds count as the unit a human would have typed it in.
427fn format_duration(secs: u64) -> String {
428    match secs {
429        s if s > 0 && s % 3600 == 0 => format!("{}h", s / 3600),
430        s if s > 0 && s % 60 == 0 => format!("{}m", s / 60),
431        s => format!("{s}s"),
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn the_timeout_is_described_in_whatever_unit_fits_it() {
441        // The old line hardcoded "(10m)", so every value looked like the default.
442        assert_eq!(format_duration(600), "10m");
443        assert_eq!(format_duration(3600), "1h");
444        assert_eq!(format_duration(90), "90s");
445        assert_eq!(format_duration(0), "0s");
446    }
447}