Skip to main content

dev_prune/commands/
stats.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Handler for `dev-prune stats`.
5//
6// `devp status` answers "what could I reclaim right now"; this answers "what has this
7// thing actually done for me". They are different questions, and folding the second into
8// the dashboard would have meant a screen of history above the list people open it for.
9//
10// Two of the three sections here are only recorded from 1.1.0 onward, because the
11// per-repository total and the pass history did not exist before it. The report says so
12// rather than letting an upgraded machine look like it has never pruned anything.
13
14use anyhow::Result;
15use chrono::{DateTime, Utc};
16
17use crate::config::Registry;
18use crate::constants::HISTORY_STARTS_AT;
19use crate::output;
20
21/// How many passes the text report lists. The registry keeps more; a screen holds fewer.
22const PASSES_SHOWN: usize = 10;
23
24/// How many repositories the text report ranks.
25const REPOS_SHOWN: usize = 10;
26
27/// Run the `stats` command.
28pub fn run(json_output: bool) -> Result<()> {
29    let registry = Registry::load()?;
30
31    if json_output {
32        return crate::json::emit(&crate::json::stats_document(&registry));
33    }
34
35    output::print_header("Lifetime");
36    output::print_info(&format!(
37        "Space reclaimed:   {}",
38        output::format_bytes_styled(registry.total_freed_bytes)
39    ));
40    output::print_info(&format!(
41        "Prune passes:      {}",
42        registry.total_pruned_count
43    ));
44    output::print_info(&format!(
45        "Repositories:      {} tracked",
46        registry.repo_count()
47    ));
48
49    print_last_pass(&registry);
50    print_recent_passes(&registry);
51    print_biggest_repositories(&registry);
52
53    Ok(())
54}
55
56/// The pass `devp restore --last-run` would undo.
57fn print_last_pass(registry: &Registry) {
58    output::print_header("Most recent pass");
59
60    let Some(last) = &registry.last_prune else {
61        output::print_info(
62            "Nothing recorded yet — `devp run --dry-run` shows what a pass would do.",
63        );
64        return;
65    };
66
67    let bytes: u64 = last.dirs.iter().map(|d| d.size_freed).sum();
68    output::print_info(&format!(
69        "{} ({}) — {} from {} {}",
70        last.at.format("%Y-%m-%d %H:%M UTC"),
71        describe_age(last.at),
72        output::format_bytes_styled(bytes),
73        last.dirs.len(),
74        output::plural(last.dirs.len(), "directory", "directories"),
75    ));
76    output::print_info("Put it back with: devp restore --last-run");
77}
78
79fn print_recent_passes(registry: &Registry) {
80    if registry.prune_history.is_empty() {
81        return;
82    }
83
84    output::print_header("Recent passes");
85    for summary in registry.prune_history.iter().rev().take(PASSES_SHOWN) {
86        use colored::Colorize;
87        // Pad before coloring: a `{:>10}` applied to a string carrying ANSI escapes
88        // counts the escapes as width and the column drifts.
89        println!(
90            "  {}   {}   {} {} across {} {}",
91            summary.at.format("%Y-%m-%d %H:%M"),
92            format!("{:>10}", output::format_bytes(summary.bytes_freed)).green(),
93            summary.dirs_removed,
94            output::plural(summary.dirs_removed, "directory", "directories"),
95            summary.repos_touched,
96            output::plural(summary.repos_touched, "repository", "repositories"),
97        );
98    }
99
100    let total = registry.prune_history.len();
101    if total > PASSES_SHOWN {
102        output::print_info(&format!(
103            "{total} passes recorded; showing the last {PASSES_SHOWN}."
104        ));
105    }
106}
107
108fn print_biggest_repositories(registry: &Registry) {
109    let mut ranked: Vec<_> = registry
110        .repositories
111        .iter()
112        .filter(|(_, entry)| entry.total_freed_bytes > 0)
113        .collect();
114
115    output::print_header("Biggest reclaims");
116
117    if ranked.is_empty() {
118        // The distinction matters on an upgraded machine: `total_freed_bytes` above can
119        // be gigabytes while every per-repository figure is still zero, and reading that
120        // as "nothing was ever pruned here" would be wrong.
121        output::print_info(&format!(
122            "No per-repository figures yet — these are recorded from {HISTORY_STARTS_AT} onward."
123        ));
124        return;
125    }
126
127    ranked.sort_by(|a, b| {
128        b.1.total_freed_bytes
129            .cmp(&a.1.total_freed_bytes)
130            .then_with(|| a.0.cmp(b.0))
131    });
132
133    for (path, entry) in ranked.iter().take(REPOS_SHOWN) {
134        use colored::Colorize;
135        let last = entry
136            .last_pruned_at
137            .map(|at| format!("last pruned {}", describe_age(at)))
138            .unwrap_or_else(|| "never pruned by this install".to_string());
139        println!(
140            "  {}   {}   ({last})",
141            format!("{:>10}", output::format_bytes(entry.total_freed_bytes)).green(),
142            output::styled_path(path),
143        );
144    }
145}
146
147/// "3 days ago", in the coarsest unit that is not a lie.
148fn describe_age(at: DateTime<Utc>) -> String {
149    let elapsed = Utc::now().signed_duration_since(at);
150    let days = elapsed.num_days();
151    if days >= 1 {
152        return format!(
153            "{days} {} ago",
154            output::plural(days as usize, "day", "days")
155        );
156    }
157    let hours = elapsed.num_hours();
158    if hours >= 1 {
159        return format!(
160            "{hours} {} ago",
161            output::plural(hours as usize, "hour", "hours")
162        );
163    }
164    let minutes = elapsed.num_minutes().max(0);
165    format!(
166        "{minutes} {} ago",
167        output::plural(minutes as usize, "minute", "minutes")
168    )
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174    use chrono::Duration;
175
176    #[test]
177    fn an_age_is_described_in_the_coarsest_unit_that_fits() {
178        assert_eq!(describe_age(Utc::now() - Duration::days(3)), "3 days ago");
179        assert_eq!(describe_age(Utc::now() - Duration::days(1)), "1 day ago");
180        assert_eq!(describe_age(Utc::now() - Duration::hours(5)), "5 hours ago");
181        assert_eq!(
182            describe_age(Utc::now() - Duration::minutes(2)),
183            "2 minutes ago"
184        );
185    }
186
187    #[test]
188    fn a_timestamp_in_the_future_does_not_render_as_negative() {
189        // Clock skew between the daemon and an interactive run is real, and
190        // "-1 minutes ago" is worse than rounding it to now.
191        assert_eq!(
192            describe_age(Utc::now() + Duration::minutes(5)),
193            "0 minutes ago"
194        );
195    }
196}