1use std::collections::BTreeMap;
9use std::path::{Path, PathBuf};
10
11use anyhow::{Context, Result};
12
13use crate::config::{PrunedDir, Registry};
14use crate::engine;
15use crate::output;
16
17pub fn run(path_str: &str) -> Result<()> {
19 let path = Path::new(path_str)
20 .canonicalize()
21 .with_context(|| format!("Path not found: {path_str}"))?;
22
23 output::print_header("dev-prune restore");
24 output::print_info(&format!(
25 "Restoring dependencies in {}",
26 output::clean_path(&path)
27 ));
28
29 let (global_depth, timeout_secs) = crate::config::Registry::load()
34 .map(|r| (r.settings.scan_depth, r.settings.command_timeout_secs))
35 .unwrap_or((
36 crate::constants::DEFAULT_SCAN_DEPTH,
37 crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS,
38 ));
39 let timeout = std::time::Duration::from_secs(timeout_secs);
40 let results = engine::restore_project_to_depth(&path, global_depth, timeout)?;
41
42 let mut failed = 0usize;
43
44 for (adapter_name, result) in &results {
45 match result {
46 Ok(()) => {
47 output::print_success(&format!("{adapter_name}: dependencies restored"));
48 }
49 Err(e) => {
50 output::print_error(&format!("{adapter_name}: {e}"));
51 failed += 1;
52 }
53 }
54 }
55
56 if failed > 0 {
60 anyhow::bail!(
61 "{failed} of {} {} failed to restore — see the errors above",
62 results.len(),
63 output::plural(results.len(), "adapter", "adapters")
64 );
65 }
66
67 output::print_success(&format!(
68 "Restored {} {}.",
69 results.len(),
70 output::plural(results.len(), "adapter", "adapters")
71 ));
72
73 Ok(())
74}
75
76pub fn run_last_run() -> Result<()> {
87 let registry = Registry::load()?;
88
89 let Some(last) = registry.last_prune.as_ref() else {
90 anyhow::bail!(
91 "No prune pass has been recorded yet, so there is nothing to put back.\n \
92 `devp restore <path>` restores a project you name."
93 );
94 };
95
96 let total: u64 = last.dirs.iter().map(|d| d.size_freed).sum();
97
98 output::print_header("dev-prune restore --last-run");
99 output::print_info(&format!(
100 "Putting back {} {} deleted on {} ({}).",
101 last.dirs.len(),
102 output::plural(last.dirs.len(), "directory", "directories"),
103 last.at.format("%Y-%m-%d %H:%M UTC"),
104 output::format_bytes(total)
105 ));
106
107 let dropped = settle_runtimes(&last.dirs)?;
110
111 let mut by_repo: BTreeMap<PathBuf, Vec<PrunedDir>> = BTreeMap::new();
114 for dir in &last.dirs {
115 let mut dir = dir.clone();
116 if dir
117 .runtime
118 .as_deref()
119 .is_some_and(|t| dropped.iter().any(|d| d == t))
120 {
121 dir.runtime = None;
122 }
123 by_repo.entry(dir.repo_path.clone()).or_default().push(dir);
124 }
125
126 let global_depth = registry.settings.scan_depth;
127 let timeout = std::time::Duration::from_secs(registry.settings.command_timeout_secs);
128 let mut attempted = 0usize;
129 let mut failed = 0usize;
130
131 for (repo_path, deleted) in &by_repo {
132 println!();
133 output::print_info(&output::clean_path(repo_path));
134
135 if !repo_path.exists() {
138 for dir in deleted {
139 attempted += 1;
140 failed += 1;
141 output::print_error(&format!(
142 " {} ({}): the repository no longer exists at this path",
143 dir.adapter, dir.bloat_dir
144 ));
145 }
146 continue;
147 }
148
149 for (label, result) in engine::restore_deleted(repo_path, deleted, global_depth, timeout) {
150 attempted += 1;
151 match result {
152 Ok(()) => output::print_success(&format!(" {label}: restored")),
153 Err(e) => {
154 failed += 1;
155 output::print_error(&format!(" {label}: {e}"));
156 }
157 }
158 }
159 }
160
161 println!();
162 if failed > 0 {
163 anyhow::bail!(
164 "{failed} of {attempted} {} failed to restore — see the errors above",
165 output::plural(attempted, "directory", "directories")
166 );
167 }
168
169 output::print_success(&format!(
170 "Restored {attempted} {} across {} {}.",
171 output::plural(attempted, "directory", "directories"),
172 by_repo.len(),
173 output::plural(by_repo.len(), "repository", "repositories")
174 ));
175
176 Ok(())
177}
178
179#[derive(Debug, PartialEq, Eq)]
185struct RuntimePlan {
186 honoured: Vec<String>,
188 missing: Vec<String>,
191}
192
193impl RuntimePlan {
194 fn build(dirs: &[PrunedDir], available: impl Fn(&str) -> bool) -> Self {
197 let mut honoured = Vec::new();
198 let mut missing = Vec::new();
199 for tag in dirs.iter().filter_map(|d| d.runtime.as_deref()) {
200 if honoured.iter().any(|t| t == tag) || missing.iter().any(|t| t == tag) {
201 continue;
202 }
203 if available(tag) {
204 honoured.push(tag.to_string());
205 } else {
206 missing.push(tag.to_string());
207 }
208 }
209 honoured.sort();
210 missing.sort();
211 Self { honoured, missing }
212 }
213}
214
215fn settle_runtimes(dirs: &[PrunedDir]) -> Result<Vec<String>> {
223 let plan = RuntimePlan::build(dirs, crate::adapters::python_runtime_available);
224
225 for tag in &plan.honoured {
226 output::print_info(&format!(
227 "Python {tag} environments will be rebuilt on Python {tag}, as recorded."
228 ));
229 }
230 if plan.missing.is_empty() {
231 return Ok(Vec::new());
232 }
233
234 let versions = plan.missing.join(", ");
235 output::print_warning(&format!(
236 "Python {versions} {} recorded for some of these environments, but not installed \
237 here. Rebuilding them means rebuilding on whatever `python` resolves to, and \
238 pinned wheels may not exist for it.",
239 output::plural(plan.missing.len(), "was", "were"),
240 ));
241 for tag in &plan.missing {
242 output::print_info(&format!(" Install it first: uv python install {tag}"));
243 }
244
245 if !confirm_other_interpreter() {
246 anyhow::bail!(
247 "Nothing was restored. Install the recorded {} and run `devp restore \
248 --last-run` again, or answer yes to rebuild on the interpreter you have.",
249 output::plural(plan.missing.len(), "interpreter", "interpreters"),
250 );
251 }
252 Ok(plan.missing)
253}
254
255fn confirm_other_interpreter() -> bool {
260 use std::io::{IsTerminal, Write};
261 if !std::io::stdin().is_terminal() {
262 output::print_info(
263 "Not running in a terminal, so this is not being answered for you — install \
264 the recorded interpreter, or re-run this where the question can be asked.",
265 );
266 return false;
267 }
268 eprint!("Rebuild them on the interpreter you have? [y/N]: ");
269 if std::io::stderr().flush().is_err() {
270 return false;
271 }
272 let mut input = String::new();
273 if std::io::stdin().read_line(&mut input).is_err() {
274 return false;
275 }
276 matches!(input.trim().to_lowercase().as_str(), "y" | "yes")
277}
278
279#[cfg(test)]
280mod tests {
281 use super::*;
282
283 fn dir_with(runtime: Option<&str>) -> PrunedDir {
284 PrunedDir {
285 repo_path: PathBuf::from("/repo"),
286 bloat_dir: ".venv".to_string(),
287 adapter: "venv".to_string(),
288 size_freed: 1,
289 runtime: runtime.map(str::to_string),
290 }
291 }
292
293 #[test]
294 fn a_recorded_interpreter_that_is_installed_is_used_without_asking() {
295 let dirs = [dir_with(Some("3.12")), dir_with(None)];
296 let plan = RuntimePlan::build(&dirs, |_| true);
297 assert_eq!(plan.honoured, vec!["3.12".to_string()]);
298 assert!(plan.missing.is_empty(), "nothing to ask about");
299 }
300
301 #[test]
302 fn each_version_is_probed_once_however_many_directories_recorded_it() {
303 let dirs: Vec<PrunedDir> = (0..40).map(|_| dir_with(Some("3.12"))).collect();
305 let probes = std::cell::Cell::new(0);
306 let plan = RuntimePlan::build(&dirs, |_| {
307 probes.set(probes.get() + 1);
308 true
309 });
310 assert_eq!(probes.get(), 1);
311 assert_eq!(plan.honoured.len(), 1);
312 }
313
314 #[test]
315 fn an_interpreter_this_machine_does_not_have_is_what_gets_asked_about() {
316 let dirs = [dir_with(Some("3.12")), dir_with(Some("3.9"))];
317 let plan = RuntimePlan::build(&dirs, |tag| tag == "3.12");
318 assert_eq!(plan.honoured, vec!["3.12".to_string()]);
319 assert_eq!(plan.missing, vec!["3.9".to_string()]);
320 }
321
322 #[test]
323 fn a_pass_that_recorded_nothing_asks_nothing() {
324 let dirs = [dir_with(None), dir_with(None)];
327 let plan = RuntimePlan::build(&dirs, |_| unreachable!("nothing to probe"));
328 assert!(plan.honoured.is_empty() && plan.missing.is_empty());
329 }
330}