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#[derive(Clone, Debug)]
29pub struct PythonInstallation {
30 pub(crate) source: PythonSource,
32 pub(crate) interpreter: Interpreter,
33}
34
35impl PythonInstallation {
36 pub(crate) fn new(source: PythonSource, interpreter: Interpreter) -> Self {
38 Self {
39 source,
40 interpreter,
41 }
42 }
43
44 #[must_use]
46 fn with_source(self, source: PythonSource) -> Self {
47 Self { source, ..self }
48 }
49
50 #[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 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 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 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 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 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 Error::MissingPython(..) => {}
203 Error::Discovery(ref err) if !err.is_critical() => {}
205 _ => return Err(err),
207 }
208
209 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 let download = match download {
233 Ok(Ok(download)) => Some(download),
234 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 return Err(err.into());
249 }
250 None
251 }
252 };
253
254 let Some(download) = download else {
255 debug_assert!(!downloads_enabled);
258 return Err(err);
259 };
260
261 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 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 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 pub fn source(&self) -> &PythonSource {
375 &self.source
376 }
377
378 pub fn key(&self) -> PythonInstallationKey {
379 self.interpreter.key()
380 }
381
382 pub fn python_version(&self) -> &Version {
384 self.interpreter.python_version()
385 }
386
387 pub fn implementation(&self) -> LenientImplementationName {
389 LenientImplementationName::from(self.interpreter.implementation_name())
390 }
391
392 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 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 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 pub fn arch(&self) -> Arch {
433 self.interpreter.arch()
434 }
435
436 pub fn libc(&self) -> Libc {
438 self.interpreter.libc()
439 }
440
441 pub fn os(&self) -> Os {
443 self.interpreter.os()
444 }
445
446 pub fn interpreter(&self) -> &Interpreter {
448 &self.interpreter
449 }
450
451 pub fn into_interpreter(self) -> Interpreter {
453 self.interpreter
454 }
455
456 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 if !interpreter
477 .implementation_name()
478 .eq_ignore_ascii_case("cpython")
479 {
480 return false;
481 }
482
483 true
484 }
485
486 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 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 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 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 pub(crate) fn satisfies_environment_preference(
615 &self,
616 preference: EnvironmentPreference,
617 ) -> bool {
618 match (
619 preference,
620 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 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
669pub 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}