Skip to main content

dev_prune/commands/
restore.rs

1// Copyright 2026 VKrishna04
2// SPDX-License-Identifier: Apache-2.0
3
4// Handler for the `dev-prune restore` command.
5//
6// Detects package managers in a project and restores dependencies from lockfiles.
7
8use 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
17/// Run the `restore` command.
18pub 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    // Read through the user's configured depth and timeout, not the built-in defaults:
30    // a repository pruned at a deeper setting has to be restored at that same setting,
31    // and a reinstall is the longest command this tool runs — the raised
32    // `command_timeout_secs` was almost certainly raised *for* it.
33    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    // A restore that failed has to exit non-zero. `devp prune && devp restore` in a
57    // script, or a CI step that runs it, otherwise carries on against a project whose
58    // dependencies are half installed — the one situation the exit code exists for.
59    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
76/// Run `restore --last-run`: put back exactly what the most recent prune pass deleted.
77///
78/// The undo the tool did not have. `devp undo` reverses an `init` or a `link`, which are
79/// registry edits; the thing people actually want reversed is the pass that emptied
80/// twelve directories across four repositories a minute ago, and reconstructing that list
81/// by hand means remembering which repositories were even in it.
82///
83/// The record is not cleared afterwards. Restoring twice is harmless — the second pass is
84/// each manager's own no-op — and a `--last-run` that could only be used once would fail
85/// exactly when a partial restore made the user want to re-run it.
86pub 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    // Settled once, before anything is rebuilt: asking per directory would put the same
108    // question in front of the user forty times in a pass that touched forty projects.
109    let dropped = settle_runtimes(&last.dirs)?;
110
111    // Grouped by repository so each tree is walked once, in a stable order, however the
112    // pass that recorded them happened to interleave.
113    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        // A repository that is gone is reported per directory, not skipped, so the count
136        // at the end still adds up to what the prune took.
137        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/// What a `--last-run` restore intends to do about the interpreters it recorded.
180///
181/// Split out from the command so the decision is testable without a terminal: the
182/// question of *whether* to ask is a pure function of what was recorded and what is
183/// installed, and only the asking needs stdin.
184#[derive(Debug, PartialEq, Eq)]
185struct RuntimePlan {
186    /// Recorded versions this machine has, which will be used as recorded.
187    honoured: Vec<String>,
188    /// Recorded versions this machine does not have. Rebuilding those directories means
189    /// rebuilding them on a different interpreter, which is the thing worth asking about.
190    missing: Vec<String>,
191}
192
193impl RuntimePlan {
194    /// `available` is asked once per distinct version rather than once per directory —
195    /// a prune of forty Python projects would otherwise spawn forty identical probes.
196    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
215/// Decide, and say out loud, which interpreter each recorded directory is rebuilt on.
216///
217/// Returns the versions to drop — the ones this machine cannot provide and the user has
218/// agreed to rebuild on whatever `python` is. Bails instead when they say no, because a
219/// restore onto the wrong interpreter is not something to do by default: it is the
220/// failure this recording exists to prevent, and it surfaces much later as an import
221/// error nobody connects back to here.
222fn 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
255/// Default no. Everything else this command does puts back exactly what was taken; this
256/// is the one step that knowingly puts back something slightly different, so a reflexive
257/// Enter should not be what agrees to it. The question goes to stderr so a piped stdout
258/// cannot eat it.
259fn 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        // Forty Python projects in one pass must not mean forty identical probes.
304        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        // Everything pruned before 1.4.0 lands here, and so does a pass that only
325        // touched node_modules. Neither should produce a question.
326        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}