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