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 if !self.satisfies_preference(&preference) {
83 return false;
84 }
85 true
86 }
87
88 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 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 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 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 Error::MissingPython(..) => {}
206 Error::Discovery(ref err) if !err.is_critical() => {}
208 _ => return Err(err),
210 }
211
212 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 let download = match download {
236 Ok(Ok(download)) => Some(download),
237 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 return Err(err.into());
252 }
253 None
254 }
255 };
256
257 let Some(download) = download else {
258 debug_assert!(!downloads_enabled);
261 return Err(err);
262 };
263
264 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 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 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 pub fn source(&self) -> &PythonSource {
378 &self.source
379 }
380
381 pub fn key(&self) -> PythonInstallationKey {
382 self.interpreter.key()
383 }
384
385 pub fn python_version(&self) -> &Version {
387 self.interpreter.python_version()
388 }
389
390 pub fn implementation(&self) -> LenientImplementationName {
392 LenientImplementationName::from(self.interpreter.implementation_name())
393 }
394
395 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 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 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 pub fn arch(&self) -> Arch {
436 self.interpreter.arch()
437 }
438
439 pub fn libc(&self) -> Libc {
441 self.interpreter.libc()
442 }
443
444 pub fn os(&self) -> Os {
446 self.interpreter.os()
447 }
448
449 pub fn interpreter(&self) -> &Interpreter {
451 &self.interpreter
452 }
453
454 pub fn into_interpreter(self) -> Interpreter {
456 self.interpreter
457 }
458
459 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 if !interpreter
480 .implementation_name()
481 .eq_ignore_ascii_case("cpython")
482 {
483 return false;
484 }
485
486 true
487 }
488
489 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 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 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 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 pub(crate) fn satisfies_environment_preference(
618 &self,
619 preference: EnvironmentPreference,
620 ) -> bool {
621 match (
622 preference,
623 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 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
672pub 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}