Skip to main content

uv_python_commands/
install.rs

1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::fmt::Write;
4use std::io::ErrorKind;
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Error, Result};
8use futures::{StreamExt, join};
9use indexmap::IndexSet;
10use itertools::Itertools;
11use owo_colors::{AnsiColors, OwoColorize};
12use rustc_hash::{FxHashMap, FxHashSet};
13use tokio::sync::mpsc;
14use tracing::{debug, trace, warn};
15
16use uv_cache::Cache;
17use uv_client::BaseClientBuilder;
18use uv_configuration::{Concurrency, PythonUpgrade, PythonUpgradeSource};
19use uv_errors::{ErrorOptions, Hints, write_error_chain_with_options};
20use uv_fs::Simplified;
21use uv_platform::{Arch, Libc};
22use uv_preview::{Preview, PreviewFeature};
23use uv_python_discovery::ConfigDiscovery;
24use uv_python_discovery::PythonVersionFile;
25use uv_python_discovery::VersionFileDiscoveryOptions;
26use uv_python_discovery::VersionFilePreference;
27use uv_python_interpreter::Interpreter;
28use uv_python_managed::downloads::{
29    self, DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList,
30};
31use uv_python_managed::{
32    ManagedPythonInstallation, ManagedPythonInstallations, PythonExecutable,
33    PythonMinorVersionLink, compare_build_versions, create_link_to_executable,
34    python_executable_dir,
35};
36use uv_python_types::{
37    ArchRequest, ImplementationName, PythonArchitecture, PythonDownloadRequest, PythonDownloads,
38    PythonInstallationKey, PythonRequest, VersionRequest,
39};
40use uv_settings::PythonInstallMirrors;
41use uv_shell::Shell;
42use uv_trampoline_builder::{Launcher, LauncherKind};
43use uv_warnings::warn_user;
44
45use crate::{ChangeEvent, ChangeEventKind};
46use uv_command_support::{ExitStatus, Printer, UvError, conjunction, elapsed};
47use uv_python_discovery::PythonDownloadReporter;
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50struct InstallRequest<'a> {
51    /// The original request from the user
52    request: PythonRequest,
53    /// A download request corresponding to the `request` with platform information filled
54    download_request: PythonDownloadRequest,
55    /// A download that satisfies the request
56    download: &'a ManagedPythonDownload,
57}
58
59impl<'a> InstallRequest<'a> {
60    fn new(
61        request: PythonRequest,
62        arch: Option<PythonArchitecture>,
63        download_list: &'a ManagedPythonDownloadList,
64    ) -> Result<Self> {
65        // Make sure the request is a valid download request and fill platform information
66        let download_request = PythonDownloadRequest::from_request(&request)
67            .ok_or_else(|| {
68                anyhow::anyhow!(
69                    "`{}` is not a valid Python download request; see `uv help python` for supported formats and `uv python list --only-downloads` for available versions",
70                    request.to_canonical_string()
71                )
72            })?
73            .with_default_arch(arch.map(PythonArchitecture::into_inner))
74            .fill()?;
75
76        // Find a matching download
77        let download = match download_list.find(&download_request) {
78            Ok(download) => download,
79            Err(downloads::Error::NoDownloadFound(request))
80                if request.libc().is_some_and(Libc::is_musl)
81                    && request.arch().is_some_and(|arch| {
82                        arch.inner() == Arch::from(&uv_platform_tags::Arch::Armv7L)
83                    }) =>
84            {
85                return Err(anyhow::anyhow!(
86                    "uv does not yet provide musl Python distributions on armv7."
87                ));
88            }
89            Err(err) => return Err(err.into()),
90        };
91
92        Ok(Self {
93            request,
94            download_request,
95            download,
96        })
97    }
98
99    fn matches_installation(&self, installation: &ManagedPythonInstallation) -> bool {
100        self.download_request.satisfied_by_key(installation.key())
101    }
102
103    fn python_request(&self) -> &PythonRequest {
104        &self.request
105    }
106}
107
108impl std::fmt::Display for InstallRequest<'_> {
109    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
110        let request = self.request.to_canonical_string();
111        let download = self.download_request.to_string();
112        if request != download {
113            write!(f, "{request} ({download})")
114        } else {
115            write!(f, "{request}")
116        }
117    }
118}
119
120#[derive(Debug, Default)]
121struct Changelog {
122    existing: FxHashSet<PythonInstallationKey>,
123    installed: FxHashSet<PythonInstallationKey>,
124    uninstalled: FxHashSet<PythonInstallationKey>,
125    installed_executables: FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>>,
126}
127
128impl Changelog {
129    fn events(&self) -> impl Iterator<Item = ChangeEvent> {
130        let reinstalled = self
131            .uninstalled
132            .intersection(&self.installed)
133            .cloned()
134            .collect::<FxHashSet<_>>();
135        let uninstalled = self.uninstalled.difference(&reinstalled).cloned();
136        let installed = self.installed.difference(&reinstalled).cloned();
137
138        uninstalled
139            .map(|key| ChangeEvent {
140                key: key.clone(),
141                kind: ChangeEventKind::Removed,
142            })
143            .chain(installed.map(|key| ChangeEvent {
144                key: key.clone(),
145                kind: ChangeEventKind::Added,
146            }))
147            .chain(reinstalled.iter().map(|key| ChangeEvent {
148                key: key.clone(),
149                kind: ChangeEventKind::Reinstalled,
150            }))
151            .sorted_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.kind.cmp(&b.kind)))
152    }
153}
154
155#[derive(Debug, Clone, Copy)]
156enum InstallErrorKind {
157    DownloadUnpack,
158    Bin,
159    #[cfg_attr(not(windows), allow(dead_code))]
160    Registry,
161}
162
163#[derive(Debug, thiserror::Error)]
164#[error("`{command}` only accepts minor versions, got: {request}")]
165pub struct InvalidUpgradeRequestError {
166    command: PythonUpgradeSource,
167    request: String,
168    from_version_file: bool,
169}
170
171impl uv_errors::Hinted for InvalidUpgradeRequestError {
172    fn hints(&self) -> Hints<'_> {
173        if self.from_version_file {
174            Hints::from(
175                "The version request came from a `.python-version` file; change the patch version in the file to upgrade instead",
176            )
177        } else {
178            Hints::none()
179        }
180    }
181}
182
183/// Download and install Python versions.
184#[expect(clippy::fn_params_excessive_bools)]
185pub async fn install(
186    project_dir: &Path,
187    install_dir: Option<PathBuf>,
188    targets: Vec<String>,
189    reinstall: bool,
190    upgrade: PythonUpgrade,
191    bin: Option<bool>,
192    registry: Option<bool>,
193    force: bool,
194    install_mirrors: PythonInstallMirrors,
195    client_builder: BaseClientBuilder<'_>,
196    default: bool,
197    python_arch: Option<PythonArchitecture>,
198    python_downloads: PythonDownloads,
199    config_discovery: ConfigDiscovery,
200    compile_bytecode: bool,
201    concurrency: &Concurrency,
202    cache: &Cache,
203    preview: Preview,
204    printer: Printer,
205) -> Result<ExitStatus> {
206    let (sender, mut receiver) = mpsc::unbounded_channel();
207    let compiler = async {
208        let mut total_files = 0;
209        let mut total_elapsed = std::time::Duration::default();
210        let mut total_skipped = 0;
211        while let Some(installation) = receiver.recv().await {
212            if let Some((files, elapsed)) =
213                compile_stdlib_bytecode(&installation, concurrency, cache)
214                    .await
215                    .with_context(|| {
216                        format!(
217                            "Failed to bytecode-compile Python standard library for: {}",
218                            installation.key()
219                        )
220                    })?
221            {
222                total_files += files;
223                total_elapsed += elapsed;
224            } else {
225                total_skipped += 1;
226            }
227        }
228        Ok::<_, anyhow::Error>((total_files, total_elapsed, total_skipped))
229    };
230
231    let installer = perform_install(
232        project_dir,
233        install_dir,
234        targets,
235        reinstall,
236        upgrade,
237        bin,
238        registry,
239        force,
240        install_mirrors,
241        client_builder,
242        cache,
243        default,
244        python_arch,
245        python_downloads,
246        config_discovery,
247        compile_bytecode.then_some(sender),
248        concurrency,
249        preview,
250        printer,
251    );
252
253    let (installer_result, compiler_result) = join!(installer, compiler);
254
255    let (total_files, total_elapsed, total_skipped) = compiler_result?;
256    if total_files > 0 {
257        let s = if total_files == 1 { "" } else { "s" };
258        writeln!(
259            printer.stderr(),
260            "{}",
261            format!(
262                "Bytecode compiled {} {}{}",
263                format!("{total_files} file{s}").bold(),
264                format!("in {}", elapsed(total_elapsed)).dimmed(),
265                if total_skipped > 0 {
266                    format!(
267                        " (skipped {total_skipped} incompatible version{})",
268                        if total_skipped == 1 { "" } else { "s" }
269                    )
270                } else {
271                    String::new()
272                }
273                .dimmed()
274            )
275            .dimmed()
276        )?;
277    } else if total_skipped > 0 {
278        writeln!(
279            printer.stderr(),
280            "{}",
281            format!("No compatible versions to bytecode compile (skipped {total_skipped})")
282                .dimmed()
283        )?;
284    }
285
286    installer_result
287}
288
289async fn perform_install(
290    project_dir: &Path,
291    install_dir: Option<PathBuf>,
292    targets: Vec<String>,
293    reinstall: bool,
294    upgrade: PythonUpgrade,
295    bin: Option<bool>,
296    registry: Option<bool>,
297    force: bool,
298    install_mirrors: PythonInstallMirrors,
299    client_builder: BaseClientBuilder<'_>,
300    cache: &Cache,
301    default: bool,
302    python_arch: Option<PythonArchitecture>,
303    python_downloads: PythonDownloads,
304    config_discovery: ConfigDiscovery,
305    bytecode_compilation_sender: Option<mpsc::UnboundedSender<ManagedPythonInstallation>>,
306    concurrency: &Concurrency,
307    preview: Preview,
308    printer: Printer,
309) -> Result<ExitStatus> {
310    let start = std::time::Instant::now();
311
312    // TODO(zanieb): We should consider marking the Python installation as the default when
313    // `--default` is used. It's not clear how this overlaps with a global Python pin, but I'd be
314    // surprised if `uv python find` returned the "newest" Python version rather than the one I just
315    // installed with the `--default` flag.
316    if default && !preview.is_enabled(PreviewFeature::PythonInstallDefault) {
317        warn_user!(
318            "The `--default` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning",
319            PreviewFeature::PythonInstallDefault
320        );
321    }
322
323    if default && targets.len() > 1 {
324        anyhow::bail!("The `--default` flag cannot be used with multiple targets");
325    }
326
327    // Read the existing installations, lock the directory for the duration
328    let installations = ManagedPythonInstallations::from_settings(install_dir.clone())?.init()?;
329    let installations_dir = installations.root();
330    let scratch_dir = installations.scratch();
331    let _lock = installations.lock().await?;
332    let existing_installations: Vec<_> = installations
333        .find_all()?
334        .inspect(|installation| trace!("Found existing installation {}", installation.key()))
335        .collect();
336
337    // Resolve the requests
338    let mut is_default_install = false;
339    let mut is_unspecified_upgrade = false;
340    let retry_policy = client_builder.retry_policy();
341    let download_list = ManagedPythonDownloadList::new(
342        &client_builder,
343        cache,
344        install_mirrors.python_downloads_json_url.as_deref(),
345    )
346    .await?;
347    // Python downloads are performing their own retries to catch stream errors, disable the
348    // default retries to avoid the middleware from performing uncontrolled retries.
349    let client = client_builder.retries(0).build()?;
350    // TODO(zanieb): We use this variable to special-case .python-version files, but it'd be nice to
351    // have generalized request source tracking instead
352    let mut is_from_python_version_file = false;
353    let requests: Vec<_> = if targets.is_empty() {
354        if matches!(
355            upgrade,
356            PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade)
357        ) {
358            is_unspecified_upgrade = true;
359            // On upgrade, derive requests for all of the existing installations
360            let mut minor_version_requests = IndexSet::<InstallRequest>::default();
361            for installation in &existing_installations {
362                let mut request = PythonDownloadRequest::from(installation);
363                // We should always have a version in the request from an existing installation
364                let version = request.take_version().unwrap();
365                // Drop the patch and prerelease parts from the request
366                request = request.with_version(version.only_minor());
367                let install_request =
368                    InstallRequest::new(PythonRequest::Key(request), python_arch, &download_list)?;
369                minor_version_requests.insert(install_request);
370            }
371            minor_version_requests.into_iter().collect::<Vec<_>>()
372        } else {
373            PythonVersionFile::discover(
374                project_dir,
375                &VersionFileDiscoveryOptions::default()
376                    .with_config_discovery(config_discovery)
377                    .with_preference(VersionFilePreference::Versions),
378            )
379            .await?
380            .inspect(|file| {
381                debug!(
382                    "Found Python version file at: {}",
383                    file.path().user_display()
384                );
385            })
386            .map(PythonVersionFile::into_versions)
387            .inspect(|_| is_from_python_version_file = true)
388            .unwrap_or_else(|| {
389                // If no version file is found and no requests were made
390                // TODO(zanieb): We should consider differentiating between a global Python version
391                // file here, allowing a request from there to enable `is_default_install`.
392                is_default_install = true;
393                vec![if reinstall {
394                    // On bare `--reinstall`, reinstall all Python versions
395                    PythonRequest::Any
396                } else {
397                    PythonRequest::Default
398                }]
399            })
400            .into_iter()
401            .map(|request| InstallRequest::new(request, python_arch, &download_list))
402            .collect::<Result<Vec<_>>>()?
403        }
404    } else {
405        targets
406            .iter()
407            .map(|target| PythonRequest::parse(target.as_str()))
408            .map(|request| InstallRequest::new(request, python_arch, &download_list))
409            .collect::<Result<Vec<_>>>()?
410    };
411
412    if requests.is_empty() {
413        match upgrade {
414            PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) => {
415                writeln!(
416                    printer.stderr(),
417                    "There are no installed versions to upgrade"
418                )?;
419            }
420            PythonUpgrade::Enabled(PythonUpgradeSource::Install) => {
421                writeln!(
422                    printer.stderr(),
423                    "No Python versions specified for upgrade; did you mean `uv python upgrade`?"
424                )?;
425            }
426            PythonUpgrade::Disabled => {}
427        }
428        return Ok(ExitStatus::Success);
429    }
430
431    let requested_minor_versions = requests
432        .iter()
433        .filter_map(|request| {
434            if let PythonRequest::Version(VersionRequest::MajorMinor(major, minor, ..)) =
435                request.python_request()
436            {
437                Some((*major, *minor))
438            } else {
439                None
440            }
441        })
442        .collect::<IndexSet<_>>();
443
444    if let PythonUpgrade::Enabled(source) = upgrade {
445        if let Some(request) = requests.iter().find(|request| {
446            request.request.includes_patch() || request.request.includes_prerelease()
447        }) {
448            return Err(UvError::user(InvalidUpgradeRequestError {
449                command: source,
450                request: request.request.to_canonical_string().into_owned(),
451                from_version_file: is_from_python_version_file,
452            })
453            .into());
454        }
455    }
456
457    // Find requests that are already satisfied
458    let mut changelog = Changelog::default();
459    let (satisfied, unsatisfied): (Vec<_>, Vec<_>) = if reinstall {
460        // In the reinstall case, we want to iterate over all matching installations instead of
461        // stopping at the first match.
462
463        let mut unsatisfied: Vec<Cow<InstallRequest>> =
464            Vec::with_capacity(existing_installations.len() + requests.len());
465
466        for request in &requests {
467            let mut matching_installations = existing_installations
468                .iter()
469                .filter(|installation| request.matches_installation(installation))
470                .peekable();
471
472            if matching_installations.peek().is_none() {
473                debug!("No installation found for request `{}`", request);
474                unsatisfied.push(Cow::Borrowed(request));
475            }
476
477            for installation in matching_installations {
478                changelog.existing.insert(installation.key().clone());
479
480                if matches!(upgrade, PythonUpgrade::Enabled(_))
481                    && !matches!(&request.request, &PythonRequest::Any)
482                {
483                    // An upgrade must reinstall the latest patch, not every matching patch.
484                    debug!("Will reinstall the latest patch for `{}`", request);
485                    unsatisfied.push(Cow::Borrowed(request));
486                    break;
487                }
488
489                // Construct an install request matching the existing installation.
490                match InstallRequest::new(
491                    PythonRequest::Key(installation.into()),
492                    python_arch,
493                    &download_list,
494                ) {
495                    Ok(request) => {
496                        debug!("Will reinstall `{}`", installation.key());
497                        unsatisfied.push(Cow::Owned(request));
498                    }
499                    Err(err) => {
500                        // This shouldn't really happen, but maybe a new version of uv dropped
501                        // support for a key we previously supported.
502                        warn_user!(
503                            "Failed to create reinstall request for existing installation `{}`: {err}",
504                            installation.key().green()
505                        );
506                    }
507                }
508            }
509        }
510        (vec![], unsatisfied)
511    } else {
512        // If we can find one existing installation that matches the request, it is satisfied
513        let mut satisfied = Vec::new();
514        let mut unsatisfied = Vec::new();
515
516        for request in &requests {
517            if matches!(upgrade, PythonUpgrade::Enabled(_)) {
518                // If this is an upgrade, the requested version is a minor version but the
519                // requested download is the highest patch for that minor version. We need to
520                // install it unless an exact match is found (including build version).
521                if let Some(installation) = existing_installations
522                    .iter()
523                    .find(|inst| request.download.key() == inst.key())
524                {
525                    if matches_build(request.download.build(), installation.build()) {
526                        debug!("Found `{}` for request `{}`", installation.key(), request);
527                        satisfied.push(installation);
528                    } else {
529                        // Key matches but build version differs - track as existing for reinstall
530                        debug!(
531                            "Build version mismatch for `{}`, will upgrade",
532                            installation.key()
533                        );
534                        changelog.existing.insert(installation.key().clone());
535                        unsatisfied.push(Cow::Borrowed(request));
536                    }
537                } else {
538                    debug!("No installation found for request `{}`", request);
539                    unsatisfied.push(Cow::Borrowed(request));
540                }
541            } else if let Some(installation) = existing_installations
542                .iter()
543                .find(|inst| request.matches_installation(inst))
544            {
545                debug!("Found `{}` for request `{}`", installation.key(), request);
546                satisfied.push(installation);
547            } else {
548                debug!("No installation found for request `{}`", request);
549                unsatisfied.push(Cow::Borrowed(request));
550            }
551        }
552
553        (satisfied, unsatisfied)
554    };
555
556    // For all satisfied installs, bytecode compile them now before any future
557    // early return.
558    if let Some(ref sender) = bytecode_compilation_sender {
559        satisfied
560            .iter()
561            .copied()
562            .cloned()
563            .try_for_each(|installation| {
564                sender
565                    .send(installation)
566                    .map_err(|err| anyhow::anyhow!(err))
567            })?;
568    }
569
570    // Check if Python downloads are banned
571    if matches!(python_downloads, PythonDownloads::Never) && !unsatisfied.is_empty() {
572        writeln!(
573            printer.stderr(),
574            "Python downloads are not allowed (`python-downloads = \"never\"`). Change to `python-downloads = \"manual\"` to allow explicit installs.",
575        )?;
576        return Ok(ExitStatus::Failure);
577    }
578
579    // Find downloads for the requests
580    let downloads = unsatisfied
581        .iter()
582        .inspect(|request| {
583            debug!(
584                "Found download `{}` for request `{}`",
585                request.download, request,
586            );
587        })
588        .map(|request| request.download)
589        // Ensure we only download each version once
590        .unique_by(|download| download.key())
591        .collect::<Vec<_>>();
592
593    // Download and unpack the Python versions concurrently
594    let reporter = PythonDownloadReporter::new(printer, Some(downloads.len() as u64));
595    let replacements = changelog.existing.clone();
596
597    let mut tasks = futures::stream::iter(&downloads)
598        .map(async |download| {
599            (
600                *download,
601                download
602                    .fetch_with_retry(
603                        &client,
604                        &retry_policy,
605                        installations_dir,
606                        &scratch_dir,
607                        reinstall || replacements.contains(download.key()),
608                        install_mirrors.mirrors(),
609                        Some(&reporter),
610                    )
611                    .await,
612            )
613        })
614        .buffer_unordered(concurrency.downloads);
615
616    let mut errors = vec![];
617    let mut downloaded = Vec::with_capacity(downloads.len());
618    let mut requests_by_new_installation = BTreeMap::new();
619    while let Some((download, result)) = tasks.next().await {
620        match result {
621            Ok(download_result) => {
622                let path = match download_result {
623                    // We should only encounter already-available during concurrent installs
624                    DownloadResult::AlreadyAvailable(path) => path,
625                    DownloadResult::Fetched(path) => path,
626                };
627
628                let installation = ManagedPythonInstallation::new(path, download)?;
629                if let Some(ref sender) = bytecode_compilation_sender {
630                    sender
631                        .send(installation.clone())
632                        .map_err(|err| anyhow::anyhow!(err))?;
633                }
634                changelog.installed.insert(installation.key().clone());
635                for request in &requests {
636                    // Take note of which installations satisfied which requests
637                    if request.matches_installation(&installation) {
638                        requests_by_new_installation
639                            .entry(installation.key().clone())
640                            .or_insert(Vec::new())
641                            .push(request);
642                    }
643                }
644                if changelog.existing.contains(installation.key()) {
645                    changelog.uninstalled.insert(installation.key().clone());
646                }
647                downloaded.push(installation.clone());
648            }
649            Err(err) => {
650                errors.push((
651                    InstallErrorKind::DownloadUnpack,
652                    download.key().clone(),
653                    anyhow::Error::new(err),
654                ));
655            }
656        }
657    }
658
659    let bin_dir = if matches!(bin, Some(false)) {
660        None
661    } else {
662        Some(python_executable_dir()?)
663    };
664
665    let installations: Vec<_> = downloaded.iter().chain(satisfied.iter().copied()).collect();
666
667    // Ensure that the installations are _complete_ for both downloaded installations and existing
668    // installations that match the request
669    for installation in &installations {
670        installation.ensure_externally_managed().await?;
671        installation.ensure_sysconfig_patched().await?;
672        installation.ensure_canonical_executables().await?;
673        installation.ensure_build_file().await?;
674        if let Err(e) = installation.ensure_dylib_patched() {
675            e.warn_user(installation);
676        }
677
678        let upgradeable = (default || is_default_install)
679            || requested_minor_versions
680                .contains(&(installation.key().major(), installation.key().minor()));
681
682        if let Some(bin_dir) = bin_dir.as_ref() {
683            create_bin_links(
684                installation,
685                bin_dir,
686                reinstall,
687                force,
688                default,
689                upgradeable,
690                matches!(
691                    upgrade,
692                    PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade)
693                ),
694                is_default_install,
695                &existing_installations,
696                &installations,
697                &mut changelog,
698                &mut errors,
699                preview,
700            );
701        }
702
703        if !matches!(registry, Some(false)) {
704            #[cfg(windows)]
705            {
706                match uv_python_managed::windows_registry::create_registry_entry(installation) {
707                    Ok(()) => {}
708                    Err(err) => {
709                        errors.push((
710                            InstallErrorKind::Registry,
711                            installation.key().clone(),
712                            err.into(),
713                        ));
714                    }
715                }
716            }
717        }
718    }
719
720    let minor_versions = ManagedPythonInstallation::highest_by_minor_version_key(
721        installations
722            .iter()
723            .copied()
724            .chain(existing_installations.iter()),
725    );
726
727    for installation in minor_versions.values() {
728        installation.ensure_minor_version_link().await?;
729    }
730
731    if changelog.installed.is_empty() && errors.is_empty() {
732        if is_default_install {
733            if matches!(
734                upgrade,
735                PythonUpgrade::Enabled(PythonUpgradeSource::Install)
736            ) {
737                writeln!(
738                    printer.stderr(),
739                    "The default Python installation is already on the latest supported patch release. Use `uv python install <request>` to install another version.",
740                )?;
741            } else {
742                writeln!(
743                    printer.stderr(),
744                    "Python is already installed. Use `uv python install <request>` to install another version.",
745                )?;
746            }
747        } else if matches!(
748            upgrade,
749            PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade)
750        ) && requests.is_empty()
751        {
752            writeln!(
753                printer.stderr(),
754                "There are no installed versions to upgrade"
755            )?;
756        } else if let [request] = requests.as_slice() {
757            // Convert to the inner request
758            let request = &request.request;
759            if is_unspecified_upgrade {
760                writeln!(
761                    printer.stderr(),
762                    "All versions already on latest supported patch release"
763                )?;
764            } else if matches!(upgrade, PythonUpgrade::Enabled(_)) {
765                writeln!(
766                    printer.stderr(),
767                    "{request} is already on the latest supported patch release"
768                )?;
769            } else {
770                writeln!(printer.stderr(), "{request} is already installed")?;
771            }
772        } else {
773            if matches!(upgrade, PythonUpgrade::Enabled(_)) {
774                if is_unspecified_upgrade {
775                    writeln!(
776                        printer.stderr(),
777                        "All versions already on latest supported patch release"
778                    )?;
779                } else {
780                    writeln!(
781                        printer.stderr(),
782                        "All requested versions already on latest supported patch release"
783                    )?;
784                }
785            } else {
786                writeln!(printer.stderr(), "All requested versions already installed")?;
787            }
788        }
789        return Ok(ExitStatus::Success);
790    }
791
792    if !changelog.installed.is_empty() {
793        for install_key in &changelog.installed {
794            // Make a note if the selected python is non-native for the architecture, if none of the
795            // matching user requests were explicit.
796            //
797            // Emscripten is exempted as it is always "emulated".
798            let native_arch = Arch::from_env();
799            if install_key.arch().family() != native_arch.family()
800                && !install_key.os().is_emscripten()
801            {
802                let not_explicit =
803                    requests_by_new_installation
804                        .get(install_key)
805                        .and_then(|requests| {
806                            let all_non_explicit = requests.iter().all(|request| {
807                                if let PythonRequest::Key(key) = &request.request {
808                                    !matches!(key.arch(), Some(ArchRequest::Explicit(_)))
809                                } else {
810                                    true
811                                }
812                            });
813                            if all_non_explicit {
814                                requests.iter().next()
815                            } else {
816                                None
817                            }
818                        });
819                if let Some(not_explicit) = not_explicit {
820                    let native_request =
821                        not_explicit.download_request.clone().with_arch(native_arch);
822                    writeln!(
823                        printer.stderr(),
824                        "{} uv selected a Python distribution with an emulated architecture ({}) for your platform ({}); to require the native architecture, use: {}",
825                        "note:".bold(),
826                        install_key.arch(),
827                        native_arch,
828                        native_request
829                    )?;
830                }
831            }
832        }
833        if changelog.installed.len() == 1 {
834            let installed = changelog.installed.iter().next().unwrap();
835            // Ex) "Installed Python 3.9.7 in 1.68s"
836            writeln!(
837                printer.stderr(),
838                "{}",
839                format!(
840                    "Installed {} {}",
841                    format!("Python {}", installed.version()).bold(),
842                    format!("in {}", elapsed(start.elapsed())).dimmed()
843                )
844                .dimmed()
845            )?;
846        } else {
847            // Ex) "Installed 2 versions in 1.68s"
848            writeln!(
849                printer.stderr(),
850                "{}",
851                format!(
852                    "Installed {} {}",
853                    format!("{} versions", changelog.installed.len()).bold(),
854                    format!("in {}", elapsed(start.elapsed())).dimmed()
855                )
856                .dimmed()
857            )?;
858        }
859
860        for event in changelog.events() {
861            let executables = format_executables(&event, &changelog.installed_executables);
862            match event.kind {
863                ChangeEventKind::Added => {
864                    writeln!(
865                        printer.stderr(),
866                        " {} {}{executables}",
867                        "+".green(),
868                        event.key.bold()
869                    )?;
870                }
871                ChangeEventKind::Removed => {
872                    writeln!(
873                        printer.stderr(),
874                        " {} {}{executables}",
875                        "-".red(),
876                        event.key.bold()
877                    )?;
878                }
879                ChangeEventKind::Reinstalled => {
880                    writeln!(
881                        printer.stderr(),
882                        " {} {}{executables}",
883                        "~".yellow(),
884                        event.key.bold(),
885                    )?;
886                }
887            }
888        }
889
890        if let Some(bin_dir) = bin_dir.as_ref() {
891            warn_if_not_on_path(bin_dir);
892        }
893    }
894
895    if !errors.is_empty() {
896        // If there are only side-effect install errors and the user didn't opt-in, we're only going
897        // to warn
898        let fatal = !errors.iter().all(|(kind, _, _)| match kind {
899            InstallErrorKind::Bin => bin.is_none(),
900            InstallErrorKind::Registry => registry.is_none(),
901            InstallErrorKind::DownloadUnpack => false,
902        });
903
904        for (kind, key, err) in errors
905            .into_iter()
906            .sorted_unstable_by(|(_, key_a, _), (_, key_b, _)| key_a.cmp(key_b))
907        {
908            match kind {
909                InstallErrorKind::DownloadUnpack => {
910                    write_error_chain_with_options(
911                        err.context(format!("Failed to install {key}")).as_ref(),
912                        &Hints::none(),
913                        ErrorOptions::default().with_stream(printer.stderr()),
914                    )?;
915                }
916                InstallErrorKind::Bin => {
917                    let (level, color) = match bin {
918                        None => ("warning", AnsiColors::Yellow),
919                        Some(false) => continue,
920                        Some(true) => ("error", AnsiColors::Red),
921                    };
922
923                    write_error_chain_with_options(
924                        err.context(format!("Failed to install executable for {key}"))
925                            .as_ref(),
926                        &Hints::none(),
927                        ErrorOptions::default()
928                            .with_level(level)
929                            .with_color(color)
930                            .with_stream(printer.stderr()),
931                    )?;
932                }
933                InstallErrorKind::Registry => {
934                    let (level, color) = match registry {
935                        None => ("warning", AnsiColors::Yellow),
936                        Some(false) => continue,
937                        Some(true) => ("error", AnsiColors::Red),
938                    };
939
940                    trace!("Error trace: {err:?}");
941                    write_error_chain_with_options(
942                        err.context(format!("Failed to create registry entry for {key}"))
943                            .as_ref(),
944                        &Hints::none(),
945                        ErrorOptions::default()
946                            .with_level(level)
947                            .with_color(color)
948                            .with_stream(printer.stderr()),
949                    )?;
950                }
951            }
952        }
953
954        if fatal {
955            return Ok(ExitStatus::Failure);
956        }
957    }
958
959    Ok(ExitStatus::Success)
960}
961
962/// Link the binaries of a managed Python installation to the bin directory.
963///
964/// This function is fallible, but errors are pushed to `errors` instead of being thrown.
965#[expect(clippy::fn_params_excessive_bools)]
966fn create_bin_links(
967    installation: &ManagedPythonInstallation,
968    bin: &Path,
969    reinstall: bool,
970    force: bool,
971    default: bool,
972    upgradeable: bool,
973    upgrade: bool,
974    is_default_install: bool,
975    existing_installations: &[ManagedPythonInstallation],
976    installations: &[&ManagedPythonInstallation],
977    changelog: &mut Changelog,
978    errors: &mut Vec<(InstallErrorKind, PythonInstallationKey, Error)>,
979    preview: Preview,
980) {
981    // TODO(zanieb): We want more feedback on the `is_default_install` behavior before stabilizing
982    // it. In particular, it may be confusing because it does not apply when versions are loaded
983    // from a `.python-version` file.
984    let should_create_default_links =
985        default || (is_default_install && preview.is_enabled(PreviewFeature::PythonInstallDefault));
986
987    let targets = if should_create_default_links {
988        vec![
989            installation.key().executable_name_minor(),
990            installation.key().executable_name_major(),
991            installation.key().executable_name(),
992        ]
993    } else {
994        vec![installation.key().executable_name_minor()]
995    };
996
997    let mut existing_unmanaged = Vec::new();
998
999    for target in targets {
1000        let target = bin.join(target);
1001        if upgrade && !target.try_exists().unwrap_or_default() {
1002            continue;
1003        }
1004        let executable = if upgradeable {
1005            if let Some(minor_version_link) =
1006                PythonMinorVersionLink::from_installation(installation)
1007            {
1008                minor_version_link.symlink_executable.clone()
1009            } else {
1010                installation.executable(false)
1011            }
1012        } else {
1013            installation.executable(false)
1014        };
1015
1016        match create_link_to_executable(&target, PythonExecutable::console(&executable)) {
1017            Ok(()) => {
1018                debug!(
1019                    "Installed executable at `{}` for {}",
1020                    target.simplified_display(),
1021                    installation.key(),
1022                );
1023                changelog.installed.insert(installation.key().clone());
1024                changelog
1025                    .installed_executables
1026                    .entry(installation.key().clone())
1027                    .or_default()
1028                    .insert(target.clone());
1029            }
1030            Err(uv_python_managed::Error::LinkExecutable(err))
1031                if err.kind() == ErrorKind::AlreadyExists =>
1032            {
1033                debug!(
1034                    "Inspecting existing executable at `{}`",
1035                    target.simplified_display()
1036                );
1037
1038                //  Figure out what installation it references, if any
1039                let existing = find_matching_bin_link(
1040                    installations
1041                        .iter()
1042                        .copied()
1043                        .chain(existing_installations.iter()),
1044                    &target,
1045                );
1046
1047                match existing {
1048                    None => {
1049                        // Determine if the link is valid, i.e., if it points to an existing
1050                        // Python we don't manage. On Windows, we just assume it is valid because
1051                        // symlinks are not common for Python interpreters.
1052                        let valid_link = cfg!(windows)
1053                            || target
1054                                .read_link()
1055                                // Resolve relative targets from the executable's directory.
1056                                .and_then(|_| target.try_exists())
1057                                .inspect_err(|err| {
1058                                    debug!("Failed to inspect executable with error: {err}");
1059                                })
1060                                // If we can't verify the link, assume it is valid.
1061                                .unwrap_or(true);
1062
1063                        // There's an existing executable we don't manage, require `--force`
1064                        if valid_link {
1065                            if !force {
1066                                if upgrade {
1067                                    warn_user!(
1068                                        "Executable already exists at `{}` but is not managed by uv; use `uv python install {}.{}{} --force` to replace it",
1069                                        target.simplified_display(),
1070                                        installation.key().major(),
1071                                        installation.key().minor(),
1072                                        installation.key().variant().display_suffix()
1073                                    );
1074                                } else {
1075                                    // Defer reporting to allow grouping.
1076                                    existing_unmanaged.push(target.clone());
1077                                }
1078                                continue;
1079                            }
1080                            debug!(
1081                                "Replacing existing executable at `{}` due to `--force`",
1082                                target.simplified_display()
1083                            );
1084                        } else {
1085                            debug!(
1086                                "Replacing broken symlink at `{}`",
1087                                target.simplified_display()
1088                            );
1089                        }
1090                    }
1091                    Some(existing) if existing == installation => {
1092                        // The existing link points to the same installation, so we're done unless
1093                        // they requested we reinstall
1094                        if !(reinstall || force) {
1095                            debug!(
1096                                "Executable at `{}` is already for `{}`",
1097                                target.simplified_display(),
1098                                installation.key(),
1099                            );
1100                            continue;
1101                        }
1102                        debug!(
1103                            "Replacing existing executable for `{}` at `{}`",
1104                            installation.key(),
1105                            target.simplified_display(),
1106                        );
1107                    }
1108                    Some(existing) => {
1109                        // The existing link points to a different installation, check if it
1110                        // is reasonable to replace
1111                        if force {
1112                            debug!(
1113                                "Replacing existing executable for `{}` at `{}` with executable for `{}` due to `--force` flag",
1114                                existing.key(),
1115                                target.simplified_display(),
1116                                installation.key(),
1117                            );
1118                        } else {
1119                            if installation.is_upgrade_of(existing) {
1120                                debug!(
1121                                    "Replacing existing executable for `{}` at `{}` with executable for `{}` since it is an upgrade",
1122                                    existing.key(),
1123                                    target.simplified_display(),
1124                                    installation.key(),
1125                                );
1126                            } else if default {
1127                                debug!(
1128                                    "Replacing existing executable for `{}` at `{}` with executable for `{}` since `--default` was requested`",
1129                                    existing.key(),
1130                                    target.simplified_display(),
1131                                    installation.key(),
1132                                );
1133                            } else {
1134                                debug!(
1135                                    "Executable already exists for `{}` at `{}`. Use `--force` to replace it",
1136                                    existing.key(),
1137                                    target.simplified_display()
1138                                );
1139                                continue;
1140                            }
1141                        }
1142                    }
1143                }
1144
1145                // Replace the existing link
1146                if let Err(err) = fs_err::remove_file(&target) {
1147                    errors.push((
1148                        InstallErrorKind::Bin,
1149                        installation.key().clone(),
1150                        anyhow::anyhow!(
1151                            "Executable already exists at `{}` but could not be removed: {err}",
1152                            target.simplified_display()
1153                        ),
1154                    ));
1155                    continue;
1156                }
1157
1158                if let Some(existing) = existing {
1159                    // Ensure we do not report installation of this executable for an existing
1160                    // key if we undo it
1161                    changelog
1162                        .installed_executables
1163                        .entry(existing.key().clone())
1164                        .or_default()
1165                        .remove(&target);
1166                }
1167
1168                if let Err(err) =
1169                    create_link_to_executable(&target, PythonExecutable::console(&executable))
1170                {
1171                    errors.push((
1172                        InstallErrorKind::Bin,
1173                        installation.key().clone(),
1174                        anyhow::anyhow!(
1175                            "Failed to create link at `{}`: {err}",
1176                            target.simplified_display()
1177                        ),
1178                    ));
1179                    continue;
1180                }
1181
1182                debug!(
1183                    "Updated executable at `{}` to {}",
1184                    target.simplified_display(),
1185                    installation.key(),
1186                );
1187                changelog.installed.insert(installation.key().clone());
1188                changelog
1189                    .installed_executables
1190                    .entry(installation.key().clone())
1191                    .or_default()
1192                    .insert(target.clone());
1193            }
1194            Err(err) => {
1195                errors.push((
1196                    InstallErrorKind::Bin,
1197                    installation.key().clone(),
1198                    Error::new(err),
1199                ));
1200            }
1201        }
1202    }
1203
1204    match existing_unmanaged.as_slice() {
1205        [] => {}
1206        [executable] => errors.push((
1207            InstallErrorKind::Bin,
1208            installation.key().clone(),
1209            anyhow::anyhow!(
1210                "Executable already exists at `{}` but is not managed by uv; use `--force` to replace it",
1211                executable.simplified_display()
1212            ),
1213        )),
1214        executables => errors.push((
1215            InstallErrorKind::Bin,
1216            installation.key().clone(),
1217            anyhow::anyhow!(
1218                "Executables {} already exist in `{}` but are not managed by uv; use `--force` to replace them",
1219                conjunction(
1220                    executables
1221                        .iter()
1222                        .filter_map(|path| path.file_name())
1223                        .map(|name| format!("`{}`", name.to_string_lossy()))
1224                        .collect(),
1225                ),
1226                bin.simplified_display()
1227            ),
1228        )),
1229    }
1230}
1231
1232/// Attempt to compile the bytecode for a [`ManagedPythonInstallation`]'s stdlib
1233async fn compile_stdlib_bytecode(
1234    installation: &ManagedPythonInstallation,
1235    concurrency: &Concurrency,
1236    cache: &Cache,
1237) -> Result<Option<(usize, std::time::Duration)>> {
1238    let start = std::time::Instant::now();
1239
1240    // Explicit matching so this heuristic is updated for future additions
1241    match installation.implementation() {
1242        ImplementationName::Pyodide => return Ok(None),
1243        ImplementationName::GraalPy | ImplementationName::PyPy | ImplementationName::CPython => (),
1244    }
1245
1246    let interpreter = Interpreter::query(installation.executable(false), cache)
1247        .context("Couldn't locate the interpreter")?;
1248
1249    // Ensure the bytecode compilation occurs in the correct place, in case the installed
1250    // interpreter reports a weird stdlib path.
1251    let interpreter_path = installation.path().canonicalize()?;
1252    let stdlib_path = match interpreter.stdlib().canonicalize() {
1253        Ok(path) if path.starts_with(&interpreter_path) => path,
1254        _ => {
1255            warn!(
1256                "The stdlib path for {} ({}) is not a subdirectory of its installation path ({}).",
1257                installation.key(),
1258                interpreter.stdlib().display(),
1259                interpreter_path.display()
1260            );
1261            return Ok(None);
1262        }
1263    };
1264
1265    let files = uv_installer::compile_tree(
1266        &stdlib_path,
1267        &installation.executable(false),
1268        concurrency,
1269        cache.root(),
1270    )
1271    .await
1272    .with_context(|| format!("Error compiling bytecode in: {}", stdlib_path.display()))?;
1273    if files == 0 {
1274        return Ok(None);
1275    }
1276    Ok(Some((files, start.elapsed())))
1277}
1278
1279pub(crate) fn format_executables(
1280    event: &ChangeEvent,
1281    executables: &FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>>,
1282) -> String {
1283    let Some(installed) = executables.get(&event.key) else {
1284        return String::new();
1285    };
1286
1287    if installed.is_empty() {
1288        return String::new();
1289    }
1290
1291    let names = installed
1292        .iter()
1293        .filter_map(|path| path.file_name())
1294        .map(|name| name.to_string_lossy())
1295        // Do not include the `.exe` during comparisons, it can change the ordering
1296        .sorted_unstable_by(|a, b| a.trim_end_matches(".exe").cmp(b.trim_end_matches(".exe")))
1297        .join(", ");
1298
1299    format!(" ({names})")
1300}
1301
1302fn warn_if_not_on_path(bin: &Path) {
1303    if !Shell::contains_path(bin) {
1304        if let Some(shell) = Shell::from_env() {
1305            if let Some(command) = shell.prepend_path(bin) {
1306                if shell.supports_update() {
1307                    warn_user!(
1308                        "`{}` is not on your PATH. To use installed Python executables, run `{}` or `{}`.",
1309                        bin.simplified_display().cyan(),
1310                        command.green(),
1311                        "uv python update-shell".green()
1312                    );
1313                } else {
1314                    warn_user!(
1315                        "`{}` is not on your PATH. To use installed Python executables, run `{}`.",
1316                        bin.simplified_display().cyan(),
1317                        command.green()
1318                    );
1319                }
1320            } else {
1321                warn_user!(
1322                    "`{}` is not on your PATH. To use installed Python executables, add the directory to your PATH.",
1323                    bin.simplified_display().cyan(),
1324                );
1325            }
1326        } else {
1327            warn_user!(
1328                "`{}` is not on your PATH. To use installed Python executables, add the directory to your PATH.",
1329                bin.simplified_display().cyan(),
1330            );
1331        }
1332    }
1333}
1334
1335/// Find the [`ManagedPythonInstallation`] corresponding to an executable link installed at the
1336/// given path, if any.
1337///
1338/// Will resolve symlinks on Unix. On Windows, will resolve the target link for a trampoline.
1339fn find_matching_bin_link<'a>(
1340    mut installations: impl Iterator<Item = &'a ManagedPythonInstallation>,
1341    path: &Path,
1342) -> Option<&'a ManagedPythonInstallation> {
1343    if cfg!(unix) {
1344        if !path.is_symlink() {
1345            return None;
1346        }
1347        let target = fs_err::canonicalize(path).ok()?;
1348
1349        installations.find(|installation| installation.executable(false) == target)
1350    } else if cfg!(windows) {
1351        let launcher = Launcher::try_from_path(path).ok()??;
1352        if !matches!(launcher.kind, LauncherKind::Python) {
1353            return None;
1354        }
1355        let target = dunce::canonicalize(launcher.python_path).ok()?;
1356
1357        installations.find(|installation| installation.executable(false) == target)
1358    } else {
1359        unreachable!("Only Unix and Windows are supported")
1360    }
1361}
1362
1363/// Check if a download's build version matches an installation's build version.
1364///
1365/// Returns `true` if the build versions match (no upgrade needed), `false` if an upgrade is needed.
1366fn matches_build(download_build: Option<&str>, installation_build: Option<&str>) -> bool {
1367    match (download_build, installation_build) {
1368        // Both have build, check if they match
1369        (Some(d), Some(i)) => compare_build_versions(d, i) == std::cmp::Ordering::Equal,
1370        // Legacy installation without BUILD file needs upgrade
1371        (Some(_), None) => false,
1372        // Download doesn't have build info, assume matches
1373        (None, _) => true,
1374    }
1375}