1use 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
21pub struct ProjectDrift {
24 pub repository: std::path::PathBuf,
26 pub project: String,
28 pub adapter: &'static str,
30 pub report: DriftReport,
32}
33
34pub 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 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(®istry);
74 return crate::json::emit(&crate::json::status_document(
75 ®istry, &repos, &daemon_st, &hook_st, top,
76 ));
77 }
78
79 output::print_banner();
80
81 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 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(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 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 let repos = engine::take_top(&engine::get_full_status(®istry), top);
138
139 if io::stdout().is_terminal() {
140 let registry_ref = ®istry;
144 match status_view::render_status_tui(&|| {
145 engine::take_top(&engine::get_full_status(registry_ref), top)
146 }) {
147 Ok(Some(candidates)) if !candidates.is_empty() => {
148 output::print_header("Pruning Selected Repositories");
152
153 let mut total_freed: u64 = 0;
154 let mut pruned_count = 0;
155 let mut error_count = 0;
156 let mut pruned_dirs: Vec<crate::config::PrunedDir> = Vec::new();
160 let pass_at = chrono::Utc::now();
161
162 let opts = engine::PruneOptions {
168 idle_days: 0,
169 dry_run: false,
170 force: true,
171 only_dirs: None,
172 adapters: engine::AdapterFilter::default(),
173 min_size_bytes: registry
174 .settings
175 .min_size_mb
176 .saturating_mul(engine::BYTES_PER_MIB),
177 scan_depth: registry.settings.scan_depth,
178 allow_manifest_rewrite: registry.settings.allow_manifest_rewrite,
179 command_timeout_secs: registry.settings.command_timeout_secs,
180 };
181
182 for path in &candidates {
183 let recorded_before = pruned_dirs.len();
184 let results = engine::prune_repo_with(path, &opts);
185 for result in results {
186 match &result.status {
187 PruneStatus::Pruned => {
188 total_freed += result.size_freed;
189 pruned_count += 1;
190 registry.mark_pruned(&result.repo_path, result.size_freed);
191 pruned_dirs.push(crate::config::PrunedDir {
192 repo_path: result.repo_path.clone(),
193 bloat_dir: result.bloat_dir.clone(),
194 adapter: result.adapter_name.clone(),
195 size_freed: result.size_freed,
196 });
197 output::print_success(&format!(
198 "{} → {} ({}) — {}",
199 output::clean_path(&result.repo_path),
200 result.bloat_dir,
201 output::format_bytes(result.size_freed),
202 result.adapter_name,
203 ));
204 }
205 PruneStatus::LockfileError(e) => {
206 error_count += 1;
207 output::print_error(&format!(
208 "{} lockfile sync failed: {}",
209 output::clean_path(&result.repo_path),
210 e,
211 ));
212 }
213 PruneStatus::DeleteError(e) => {
214 error_count += 1;
215 if result.size_freed > 0 {
220 pruned_dirs.push(crate::config::PrunedDir {
221 repo_path: result.repo_path.clone(),
222 bloat_dir: result.bloat_dir.clone(),
223 adapter: result.adapter_name.clone(),
224 size_freed: result.size_freed,
225 });
226 }
227 output::print_error(&format!(
228 "{} delete failed: {}",
229 output::clean_path(&result.repo_path),
230 e,
231 ));
232 }
233 PruneStatus::ConfigError(e) => {
234 error_count += 1;
235 output::print_error(&format!(
236 "{} skipped — unreadable .devprune.json: {}",
237 output::clean_path(&result.repo_path),
238 e,
239 ));
240 }
241 PruneStatus::SkippedSymlink(e) => {
244 output::print_warning(&format!(
245 "{} → {}",
246 output::clean_path(&result.repo_path),
247 e.trim(),
248 ));
249 }
250 _ => {}
251 }
252 }
253
254 if pruned_dirs.len() > recorded_before {
259 registry.record_prune_progress(pass_at, pruned_dirs.clone());
260 let _ = registry.save();
261 }
262 }
263
264 registry.record_prune_progress(pass_at, pruned_dirs);
265 registry.save()?;
266
267 output::print_header("Summary");
268 output::print_success(&format!(
269 "Freed: {} across {pruned_count} directories",
270 output::format_bytes(total_freed)
271 ));
272 if error_count > 0 {
275 anyhow::bail!("{error_count} directories could not be pruned.");
276 }
277 }
278 Ok(_) => {
279 }
281 Err(e) => {
282 output::print_warning(&format!("Interactive view ended: {e:#}"));
286 status_view::render_status_plain(&repos);
287 }
288 }
289 } else {
290 status_view::render_status_plain(&repos);
292 }
293
294 Ok(())
295}
296
297fn run_drift(json_output: bool) -> Result<()> {
305 let registry = Registry::load()?;
306
307 let pb = (!json_output)
308 .then(|| output::create_spinner("Comparing environments against lockfiles..."));
309
310 let mut findings: Vec<ProjectDrift> = Vec::new();
311 for path in registry.repositories.keys() {
312 if !path.exists() {
313 continue;
314 }
315 let depth = workspace::resolve_depth(path, registry.settings.scan_depth);
316 for project in workspace::discover_to_depth(path, depth) {
317 for adapter in &project.adapters {
318 for report in adapter.drift(&project.path) {
319 findings.push(ProjectDrift {
320 repository: path.clone(),
321 project: project.relative.clone(),
322 adapter: adapter.name(),
323 report,
324 });
325 }
326 }
327 }
328 }
329 findings.sort_by(|a, b| {
332 (&a.repository, &a.project, a.adapter, &a.report.directory).cmp(&(
333 &b.repository,
334 &b.project,
335 b.adapter,
336 &b.report.directory,
337 ))
338 });
339
340 if let Some(pb) = pb {
341 pb.finish_and_clear();
342 }
343
344 if json_output {
345 return crate::json::emit(&crate::json::drift_document(&findings));
346 }
347
348 output::print_header("Lockfile drift");
349 println!();
350
351 if findings.is_empty() {
352 output::print_success(
353 "No drift found: nothing is installed that the lockfiles do not record.",
354 );
355 output::print_info(
356 "Checked where a cheap file-level comparison exists: node_modules against \
357 package-lock.json (npm), .venv against uv.lock (uv), and every virtual \
358 environment against requirements.txt (venv).",
359 );
360 return Ok(());
361 }
362
363 let mut last_repo: Option<&std::path::Path> = None;
364 for f in &findings {
365 if last_repo != Some(f.repository.as_path()) {
366 println!(" {}", output::clean_path(&f.repository));
367 last_repo = Some(f.repository.as_path());
368 }
369 let location = if f.project == "." {
370 f.report.directory.clone()
371 } else {
372 format!("{}/{}", f.project, f.report.directory)
373 };
374 let shown = f
375 .report
376 .unrecorded
377 .iter()
378 .take(10)
379 .map(String::as_str)
380 .collect::<Vec<_>>()
381 .join(", ");
382 let suffix = if f.report.unrecorded.len() > 10 {
383 format!(", … and {} more", f.report.unrecorded.len() - 10)
384 } else {
385 String::new()
386 };
387 println!(
388 " {} ({}): {} unrecorded {} — {shown}{suffix}",
389 location,
390 f.adapter,
391 f.report.unrecorded.len(),
392 output::plural(f.report.unrecorded.len(), "package", "packages"),
393 );
394 println!(" record them: {}", f.report.record_command);
395 println!();
396 }
397
398 output::print_info(
399 "A prune refuses to delete these environments as they are — the unrecorded \
400 packages would be lost with no way back. Record them with the command shown, \
401 or uninstall them, and the refusal goes away.",
402 );
403 Ok(())
404}
405
406fn format_duration(secs: u64) -> String {
408 match secs {
409 s if s > 0 && s % 3600 == 0 => format!("{}h", s / 3600),
410 s if s > 0 && s % 60 == 0 => format!("{}m", s / 60),
411 s => format!("{s}s"),
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 #[test]
420 fn the_timeout_is_described_in_whatever_unit_fits_it() {
421 assert_eq!(format_duration(600), "10m");
423 assert_eq!(format_duration(3600), "1h");
424 assert_eq!(format_duration(90), "90s");
425 assert_eq!(format_duration(0), "0s");
426 }
427}