Skip to main content

uv_python_commands/
uninstall.rs

1use std::collections::BTreeSet;
2use std::fmt::Write;
3use std::io;
4use std::path::PathBuf;
5
6use anyhow::Result;
7use futures::StreamExt;
8use futures::stream::FuturesUnordered;
9use indexmap::IndexSet;
10use itertools::Itertools;
11use owo_colors::OwoColorize;
12use rustc_hash::{FxHashMap, FxHashSet};
13use tracing::{debug, warn};
14
15use uv_command_support::Printer;
16use uv_command_support::{ExitStatus, elapsed};
17use uv_fs::Simplified;
18use uv_python_managed::{
19    ManagedPythonInstallation, ManagedPythonInstallations, PythonMinorVersionLink,
20    python_executable_dir,
21};
22use uv_python_types::{
23    PythonDownloadRequest, PythonInstallationKey, PythonInstallationMinorVersionKey, PythonRequest,
24};
25
26use crate::install::format_executables;
27use crate::{ChangeEvent, ChangeEventKind};
28
29#[derive(Debug, thiserror::Error)]
30#[error("Failed to remove symlink directory `{}`", path.display())]
31struct MinorVersionLinkRemovalError {
32    path: PathBuf,
33    #[source]
34    source: io::Error,
35}
36
37/// Uninstall managed Python versions.
38pub async fn uninstall(
39    install_dir: Option<PathBuf>,
40    targets: Vec<String>,
41    all: bool,
42    printer: Printer,
43) -> Result<ExitStatus> {
44    let installations = ManagedPythonInstallations::from_settings(install_dir)?.init()?;
45
46    let _lock = installations.lock().await?;
47
48    // Perform the uninstallation.
49    do_uninstall(&installations, targets, all, printer).await?;
50
51    // Clean up any empty directories.
52    if uv_fs::directories(installations.root())?.all(|path| uv_fs::is_temporary(&path)) {
53        fs_err::tokio::remove_dir_all(&installations.root()).await?;
54
55        if let Some(top_level) = installations.root().parent() {
56            // Remove the `toolchains` symlink.
57            match fs_err::tokio::remove_file(top_level.join("toolchains")).await {
58                Ok(()) => {}
59                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
60                Err(err) => return Err(err.into()),
61            }
62
63            // Best-effort cleanup: the parent may contain user files or be in use.
64            if let Err(err) = fs_err::tokio::remove_dir(top_level).await {
65                debug!(
66                    "Skipping removal of parent directory `{}`: {err}",
67                    top_level.user_display()
68                );
69            }
70        }
71    }
72
73    Ok(ExitStatus::Success)
74}
75
76/// Perform the uninstallation of managed Python installations.
77async fn do_uninstall(
78    installations: &ManagedPythonInstallations,
79    targets: Vec<String>,
80    all: bool,
81    printer: Printer,
82) -> Result<ExitStatus> {
83    let start = std::time::Instant::now();
84
85    let requests = if all {
86        vec![PythonRequest::Default]
87    } else {
88        let targets = targets.into_iter().collect::<BTreeSet<_>>();
89        targets
90            .iter()
91            .map(|target| PythonRequest::parse(target.as_str()))
92            .collect::<Vec<_>>()
93    };
94
95    let download_requests = requests
96        .iter()
97        .map(|request| {
98            PythonDownloadRequest::from_request(request).ok_or_else(|| {
99                anyhow::anyhow!("Cannot uninstall managed Python for request: {request}")
100            })
101        })
102        // Always include pre-releases in uninstalls
103        .map(|result| result.map(|request| request.with_prereleases(true)))
104        .collect::<Result<Vec<_>>>()?;
105    let installed_installations: Vec<_> = installations.find_all()?.collect();
106    let mut matching_installations = BTreeSet::default();
107    for (request, download_request) in requests.iter().zip(download_requests) {
108        if matches!(requests.as_slice(), [PythonRequest::Default]) {
109            writeln!(printer.stderr(), "Searching for Python installations")?;
110        } else {
111            writeln!(
112                printer.stderr(),
113                "Searching for Python versions matching: {}",
114                request.cyan()
115            )?;
116        }
117        let mut found = false;
118        for installation in installed_installations
119            .iter()
120            .filter(|installation| download_request.satisfied_by_key(installation.key()))
121        {
122            found = true;
123            matching_installations.insert(installation.clone());
124        }
125        if !found {
126            // Clear any remnants in the registry
127            #[cfg(windows)]
128            {
129                uv_python_managed::windows_registry::remove_orphan_registry_entries(
130                    &installed_installations,
131                );
132            }
133
134            if matches!(requests.as_slice(), [PythonRequest::Default]) {
135                writeln!(printer.stderr(), "No Python installations found")?;
136                return Ok(ExitStatus::Failure);
137            }
138
139            writeln!(
140                printer.stderr(),
141                "No existing installations found for: {}",
142                request.cyan()
143            )?;
144        }
145    }
146
147    if matching_installations.is_empty() {
148        writeln!(
149            printer.stderr(),
150            "No Python installations found matching the requests"
151        )?;
152        return Ok(ExitStatus::Failure);
153    }
154
155    // Remove registry entries first, so we don't have dangling entries between the file removal
156    // and the registry removal.
157    let mut errors = vec![];
158    #[cfg(windows)]
159    {
160        uv_python_managed::windows_registry::remove_registry_entry(
161            &matching_installations,
162            all,
163            &mut errors,
164        );
165        uv_python_managed::windows_registry::remove_orphan_registry_entries(
166            &installed_installations,
167        );
168    }
169
170    // Find and remove all relevant Python executables
171    let mut uninstalled_executables: FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>> =
172        FxHashMap::default();
173    for executable in python_executable_dir()?
174        .read_dir()
175        .into_iter()
176        .flatten()
177        .filter_map(|entry| match entry {
178            Ok(entry) => Some(entry),
179            Err(err) => {
180                warn!("Failed to read executable: {}", err);
181                None
182            }
183        })
184        .filter(|entry| entry.file_type().is_ok_and(|file_type| !file_type.is_dir()))
185        .map(|entry| entry.path())
186        // Only include files that match the expected Python executable names
187        // TODO(zanieb): This is a minor optimization to avoid opening more files, but we could
188        // leave broken links behind, i.e., if the user created them.
189        .filter(|path| {
190            matching_installations.iter().any(|installation| {
191                let name = path.file_name().and_then(|name| name.to_str());
192                name == Some(&installation.key().executable_name_minor())
193                    || name == Some(&installation.key().executable_name_major())
194                    || name == Some(&installation.key().executable_name())
195            })
196        })
197        .sorted()
198    {
199        let Some(installation) = matching_installations
200            .iter()
201            .find(|installation| installation.is_bin_link(executable.as_path()))
202        else {
203            continue;
204        };
205
206        fs_err::remove_file(&executable)?;
207        debug!(
208            "Removed `{}` for `{}`",
209            executable.simplified_display(),
210            installation.key()
211        );
212        uninstalled_executables
213            .entry(installation.key().clone())
214            .or_default()
215            .insert(executable);
216    }
217
218    let mut tasks = FuturesUnordered::new();
219    for installation in &matching_installations {
220        tasks.push(async {
221            (
222                installation.key(),
223                fs_err::tokio::remove_dir_all(installation.path()).await,
224            )
225        });
226    }
227
228    let mut uninstalled = IndexSet::<PythonInstallationKey>::default();
229    while let Some((key, result)) = tasks.next().await {
230        if let Err(err) = result {
231            errors.push((key.clone(), anyhow::Error::new(err)));
232        } else {
233            uninstalled.insert(key.clone());
234        }
235    }
236
237    // Read all existing managed installations and find the highest installed patch
238    // for each installed minor version. Ensure the minor version link directory
239    // is still valid.
240    let uninstalled_minor_versions: IndexSet<_> = uninstalled
241        .iter()
242        .map(PythonInstallationMinorVersionKey::ref_cast)
243        .collect();
244    let remaining_installations: Vec<_> = installed_installations
245        .into_iter()
246        .filter(|installation| !uninstalled.contains(installation.key()))
247        .collect();
248
249    let remaining_minor_versions =
250        ManagedPythonInstallation::highest_by_minor_version_key(remaining_installations.iter());
251
252    for (_, installation) in remaining_minor_versions
253        .iter()
254        .filter(|(minor_version, _)| uninstalled_minor_versions.contains(minor_version))
255    {
256        installation.ensure_minor_version_link().await?;
257    }
258    // For each uninstalled installation, check if there are no remaining installations
259    // for its minor version. If there are none remaining, remove the symlink directory
260    // (or junction on Windows) if it exists.
261    for installation in &matching_installations {
262        if !remaining_minor_versions.contains_key(installation.minor_version_key()) {
263            if let Some(minor_version_link) =
264                PythonMinorVersionLink::from_installation(installation)
265            {
266                if minor_version_link.exists() {
267                    uv_fs::remove_symlink(&minor_version_link.symlink_directory).map_err(
268                        |source| MinorVersionLinkRemovalError {
269                            path: minor_version_link.symlink_directory.clone(),
270                            source,
271                        },
272                    )?;
273                    let symlink_term = if cfg!(windows) {
274                        "junction"
275                    } else {
276                        "symlink directory"
277                    };
278                    debug!(
279                        "Removed {}: {}",
280                        symlink_term,
281                        minor_version_link.symlink_directory.to_string_lossy()
282                    );
283                }
284            }
285        }
286    }
287
288    // Report on any uninstalled installations.
289    if let Some(first_uninstalled) = uninstalled.first() {
290        if uninstalled.len() == 1 {
291            // Ex) "Uninstalled Python 3.9.7 in 1.68s"
292            writeln!(
293                printer.stderr(),
294                "{}",
295                format!(
296                    "Uninstalled {} {}",
297                    format!("Python {}", first_uninstalled.version()).bold(),
298                    format!("in {}", elapsed(start.elapsed())).dimmed()
299                )
300                .dimmed()
301            )?;
302        } else {
303            // Ex) "Uninstalled 2 versions in 1.68s"
304            writeln!(
305                printer.stderr(),
306                "{}",
307                format!(
308                    "Uninstalled {} {}",
309                    format!("{} versions", uninstalled.len()).bold(),
310                    format!("in {}", elapsed(start.elapsed())).dimmed()
311                )
312                .dimmed()
313            )?;
314        }
315
316        for event in uninstalled
317            .into_iter()
318            .map(|key| ChangeEvent {
319                key,
320                kind: ChangeEventKind::Removed,
321            })
322            .sorted_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.kind.cmp(&b.kind)))
323        {
324            let executables = format_executables(&event, &uninstalled_executables);
325            match event.kind {
326                ChangeEventKind::Removed => {
327                    writeln!(
328                        printer.stderr(),
329                        " {} {}{}",
330                        "-".red(),
331                        event.key.bold(),
332                        executables,
333                    )?;
334                }
335                _ => unreachable!(),
336            }
337        }
338    }
339
340    if !errors.is_empty() {
341        for (key, err) in errors {
342            writeln!(
343                printer.stderr(),
344                "Failed to uninstall {}: {}",
345                key.green(),
346                err.to_string().trim()
347            )?;
348        }
349        return Ok(ExitStatus::Failure);
350    }
351
352    Ok(ExitStatus::Success)
353}