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