Skip to main content

uv_python_discovery/
installation.rs

1use reqwest_retry::policies::ExponentialBackoff;
2use tracing::{debug, info};
3use uv_fs::Simplified;
4use uv_warnings::warn_user;
5
6use uv_cache::Cache;
7use uv_client::{BaseClient, BaseClientBuilder};
8use uv_pep440::Version;
9use uv_platform::{Arch, Libc, Os};
10
11use crate::Error;
12use crate::MissingPythonHint;
13use crate::discovery::find_best_python_installation;
14use crate::discovery::find_python_installation;
15use uv_python_interpreter::{EnvironmentNotFound, Interpreter, PythonEnvironment};
16use uv_python_managed::downloads::{
17    DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList, Reporter,
18};
19use uv_python_managed::{ManagedPythonInstallation, ManagedPythonInstallations};
20use uv_python_types::PythonInstallationKey;
21use uv_python_types::{
22    EnvironmentPreference, ImplementationName, LenientImplementationName, PythonArchitecture,
23    PythonDownloadMirrors, PythonDownloadRequest, PythonDownloads, PythonPreference, PythonRequest,
24    PythonSource, PythonVersion, VersionRequest,
25};
26
27/// A Python interpreter and accompanying tools.
28#[derive(Clone, Debug)]
29pub struct PythonInstallation {
30    // Public in the crate for test assertions
31    pub(crate) source: PythonSource,
32    pub(crate) interpreter: Interpreter,
33}
34
35impl PythonInstallation {
36    /// Create a new [`PythonInstallation`] from a source and interpreter.
37    pub(crate) fn new(source: PythonSource, interpreter: Interpreter) -> Self {
38        Self {
39            source,
40            interpreter,
41        }
42    }
43
44    /// Return a new installation with the given [`PythonSource`].
45    #[must_use]
46    fn with_source(self, source: PythonSource) -> Self {
47        Self { source, ..self }
48    }
49
50    /// In test mode, change the source to [`PythonSource::Managed`] if the interpreter was
51    /// marked as managed via `TestContext::with_versions_as_managed`.
52    #[must_use]
53    pub(crate) fn maybe_with_test_source(self) -> Self {
54        if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok()
55            && self.is_managed()
56        {
57            self.with_source(PythonSource::Managed)
58        } else {
59            self
60        }
61    }
62
63    /// Check whether this installation satisfies the standard post-query discovery filters:
64    /// environment preference, version request, and Python preference.
65    pub(crate) fn satisfies_preferences(
66        &self,
67        version: &VersionRequest,
68        environments: EnvironmentPreference,
69        preference: PythonPreference,
70    ) -> bool {
71        if !self.satisfies_environment_preference(environments) {
72            return false;
73        }
74        if !self.matches_version_request(version) {
75            debug!(
76                "Skipping interpreter at `{}` from {}: does not satisfy request `{version}`",
77                self.interpreter.sys_executable().user_display(),
78                self.source,
79            );
80            return false;
81        }
82        self.satisfies_preference(&preference)
83    }
84
85    /// Find an installed [`PythonInstallation`].
86    ///
87    /// This is the standard interface for discovering a Python installation for creating
88    /// an environment. If interested in finding an existing environment, see
89    /// [`find_environment`] instead.
90    ///
91    /// Note we still require an [`EnvironmentPreference`] as this can either bypass virtual environments
92    /// or prefer them. In most cases, this should be [`EnvironmentPreference::OnlySystem`]
93    /// but if you want to allow an interpreter from a virtual environment if it satisfies the request,
94    /// then use [`EnvironmentPreference::Any`].
95    ///
96    /// See `find_python_installation` for implementation details.
97    pub fn find(
98        request: &PythonRequest,
99        environments: EnvironmentPreference,
100        preference: PythonPreference,
101        arch: Option<PythonArchitecture>,
102        download_list: &ManagedPythonDownloadList,
103        cache: &Cache,
104    ) -> Result<Self, Error> {
105        let installation = Self::find_existing(request, environments, preference, arch, cache)?;
106        installation.warn_if_outdated_prerelease(request, download_list);
107        Ok(installation)
108    }
109
110    /// Find an existing [`PythonInstallation`].
111    pub fn find_existing(
112        request: &PythonRequest,
113        environments: EnvironmentPreference,
114        preference: PythonPreference,
115        arch: Option<PythonArchitecture>,
116        cache: &Cache,
117    ) -> Result<Self, Error> {
118        Ok(find_python_installation(
119            request,
120            environments,
121            preference,
122            arch,
123            cache,
124        )??)
125    }
126
127    /// Find or download a [`PythonInstallation`] that satisfies a requested version, if the request
128    /// cannot be satisfied, fallback to the best available Python installation.
129    pub async fn find_best(
130        request: &PythonRequest,
131        environments: EnvironmentPreference,
132        preference: PythonPreference,
133        arch: Option<PythonArchitecture>,
134        python_downloads: PythonDownloads,
135        client_builder: &BaseClientBuilder<'_>,
136        cache: &Cache,
137        reporter: Option<&dyn Reporter>,
138        mirrors: PythonDownloadMirrors<'_>,
139        python_downloads_json_url: Option<&str>,
140    ) -> Result<Self, Error> {
141        let downloads_enabled = preference.allows_managed()
142            && python_downloads.is_automatic()
143            && !client_builder.is_offline();
144        let installation = find_best_python_installation(
145            request,
146            environments,
147            preference,
148            arch,
149            downloads_enabled,
150            client_builder,
151            cache,
152            reporter,
153            mirrors,
154            python_downloads_json_url,
155        )
156        .await?;
157        installation
158            .download_and_warn_if_outdated_prerelease(
159                request,
160                client_builder,
161                cache,
162                python_downloads_json_url,
163            )
164            .await?;
165        Ok(installation)
166    }
167
168    /// Find or fetch a [`PythonInstallation`].
169    ///
170    /// Unlike [`PythonInstallation::find`], if the required Python is not installed it will be installed automatically.
171    pub async fn find_or_download(
172        request: Option<&PythonRequest>,
173        environments: EnvironmentPreference,
174        preference: PythonPreference,
175        arch: Option<PythonArchitecture>,
176        python_downloads: PythonDownloads,
177        client_builder: &BaseClientBuilder<'_>,
178        cache: &Cache,
179        reporter: Option<&dyn Reporter>,
180        mirrors: PythonDownloadMirrors<'_>,
181        python_downloads_json_url: Option<&str>,
182    ) -> Result<Self, Error> {
183        let request = request.unwrap_or(&PythonRequest::Default);
184
185        let err = match Self::find_existing(request, environments, preference, arch, cache) {
186            Ok(installation) => {
187                installation
188                    .download_and_warn_if_outdated_prerelease(
189                        request,
190                        client_builder,
191                        cache,
192                        python_downloads_json_url,
193                    )
194                    .await?;
195                return Ok(installation);
196            }
197            Err(err) => err,
198        };
199
200        match err {
201            // If Python is missing, we should attempt a download
202            Error::MissingPython(..) => {}
203            // If we raised a non-critical error, we should attempt a download
204            Error::Discovery(ref err) if !err.is_critical() => {}
205            // Otherwise, this is fatal
206            _ => return Err(err),
207        }
208
209        // If we can't convert the request to a download, throw the original error
210        let Some(download_request) = PythonDownloadRequest::from_request(request) else {
211            return Err(err);
212        };
213
214        let download_list =
215            ManagedPythonDownloadList::new(client_builder, cache, python_downloads_json_url)
216                .await?;
217
218        let downloads_enabled = preference.allows_managed()
219            && python_downloads.is_automatic()
220            && !client_builder.is_offline();
221
222        let download = download_request
223            .clone()
224            .with_default_arch(arch.map(PythonArchitecture::into_inner))
225            .fill()
226            .map_err(uv_python_managed::downloads::Error::from)
227            .map(|request| download_list.find(&request));
228
229        // Regardless of whether downloads are enabled, we want to determine if the download is
230        // available to power error messages. However, if downloads aren't enabled, we don't want to
231        // report any errors related to them.
232        let download = match download {
233            Ok(Ok(download)) => Some(download),
234            // If the download cannot be found, return the _original_ discovery error
235            Ok(Err(uv_python_managed::downloads::Error::NoDownloadFound(_))) => {
236                if downloads_enabled {
237                    debug!("No downloads are available for {request}");
238                    if matches!(request, PythonRequest::Default | PythonRequest::Any) {
239                        return Err(err);
240                    }
241                    return Err(err.with_hint(MissingPythonHint::RequiresUpdate));
242                }
243                None
244            }
245            Err(err) | Ok(Err(err)) => {
246                if downloads_enabled {
247                    // We failed to determine the platform information
248                    return Err(err.into());
249                }
250                None
251            }
252        };
253
254        let Some(download) = download else {
255            // N.B. We should only be in this case when downloads are disabled; when downloads are
256            // enabled, we should fail eagerly when something goes wrong with the download.
257            debug_assert!(!downloads_enabled);
258            return Err(err);
259        };
260
261        // If the download is available, but not usable, we attach a hint to the original error.
262        if !downloads_enabled {
263            match python_downloads {
264                PythonDownloads::Automatic => {}
265                PythonDownloads::Manual => {
266                    return Err(err.with_hint(MissingPythonHint::DownloadsManual(request.clone())));
267                }
268                PythonDownloads::Never => {
269                    return Err(err.with_hint(MissingPythonHint::DownloadsNever(request.clone())));
270                }
271            }
272
273            match preference {
274                PythonPreference::OnlySystem => {
275                    return Err(
276                        err.with_hint(MissingPythonHint::PreferenceOnlySystem(request.clone()))
277                    );
278                }
279                PythonPreference::Managed
280                | PythonPreference::OnlyManaged
281                | PythonPreference::System => {}
282            }
283
284            if client_builder.is_offline() {
285                return Err(err.with_hint(MissingPythonHint::Offline(request.clone())));
286            }
287
288            return Err(err);
289        }
290
291        // Python downloads are performing their own retries to catch stream errors, disable the
292        // default retries to avoid the middleware performing uncontrolled retries.
293        let retry_policy = client_builder.retry_policy();
294        let download_client = client_builder.clone().retries(0).build()?;
295
296        let installation = Self::fetch(
297            download,
298            &download_client,
299            &retry_policy,
300            cache,
301            reporter,
302            mirrors,
303        )
304        .await?;
305
306        installation.warn_if_outdated_prerelease(request, &download_list);
307
308        Ok(installation)
309    }
310
311    /// Download and install the requested installation.
312    pub(crate) async fn fetch(
313        download: &ManagedPythonDownload,
314        client: &BaseClient,
315        retry_policy: &ExponentialBackoff,
316        cache: &Cache,
317        reporter: Option<&dyn Reporter>,
318        mirrors: PythonDownloadMirrors<'_>,
319    ) -> Result<Self, Error> {
320        let installations = ManagedPythonInstallations::from_settings(None)?.init()?;
321        let installations_dir = installations.root();
322        let scratch_dir = installations.scratch();
323        let _lock = installations.lock().await?;
324
325        info!("Fetching requested Python...");
326        let result = download
327            .fetch_with_retry(
328                client,
329                retry_policy,
330                installations_dir,
331                &scratch_dir,
332                false,
333                mirrors,
334                reporter,
335            )
336            .await?;
337
338        let path = match result {
339            DownloadResult::AlreadyAvailable(path) => path,
340            DownloadResult::Fetched(path) => path,
341        };
342
343        let installed = ManagedPythonInstallation::new(path, download)?;
344        installed.ensure_externally_managed().await?;
345        installed.ensure_sysconfig_patched().await?;
346        installed.ensure_canonical_executables().await?;
347        installed.ensure_build_file().await?;
348
349        let minor_version = installed.minor_version_key();
350        let highest_patch = installations
351            .find_all()?
352            .filter(|installation| installation.minor_version_key() == minor_version)
353            .filter_map(|installation| installation.version().patch())
354            .fold(0, std::cmp::max);
355        if installed
356            .version()
357            .patch()
358            .is_some_and(|p| p >= highest_patch)
359        {
360            installed.ensure_minor_version_link().await?;
361        }
362
363        if let Err(e) = installed.ensure_dylib_patched() {
364            e.warn_user(&installed);
365        }
366
367        Ok(Self {
368            source: PythonSource::Managed,
369            interpreter: Interpreter::query(installed.executable(false), cache)?,
370        })
371    }
372
373    /// Return the [`PythonSource`] of the Python installation, indicating where it was found.
374    pub fn source(&self) -> &PythonSource {
375        &self.source
376    }
377
378    pub fn key(&self) -> PythonInstallationKey {
379        self.interpreter.key()
380    }
381
382    /// Return the Python [`Version`] of the Python installation as reported by its interpreter.
383    pub fn python_version(&self) -> &Version {
384        self.interpreter.python_version()
385    }
386
387    /// Return the [`LenientImplementationName`] of the Python installation as reported by its interpreter.
388    pub fn implementation(&self) -> LenientImplementationName {
389        LenientImplementationName::from(self.interpreter.implementation_name())
390    }
391
392    /// Returns `true` if this is a managed (uv-installed) Python installation.
393    ///
394    /// Uses the source as a fast path, then falls back to checking the interpreter's base prefix.
395    pub(crate) fn is_managed(&self) -> bool {
396        if self.source.is_managed() {
397            return true;
398        }
399
400        if let Ok(test_managed) =
401            std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED)
402        {
403            // During testing, we collect interpreters into an artificial search path and need to
404            // be able to mock whether an interpreter is managed or not.
405            return test_managed.split_ascii_whitespace().any(|item| {
406                let version = <PythonVersion as std::str::FromStr>::from_str(item).expect(
407                    "`UV_INTERNAL__TEST_PYTHON_MANAGED` items should be valid Python versions",
408                );
409                if version.patch().is_some() {
410                    version.version() == self.interpreter.python_version()
411                } else {
412                    (version.major(), version.minor()) == self.interpreter.python_tuple()
413                }
414            });
415        }
416
417        ManagedPythonInstallations::from_settings(None)
418            .is_ok_and(|installations| installations.contains(&self.interpreter))
419    }
420
421    /// Whether this is a CPython installation.
422    ///
423    /// Returns false if it is an alternative implementation, e.g., PyPy.
424    pub(crate) fn is_alternative_implementation(&self) -> bool {
425        !matches!(
426            self.implementation(),
427            LenientImplementationName::Known(ImplementationName::CPython)
428        ) || self.os().is_emscripten()
429    }
430
431    /// Return the [`Arch`] of the Python installation as reported by its interpreter.
432    pub fn arch(&self) -> Arch {
433        self.interpreter.arch()
434    }
435
436    /// Return the [`Libc`] of the Python installation as reported by its interpreter.
437    pub fn libc(&self) -> Libc {
438        self.interpreter.libc()
439    }
440
441    /// Return the [`Os`] of the Python installation as reported by its interpreter.
442    pub fn os(&self) -> Os {
443        self.interpreter.os()
444    }
445
446    /// Return the [`Interpreter`] for the Python installation.
447    pub fn interpreter(&self) -> &Interpreter {
448        &self.interpreter
449    }
450
451    /// Consume the [`PythonInstallation`] and return the [`Interpreter`].
452    pub fn into_interpreter(self) -> Interpreter {
453        self.interpreter
454    }
455
456    /// Return `true` when checking for an outdated managed prerelease warning may be necessary.
457    fn should_check_outdated_prerelease_warning(&self, request: &PythonRequest) -> bool {
458        if request.allows_prereleases() {
459            return false;
460        }
461
462        let interpreter = self.interpreter();
463
464        if interpreter.python_version().pre().is_none() {
465            return false;
466        }
467
468        if !self.is_managed() {
469            return false;
470        }
471
472        // Transparent upgrades only exist for CPython, so skip the warning for other
473        // managed implementations.
474        //
475        // See: https://github.com/astral-sh/uv/issues/16675
476        if !interpreter
477            .implementation_name()
478            .eq_ignore_ascii_case("cpython")
479        {
480            return false;
481        }
482
483        true
484    }
485
486    /// Emit a warning when the interpreter is a managed prerelease and a matching stable
487    /// build can be installed via `uv python upgrade`.
488    fn warn_if_outdated_prerelease(
489        &self,
490        request: &PythonRequest,
491        download_list: &ManagedPythonDownloadList,
492    ) {
493        if !self.should_check_outdated_prerelease_warning(request) {
494            return;
495        }
496
497        let interpreter = self.interpreter();
498        let version = interpreter.python_version();
499
500        let release = version.only_release();
501
502        let Ok(download_request) = PythonDownloadRequest::try_from(&interpreter.key()) else {
503            return;
504        };
505
506        let download_request = download_request.with_prereleases(false);
507
508        let has_stable_download = {
509            let mut downloads = download_list.iter_matching(&download_request);
510
511            downloads.any(|download| {
512                let download_version = download.key().version().into_version();
513                download_version.pre().is_none() && download_version.only_release() >= release
514            })
515        };
516
517        if !has_stable_download {
518            return;
519        }
520
521        if let Some(upgrade_request) = download_request
522            .unset_defaults()
523            .without_patch()
524            .simplified_display()
525        {
526            warn_user!(
527                "You're using a pre-release version of Python ({}) but a stable version is available. Use `uv python upgrade {}` to upgrade.",
528                version,
529                upgrade_request
530            );
531        } else {
532            warn_user!(
533                "You're using a pre-release version of Python ({}) but a stable version is available. Run `uv python upgrade` to update your managed interpreters.",
534                version,
535            );
536        }
537    }
538
539    /// Emit a warning when the interpreter is a managed prerelease and a matching stable
540    /// build can be installed via `uv python upgrade`.
541    ///
542    /// Avoids loading the Python download list unless the discovered interpreter could require
543    /// the warning.
544    pub async fn download_and_warn_if_outdated_prerelease(
545        &self,
546        request: &PythonRequest,
547        client_builder: &BaseClientBuilder<'_>,
548        cache: &Cache,
549        python_downloads_json_url: Option<&str>,
550    ) -> Result<(), Error> {
551        if !self.should_check_outdated_prerelease_warning(request) {
552            return Ok(());
553        }
554
555        let download_list =
556            ManagedPythonDownloadList::new(client_builder, cache, python_downloads_json_url)
557                .await?;
558        self.warn_if_outdated_prerelease(request, &download_list);
559
560        Ok(())
561    }
562
563    /// Check whether this installation satisfies the Python preference.
564    ///
565    /// Explicit sources, including provided paths and active environments, are accepted even
566    /// when their managed status conflicts with the preference.
567    pub fn satisfies_preference(&self, preference: &PythonPreference) -> bool {
568        let source = self.source;
569        let interpreter = &self.interpreter;
570
571        match preference {
572            PythonPreference::OnlyManaged => {
573                if self.is_managed() {
574                    true
575                } else if source.is_explicit() {
576                    debug!(
577                        "Allowing unmanaged Python interpreter at `{}` (in conflict with the `python-preference`) since it is from source: {source}",
578                        interpreter.sys_executable().display()
579                    );
580                    true
581                } else {
582                    debug!(
583                        "Ignoring Python interpreter at `{}`: only managed interpreters allowed",
584                        interpreter.sys_executable().display()
585                    );
586                    false
587                }
588            }
589            // If not "only" a kind, any interpreter is okay
590            PythonPreference::Managed | PythonPreference::System => true,
591            PythonPreference::OnlySystem => {
592                if !self.is_managed() {
593                    true
594                } else if source.is_explicit() {
595                    debug!(
596                        "Allowing managed Python interpreter at `{}` (in conflict with the `python-preference`) since it is from source: {source}",
597                        interpreter.sys_executable().display()
598                    );
599                    true
600                } else {
601                    debug!(
602                        "Ignoring Python interpreter at `{}`: only system interpreters allowed",
603                        interpreter.sys_executable().display()
604                    );
605                    false
606                }
607            }
608        }
609    }
610
611    /// Check the environment preference using both the discovery source and queried interpreter.
612    ///
613    /// Source filtering alone cannot determine whether an interpreter is in a virtual environment.
614    pub(crate) fn satisfies_environment_preference(
615        &self,
616        preference: EnvironmentPreference,
617    ) -> bool {
618        match (
619            preference,
620            // Conda environments are not conformant virtual environments but we treat them as such.
621            self.interpreter.is_virtualenv() || (matches!(self.source, PythonSource::CondaPrefix)),
622        ) {
623            (EnvironmentPreference::Any, _) => true,
624            (EnvironmentPreference::OnlyVirtual, true) => true,
625            (EnvironmentPreference::OnlyVirtual, false) => {
626                debug!(
627                    "Ignoring Python interpreter at `{}`: only virtual environments allowed",
628                    self.interpreter.sys_executable().display()
629                );
630                false
631            }
632            (EnvironmentPreference::ExplicitSystem, true) => true,
633            (EnvironmentPreference::ExplicitSystem, false) => {
634                if matches!(
635                    self.source,
636                    PythonSource::ProvidedPath | PythonSource::ParentInterpreter
637                ) {
638                    debug!(
639                        "Allowing explicitly requested system Python interpreter at `{}`",
640                        self.interpreter.sys_executable().display()
641                    );
642                    true
643                } else {
644                    debug!(
645                        "Ignoring Python interpreter at `{}`: system interpreter not explicitly requested",
646                        self.interpreter.sys_executable().display()
647                    );
648                    false
649                }
650            }
651            (EnvironmentPreference::OnlySystem, true) => {
652                debug!(
653                    "Ignoring Python interpreter at `{}`: system interpreter required",
654                    self.interpreter.sys_executable().display()
655                );
656                false
657            }
658            (EnvironmentPreference::OnlySystem, false) => true,
659        }
660    }
661
662    /// Check the version request after adjusting its defaults for this installation's source.
663    fn matches_version_request(&self, request: &VersionRequest) -> bool {
664        let request = request.clone().into_request_for_source(self.source);
665        self.interpreter.matches_version_request(&request)
666    }
667}
668
669/// Find a [`PythonEnvironment`] matching the given request and preference.
670///
671/// If looking for a Python interpreter to create a new environment, use [`PythonInstallation::find`]
672/// instead.
673pub fn find_environment(
674    request: &PythonRequest,
675    preference: EnvironmentPreference,
676    python_preference: PythonPreference,
677    python_arch: Option<PythonArchitecture>,
678    cache: &Cache,
679) -> Result<PythonEnvironment, Error> {
680    let installation =
681        match find_python_installation(request, preference, python_preference, python_arch, cache)?
682        {
683            Ok(installation) => installation,
684            Err(err) => {
685                return Err(
686                    EnvironmentNotFound::new(err.request, err.environment_preference).into(),
687                );
688            }
689        };
690    Ok(PythonEnvironment::from_interpreter(
691        installation.into_interpreter(),
692    ))
693}