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};
6use std::str::FromStr;
7
8use anyhow::{Context, Error, Result};
9use futures::{StreamExt, join};
10use indexmap::IndexSet;
11use itertools::Itertools;
12use owo_colors::{AnsiColors, OwoColorize};
13use rustc_hash::{FxHashMap, FxHashSet};
14use tokio::sync::mpsc;
15use tracing::{debug, trace, warn};
16
17use uv_cache::Cache;
18use uv_client::BaseClientBuilder;
19use uv_configuration::{Concurrency, PythonUpgrade, PythonUpgradeSource};
20use uv_errors::{ErrorOptions, Hints, write_error_chain_with_options};
21use uv_fs::Simplified;
22use uv_platform::{Arch, Libc};
23use uv_preview::{Preview, PreviewFeature};
24use uv_python_discovery::ConfigDiscovery;
25use uv_python_discovery::PythonVersionFile;
26use uv_python_discovery::VersionFileDiscoveryOptions;
27use uv_python_discovery::VersionFilePreference;
28use uv_python_interpreter::Interpreter;
29use uv_python_managed::downloads::{
30    self, DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList,
31};
32use uv_python_managed::{
33    ManagedPythonInstallation, ManagedPythonInstallations, PythonExecutable,
34    PythonMinorVersionLink, compare_build_versions, create_link_to_executable,
35    python_executable_dir,
36};
37use uv_python_types::{
38    ArchRequest, ImplementationName, PythonArchitecture, PythonDownloadRequest, PythonDownloads,
39    PythonInstallationKey, PythonRequest, VersionRequest,
40};
41use uv_settings::PythonInstallMirrors;
42use uv_shell::Shell;
43use uv_trampoline_builder::{Launcher, LauncherKind};
44use uv_warnings::warn_user;
45
46use crate::{ChangeEvent, ChangeEventKind};
47use uv_command_support::{ExitStatus, Printer, UvError, conjunction, elapsed};
48use uv_python_discovery::PythonDownloadReporter;
49
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51struct InstallRequest<'a> {
52    /// The original request from the user
53    request: PythonRequest,
54    /// A download request corresponding to the `request` with platform information filled
55    download_request: PythonDownloadRequest,
56    /// A download that satisfies the request
57    download: &'a ManagedPythonDownload,
58}
59
60impl<'a> InstallRequest<'a> {
61    fn new(
62        request: PythonRequest,
63        arch: Option<PythonArchitecture>,
64        download_list: &'a ManagedPythonDownloadList,
65    ) -> Result<Self> {
66        // Make sure the request is a valid download request and fill platform information
67        let download_request = PythonDownloadRequest::from_request(&request)
68            .ok_or_else(|| {
69                anyhow::anyhow!(
70                    "`{}` is not a valid Python download request; see `uv help python` for supported formats and `uv python list --only-downloads` for available versions",
71                    request.to_canonical_string()
72                )
73            })?
74            .with_default_arch(arch.map(PythonArchitecture::into_inner))
75            .fill()?;
76
77        // Find a matching download
78        let download = match download_list.find(&download_request) {
79            Ok(download) => download,
80            Err(downloads::Error::NoDownloadFound(request))
81                if request.libc().is_some_and(Libc::is_musl)
82                    && request.arch().is_some_and(|arch| {
83                        arch.inner() == Arch::from(&uv_platform_tags::Arch::Armv7L)
84                    }) =>
85            {
86                return Err(anyhow::anyhow!(
87                    "uv does not yet provide musl Python distributions on armv7."
88                ));
89            }
90            Err(err) => return Err(err.into()),
91        };
92
93        Ok(Self {
94            request,
95            download_request,
96            download,
97        })
98    }
99
100    fn matches_installation(&self, installation: &ManagedPythonInstallation) -> bool {
101        self.download_request.satisfied_by_key(installation.key())
102    }
103
104    fn python_request(&self) -> &PythonRequest {
105        &self.request
106    }
107}
108
109impl std::fmt::Display for InstallRequest<'_> {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        let request = self.request.to_canonical_string();
112        let download = self.download_request.to_string();
113        if request != download {
114            write!(f, "{request} ({download})")
115        } else {
116            write!(f, "{request}")
117        }
118    }
119}
120
121#[derive(Debug, Default)]
122struct Changelog {
123    existing: FxHashSet<PythonInstallationKey>,
124    installed: FxHashSet<PythonInstallationKey>,
125    uninstalled: FxHashSet<PythonInstallationKey>,
126    installed_executables: FxHashMap<PythonInstallationKey, FxHashSet<PathBuf>>,
127}
128
129impl Changelog {
130    fn events(&self) -> impl Iterator<Item = ChangeEvent> {
131        let reinstalled = self
132            .uninstalled
133            .intersection(&self.installed)
134            .cloned()
135            .collect::<FxHashSet<_>>();
136        let uninstalled = self.uninstalled.difference(&reinstalled).cloned();
137        let installed = self.installed.difference(&reinstalled).cloned();
138
139        uninstalled
140            .map(|key| ChangeEvent {
141                key: key.clone(),
142                kind: ChangeEventKind::Removed,
143            })
144            .chain(installed.map(|key| ChangeEvent {
145                key: key.clone(),
146                kind: ChangeEventKind::Added,
147            }))
148            .chain(reinstalled.iter().map(|key| ChangeEvent {
149                key: key.clone(),
150                kind: ChangeEventKind::Reinstalled,
151            }))
152            .sorted_unstable_by(|a, b| a.key.cmp(&b.key).then_with(|| a.kind.cmp(&b.kind)))
153    }
154}
155
156#[derive(Debug, Clone, Copy)]
157enum InstallErrorKind {
158    DownloadUnpack,
159    Bin,
160    #[cfg_attr(not(windows), allow(dead_code))]
161    Registry,
162}
163
164#[derive(Debug, thiserror::Error)]
165#[error("`{command}` only accepts minor versions, got: {request}")]
166pub struct InvalidUpgradeRequestError {
167    command: PythonUpgradeSource,
168    request: String,
169    from_version_file: bool,
170}
171
172impl uv_errors::Hinted for InvalidUpgradeRequestError {
173    fn hints(&self) -> Hints<'_> {
174        if self.from_version_file {
175            Hints::from(
176                "The version request came from a `.python-version` file; change the patch version in the file to upgrade instead",
177            )
178        } else {
179            Hints::none()
180        }
181    }
182}
183
184/// Download and install Python versions.
185#[expect(clippy::fn_params_excessive_bools)]
186pub async fn install(
187    project_dir: &Path,
188    install_dir: Option<PathBuf>,
189    targets: Vec<String>,
190    reinstall: bool,
191    upgrade: PythonUpgrade,
192    bin: Option<bool>,
193    registry: Option<bool>,
194    force: bool,
195    install_mirrors: PythonInstallMirrors,
196    client_builder: BaseClientBuilder<'_>,
197    default: bool,
198    python_arch: Option<PythonArchitecture>,
199    python_downloads: PythonDownloads,
200    config_discovery: ConfigDiscovery,
201    compile_bytecode: bool,
202    concurrency: &Concurrency,
203    cache: &Cache,
204    preview: Preview,
205    printer: Printer,
206) -> Result<ExitStatus> {
207    let (sender, mut receiver) = mpsc::unbounded_channel();
208    let compiler = async {
209        let mut total_files = 0;
210        let mut total_elapsed = std::time::Duration::default();
211        let mut total_skipped = 0;
212        while let Some(installation) = receiver.recv().await {
213            if let Some((files, elapsed)) =
214                compile_stdlib_bytecode(&installation, concurrency, cache)
215                    .await
216                    .with_context(|| {
217                        format!(
218                            "Failed to bytecode-compile Python standard library for: {}",
219                            installation.key()
220                        )
221                    })?
222            {
223                total_files += files;
224                total_elapsed += elapsed;
225            } else {
226                total_skipped += 1;
227            }
228        }
229        Ok::<_, anyhow::Error>((total_files, total_elapsed, total_skipped))
230    };
231
232    let installer = perform_install(
233        project_dir,
234        install_dir,
235        targets,
236        reinstall,
237        upgrade,
238        bin,
239        registry,
240        force,
241        install_mirrors,
242        client_builder,
243        cache,
244        default,
245        python_arch,
246        python_downloads,
247        config_discovery,
248        compile_bytecode.then_some(sender),
249        concurrency,
250        preview,
251        printer,
252    );
253
254    let (installer_result, compiler_result) = join!(installer, compiler);
255
256    let (total_files, total_elapsed, total_skipped) = compiler_result?;
257    if total_files > 0 {
258        let s = if total_files == 1 { "" } else { "s" };
259        writeln!(
260            printer.stderr(),
261            "{}",
262            format!(
263                "Bytecode compiled {} {}{}",
264                format!("{total_files} file{s}").bold(),
265                format!("in {}", elapsed(total_elapsed)).dimmed(),
266                if total_skipped > 0 {
267                    format!(
268                        " (skipped {total_skipped} incompatible version{})",
269                        if total_skipped == 1 { "" } else { "s" }
270                    )
271                } else {
272                    String::new()
273                }
274                .dimmed()
275            )
276            .dimmed()
277        )?;
278    } else if total_skipped > 0 {
279        writeln!(
280            printer.stderr(),
281            "{}",
282            format!("No compatible versions to bytecode compile (skipped {total_skipped})")
283                .dimmed()
284        )?;
285    }
286
287    installer_result
288}
289
290async fn perform_install(
291    project_dir: &Path,
292    install_dir: Option<PathBuf>,
293    targets: Vec<String>,
294    reinstall: bool,
295    upgrade: PythonUpgrade,
296    bin: Option<bool>,
297    registry: Option<bool>,
298    force: bool,
299    install_mirrors: PythonInstallMirrors,
300    client_builder: BaseClientBuilder<'_>,
301    cache: &Cache,
302    default: bool,
303    python_arch: Option<PythonArchitecture>,
304    python_downloads: PythonDownloads,
305    config_discovery: ConfigDiscovery,
306    bytecode_compilation_sender: Option<mpsc::UnboundedSender<ManagedPythonInstallation>>,
307    concurrency: &Concurrency,
308    preview: Preview,
309    printer: Printer,
310) -> Result<ExitStatus> {
311    let start = std::time::Instant::now();
312
313    // TODO(zanieb): We should consider marking the Python installation as the default when
314    // `--default` is used. It's not clear how this overlaps with a global Python pin, but I'd be
315    // surprised if `uv python find` returned the "newest" Python version rather than the one I just
316    // installed with the `--default` flag.
317    if default && !preview.is_enabled(PreviewFeature::PythonInstallDefault) {
318        warn_user!(
319            "The `--default` option is experimental and may change without warning. Pass `--preview-features {}` to disable this warning",
320            PreviewFeature::PythonInstallDefault
321        );
322    }
323
324    if default && targets.len() > 1 {
325        anyhow::bail!("The `--default` flag cannot be used with multiple targets");
326    }
327
328    // Read the existing installations, lock the directory for the duration
329    let installations = ManagedPythonInstallations::from_settings(install_dir.clone())?.init()?;
330    let installations_dir = installations.root();
331    let scratch_dir = installations.scratch();
332    let _lock = installations.lock().await?;
333    let existing_installations: Vec<_> = installations
334        .find_all()?
335        .inspect(|installation| trace!("Found existing installation {}", installation.key()))
336        .collect();
337
338    // Resolve the requests
339    let mut is_default_install = false;
340    let mut is_unspecified_upgrade = false;
341    let retry_policy = client_builder.retry_policy();
342    let download_list = ManagedPythonDownloadList::new(
343        &client_builder,
344        cache,
345        install_mirrors.python_downloads_json_url.as_deref(),
346    )
347    .await?;
348    // Python downloads are performing their own retries to catch stream errors, disable the
349    // default retries to avoid the middleware from performing uncontrolled retries.
350    let client = client_builder.retries(0).build()?;
351    // TODO(zanieb): We use this variable to special-case .python-version files, but it'd be nice to
352    // have generalized request source tracking instead
353    let mut is_from_python_version_file = false;
354    let requests: Vec<_> = if targets.is_empty() {
355        if matches!(
356            upgrade,
357            PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade)
358        ) {
359            is_unspecified_upgrade = true;
360            // On upgrade, derive requests for all of the existing installations
361            let mut minor_version_requests = IndexSet::<InstallRequest>::default();
362            for installation in &existing_installations {
363                let mut request = PythonDownloadRequest::from(installation);
364                // We should always have a version in the request from an existing installation
365                let version = request.take_version().unwrap();
366                // Drop the patch and prerelease parts from the request
367                request = request.with_version(version.only_minor());
368                let install_request =
369                    InstallRequest::new(PythonRequest::Key(request), python_arch, &download_list)?;
370                minor_version_requests.insert(install_request);
371            }
372            minor_version_requests.into_iter().collect::<Vec<_>>()
373        } else {
374            PythonVersionFile::discover(
375                project_dir,
376                &VersionFileDiscoveryOptions::default()
377                    .with_config_discovery(config_discovery)
378                    .with_preference(VersionFilePreference::Versions),
379            )
380            .await?
381            .inspect(|file| {
382                debug!(
383                    "Found Python version file at: {}",
384                    file.path().user_display()
385                );
386            })
387            .map(PythonVersionFile::into_versions)
388            .inspect(|_| is_from_python_version_file = true)
389            .unwrap_or_else(|| {
390                // If no version file is found and no requests were made
391                // TODO(zanieb): We should consider differentiating between a global Python version
392                // file here, allowing a request from there to enable `is_default_install`.
393                is_default_install = true;
394                vec![if reinstall {
395                    // On bare `--reinstall`, reinstall all Python versions
396                    PythonRequest::Any
397                } else {
398                    PythonRequest::Default
399                }]
400            })
401            .into_iter()
402            .map(|request| InstallRequest::new(request, python_arch, &download_list))
403            .collect::<Result<Vec<_>>>()?
404        }
405    } else {
406        targets
407            .iter()
408            .map(|target| PythonRequest::parse(target.as_str()))
409            .map(|request| InstallRequest::new(request, python_arch, &download_list))
410            .collect::<Result<Vec<_>>>()?
411    };
412
413    if requests.is_empty() {
414        match upgrade {
415            PythonUpgrade::Enabled(PythonUpgradeSource::Upgrade) => {
416                writeln!(
417                    printer.stderr(),
418                    "There are no installed versions to upgrade"
419                )?;
420            }
421            PythonUpgrade::Enabled(PythonUpgradeSource::Install) => {
422                writeln!(
423                    printer.stderr(),
424                    "No Python versions specified for upgrade; did you mean `uv python upgrade`?"
425                )?;
426            }
427            PythonUpgrade::Disabled => {}
428        }
429        return Ok(ExitStatus::Success);
430    }
431
432    let requested_minor_versions = requests
433        .iter()
434        .filter_map(|request| {
435            if let PythonRequest::Version(VersionRequest::MajorMinor(major, minor, ..)) =
436                request.python_request()
437            {
438                uv_pep440::Version::from_str(&format!("{major}.{minor}")).ok()
439            } else {
440                None
441            }
442        })
443        .collect::<IndexSet<_>>();
444
445    if let PythonUpgrade::Enabled(source) = upgrade {
446        if let Some(request) = requests.iter().find(|request| {
447            request.request.includes_patch() || request.request.includes_prerelease()
448        }) {
449            return Err(UvError::user(InvalidUpgradeRequestError {
450                command: source,
451                request: request.request.to_canonical_string().into_owned(),
452                from_version_file: is_from_python_version_file,
453            })
454            .into());
455        }
456    }
457
458    // Find requests that are already satisfied
459    let mut changelog = Changelog::default();
460    let (satisfied, unsatisfied): (Vec<_>, Vec<_>) = if reinstall {
461        // In the reinstall case, we want to iterate over all matching installations instead of
462        // stopping at the first match.
463
464        let mut unsatisfied: Vec<Cow<InstallRequest>> =
465            Vec::with_capacity(existing_installations.len() + requests.len());
466
467        for request in &requests {
468            let mut matching_installations = existing_installations
469                .iter()
470                .filter(|installation| request.matches_installation(installation))
471                .peekable();
472
473            if matching_installations.peek().is_none() {
474                debug!("No installation found for request `{}`", request);
475                unsatisfied.push(Cow::Borrowed(request));
476            }
477
478            for installation in matching_installations {
479                changelog.existing.insert(installation.key().clone());
480
481                if matches!(upgrade, PythonUpgrade::Enabled(_))
482                    && !matches!(&request.request, &PythonRequest::Any)
483                {
484                    // An upgrade must reinstall the latest patch, not every matching patch.
485                    debug!("Will reinstall the latest patch for `{}`", request);
486                    unsatisfied.push(Cow::Borrowed(request));
487                    break;
488                }
489
490                // Construct an install request matching the existing installation.
491                match InstallRequest::new(
492                    PythonRequest::Key(installation.into()),
493                    python_arch,
494                    &download_list,
495                ) {
496                    Ok(request) => {
497                        debug!("Will reinstall `{}`", installation.key());
498                        unsatisfied.push(Cow::Owned(request));
499                    }
500                    Err(err) => {
501                        // This shouldn't really happen, but maybe a new version of uv dropped
502                        // support for a key we previously supported.
503                        warn_user!(
504                            "Failed to create reinstall request for existing installation `{}`: {err}",
505                            installation.key().green()
506                        );
507                    }
508                }
509            }
510        }
511        (vec![], unsatisfied)
512    } else {
513        // If we can find one existing installation that matches the request, it is satisfied
514        let mut satisfied = Vec::new();
515        let mut unsatisfied = Vec::new();
516
517        for request in &requests {
518            if matches!(upgrade, PythonUpgrade::Enabled(_)) {
519                // If this is an upgrade, the requested version is a minor version but the
520                // requested download is the highest patch for that minor version. We need to
521                // install it unless an exact match is found (including build version).
522                if let Some(installation) = existing_installations
523                    .iter()
524                    .find(|inst| request.download.key() == inst.key())
525                {
526                    if matches_build(request.download.build(), installation.build()) {
527                        debug!("Found `{}` for request `{}`", installation.key(), request);
528                        satisfied.push(installation);
529                    } else {
530                        // Key matches but build version differs - track as existing for reinstall
531                        debug!(
532                            "Build version mismatch for `{}`, will upgrade",
533                            installation.key()
534                        );
535                        changelog.existing.insert(installation.key().clone());
536                        unsatisfied.push(Cow::Borrowed(request));
537                    }
538                } else {
539                    debug!("No installation found for request `{}`", request);
540                    unsatisfied.push(Cow::Borrowed(request));
541                }
542            } else if let Some(installation) = existing_installations
543                .iter()
544                .find(|inst| request.matches_installation(inst))
545            {
546                debug!("Found `{}` for request `{}`", installation.key(), request);
547                satisfied.push(installation);
548            } else {
549                debug!("No installation found for request `{}`", request);
550                unsatisfied.push(Cow::Borrowed(request));
551            }
552        }
553
554        (satisfied, unsatisfied)
555    };
556
557    // For all satisfied installs, bytecode compile them now before any future
558    // early return.
559    if let Some(ref sender) = bytecode_compilation_sender {
560        satisfied
561            .iter()
562            .copied()
563            .cloned()
564            .try_for_each(|installation| {
565                sender
566                    .send(installation)
567                    .map_err(|err| anyhow::anyhow!(err))
568            })?;
569    }
570
571    // Check if Python downloads are banned
572    if matches!(python_downloads, PythonDownloads::Never) && !unsatisfied.is_empty() {
573        writeln!(
574            printer.stderr(),
575            "Python downloads are not allowed (`python-downloads = \"never\"`). Change to `python-downloads = \"manual\"` to allow explicit installs.",
576        )?;
577        return Ok(ExitStatus::Failure);
578    }
579
580    // Find downloads for the requests
581    let downloads = unsatisfied
582        .iter()
583        .inspect(|request| {
584            debug!(
585                "Found download `{}` for request `{}`",
586                request.download, request,
587            );
588        })
589        .map(|request| request.download)
590        // Ensure we only download each version once
591        .unique_by(|download| download.key())
592        .collect::<Vec<_>>();
593
594    // Download and unpack the Python versions concurrently
595    let reporter = PythonDownloadReporter::new(printer, Some(downloads.len() as u64));
596    let replacements = changelog.existing.clone();
597
598    let mut tasks = futures::stream::iter(&downloads)
599        .map(async |download| {
600            (
601                *download,
602                download
603                    .fetch_with_retry(
604                        &client,
605                        &retry_policy,
606                        installations_dir,
607                        &scratch_dir,
608                        reinstall || replacements.contains(download.key()),
609                        install_mirrors.mirrors(),
610                        Some(&reporter),
611                    )
612                    .await,
613            )
614        })
615        .buffer_unordered(concurrency.downloads);
616
617    let mut errors = vec![];
618    let mut downloaded = Vec::with_capacity(downloads.len());
619    let mut requests_by_new_installation = BTreeMap::new();
620    while let Some((download, result)) = tasks.next().await {
621        match result {
622            Ok(download_result) => {
623                let path = match download_result {
624                    // We should only encounter already-available during concurrent installs
625                    DownloadResult::AlreadyAvailable(path) => path,
626                    DownloadResult::Fetched(path) => path,
627                };
628
629                let installation = ManagedPythonInstallation::new(path, download)?;
630                if let Some(ref sender) = bytecode_compilation_sender {
631                    sender
632                        .send(installation.clone())
633                        .map_err(|err| anyhow::anyhow!(err))?;
634                }
635                changelog.installed.insert(installation.key().clone());
636                for request in &requests {
637                    // Take note of which installations satisfied which requests
638                    if request.matches_installation(&installation) {
639                        requests_by_new_installation
640                            .entry(installation.key().clone())
641                            .or_insert(Vec::new())
642                            .push(request);
643                    }
644                }
645                if changelog.existing.contains(installation.key()) {
646                    changelog.uninstalled.insert(installation.key().clone());
647                }
648                downloaded.push(installation.clone());
649            }
650            Err(err) => {
651                errors.push((
652                    InstallErrorKind::DownloadUnpack,
653                    download.key().clone(),
654                    anyhow::Error::new(err),
655                ));
656            }
657        }
658    }
659
660    let bin_dir = if matches!(bin, Some(false)) {
661        None
662    } else {
663        Some(python_executable_dir()?)
664    };
665
666    let installations: Vec<_> = downloaded.iter().chain(satisfied.iter().copied()).collect();
667
668    // Ensure that the installations are _complete_ for both downloaded installations and existing
669    // installations that match the request
670    for installation in &installations {
671        installation.ensure_externally_managed()?;
672        installation.ensure_sysconfig_patched()?;
673        installation.ensure_canonical_executables()?;
674        installation.ensure_build_file()?;
675        if let Err(e) = installation.ensure_dylib_patched() {
676            e.warn_user(installation);
677        }
678
679        let upgradeable = (default || is_default_install)
680            || requested_minor_versions.contains(&installation.key().version().python_version());
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()?;
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}