use reqwest_retry::policies::ExponentialBackoff;
use tracing::{debug, info};
use uv_fs::Simplified;
use uv_warnings::warn_user;
use uv_cache::Cache;
use uv_client::{BaseClient, BaseClientBuilder};
use uv_pep440::Version;
use uv_platform::{Arch, Libc, Os};
use crate::Error;
use crate::MissingPythonHint;
use crate::discovery::find_best_python_installation;
use crate::discovery::find_python_installation;
use uv_python_interpreter::{EnvironmentNotFound, Interpreter, PythonEnvironment};
use uv_python_managed::downloads::{
DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList, Reporter,
};
use uv_python_managed::{ManagedPythonInstallation, ManagedPythonInstallations};
use uv_python_types::PythonInstallationKey;
use uv_python_types::{
EnvironmentPreference, ImplementationName, LenientImplementationName, PythonArchitecture,
PythonDownloadMirrors, PythonDownloadRequest, PythonDownloads, PythonPreference, PythonRequest,
PythonSource, PythonVersion, VersionRequest,
};
#[derive(Clone, Debug)]
pub struct PythonInstallation {
pub(crate) source: PythonSource,
pub(crate) interpreter: Interpreter,
}
impl PythonInstallation {
pub(crate) fn new(source: PythonSource, interpreter: Interpreter) -> Self {
Self {
source,
interpreter,
}
}
#[must_use]
fn with_source(self, source: PythonSource) -> Self {
Self { source, ..self }
}
#[must_use]
pub(crate) fn maybe_with_test_source(self) -> Self {
if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok()
&& self.is_managed()
{
self.with_source(PythonSource::Managed)
} else {
self
}
}
pub(crate) fn satisfies_preferences(
&self,
version: &VersionRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
) -> bool {
if !self.satisfies_environment_preference(environments) {
return false;
}
if !self.matches_version_request(version) {
debug!(
"Skipping interpreter at `{}` from {}: does not satisfy request `{version}`",
self.interpreter.sys_executable().user_display(),
self.source,
);
return false;
}
self.satisfies_preference(&preference)
}
pub fn find(
request: &PythonRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
arch: Option<PythonArchitecture>,
download_list: &ManagedPythonDownloadList,
cache: &Cache,
) -> Result<Self, Error> {
let installation = Self::find_existing(request, environments, preference, arch, cache)?;
installation.warn_if_outdated_prerelease(request, download_list);
Ok(installation)
}
pub fn find_existing(
request: &PythonRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
arch: Option<PythonArchitecture>,
cache: &Cache,
) -> Result<Self, Error> {
Ok(find_python_installation(
request,
environments,
preference,
arch,
cache,
)??)
}
pub async fn find_best(
request: &PythonRequest,
environments: EnvironmentPreference,
preference: PythonPreference,
arch: Option<PythonArchitecture>,
python_downloads: PythonDownloads,
client_builder: &BaseClientBuilder<'_>,
cache: &Cache,
reporter: Option<&dyn Reporter>,
mirrors: PythonDownloadMirrors<'_>,
python_downloads_json_url: Option<&str>,
) -> Result<Self, Error> {
let downloads_enabled = preference.allows_managed()
&& python_downloads.is_automatic()
&& !client_builder.is_offline();
let installation = find_best_python_installation(
request,
environments,
preference,
arch,
downloads_enabled,
client_builder,
cache,
reporter,
mirrors,
python_downloads_json_url,
)
.await?;
installation
.download_and_warn_if_outdated_prerelease(
request,
client_builder,
cache,
python_downloads_json_url,
)
.await?;
Ok(installation)
}
pub async fn find_or_download(
request: Option<&PythonRequest>,
environments: EnvironmentPreference,
preference: PythonPreference,
arch: Option<PythonArchitecture>,
python_downloads: PythonDownloads,
client_builder: &BaseClientBuilder<'_>,
cache: &Cache,
reporter: Option<&dyn Reporter>,
mirrors: PythonDownloadMirrors<'_>,
python_downloads_json_url: Option<&str>,
) -> Result<Self, Error> {
let request = request.unwrap_or(&PythonRequest::Default);
let err = match Self::find_existing(request, environments, preference, arch, cache) {
Ok(installation) => {
installation
.download_and_warn_if_outdated_prerelease(
request,
client_builder,
cache,
python_downloads_json_url,
)
.await?;
return Ok(installation);
}
Err(err) => err,
};
match err {
Error::MissingPython(..) => {}
Error::Discovery(ref err) if !err.is_critical() => {}
_ => return Err(err),
}
let Some(download_request) = PythonDownloadRequest::from_request(request) else {
return Err(err);
};
let download_list =
ManagedPythonDownloadList::new(client_builder, cache, python_downloads_json_url)
.await?;
let downloads_enabled = preference.allows_managed()
&& python_downloads.is_automatic()
&& !client_builder.is_offline();
let download = download_request
.clone()
.with_default_arch(arch.map(PythonArchitecture::into_inner))
.fill()
.map_err(uv_python_managed::downloads::Error::from)
.map(|request| download_list.find(&request));
let download = match download {
Ok(Ok(download)) => Some(download),
Ok(Err(uv_python_managed::downloads::Error::NoDownloadFound(_))) => {
if downloads_enabled {
debug!("No downloads are available for {request}");
if matches!(request, PythonRequest::Default | PythonRequest::Any) {
return Err(err);
}
return Err(err.with_hint(MissingPythonHint::RequiresUpdate));
}
None
}
Err(err) | Ok(Err(err)) => {
if downloads_enabled {
return Err(err.into());
}
None
}
};
let Some(download) = download else {
debug_assert!(!downloads_enabled);
return Err(err);
};
if !downloads_enabled {
match python_downloads {
PythonDownloads::Automatic => {}
PythonDownloads::Manual => {
return Err(err.with_hint(MissingPythonHint::DownloadsManual(request.clone())));
}
PythonDownloads::Never => {
return Err(err.with_hint(MissingPythonHint::DownloadsNever(request.clone())));
}
}
match preference {
PythonPreference::OnlySystem => {
return Err(
err.with_hint(MissingPythonHint::PreferenceOnlySystem(request.clone()))
);
}
PythonPreference::Managed
| PythonPreference::OnlyManaged
| PythonPreference::System => {}
}
if client_builder.is_offline() {
return Err(err.with_hint(MissingPythonHint::Offline(request.clone())));
}
return Err(err);
}
let retry_policy = client_builder.retry_policy();
let download_client = client_builder.clone().retries(0).build()?;
let installation = Self::fetch(
download,
&download_client,
&retry_policy,
cache,
reporter,
mirrors,
)
.await?;
installation.warn_if_outdated_prerelease(request, &download_list);
Ok(installation)
}
pub(crate) async fn fetch(
download: &ManagedPythonDownload,
client: &BaseClient,
retry_policy: &ExponentialBackoff,
cache: &Cache,
reporter: Option<&dyn Reporter>,
mirrors: PythonDownloadMirrors<'_>,
) -> Result<Self, Error> {
let installations = ManagedPythonInstallations::from_settings(None)?.init()?;
let installations_dir = installations.root();
let scratch_dir = installations.scratch();
let _lock = installations.lock().await?;
info!("Fetching requested Python...");
let result = download
.fetch_with_retry(
client,
retry_policy,
installations_dir,
&scratch_dir,
false,
mirrors,
reporter,
)
.await?;
let path = match result {
DownloadResult::AlreadyAvailable(path) => path,
DownloadResult::Fetched(path) => path,
};
let installed = ManagedPythonInstallation::new(path, download)?;
installed.ensure_externally_managed().await?;
installed.ensure_sysconfig_patched().await?;
installed.ensure_canonical_executables().await?;
installed.ensure_build_file().await?;
let minor_version = installed.minor_version_key();
let highest_patch = installations
.find_all()?
.filter(|installation| installation.minor_version_key() == minor_version)
.filter_map(|installation| installation.version().patch())
.fold(0, std::cmp::max);
if installed
.version()
.patch()
.is_some_and(|p| p >= highest_patch)
{
installed.ensure_minor_version_link().await?;
}
if let Err(e) = installed.ensure_dylib_patched() {
e.warn_user(&installed);
}
Ok(Self {
source: PythonSource::Managed,
interpreter: Interpreter::query(installed.executable(false), cache)?,
})
}
pub fn source(&self) -> &PythonSource {
&self.source
}
pub fn key(&self) -> PythonInstallationKey {
self.interpreter.key()
}
pub fn python_version(&self) -> &Version {
self.interpreter.python_version()
}
pub fn implementation(&self) -> LenientImplementationName {
LenientImplementationName::from(self.interpreter.implementation_name())
}
pub(crate) fn is_managed(&self) -> bool {
if self.source.is_managed() {
return true;
}
if let Ok(test_managed) =
std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED)
{
return test_managed.split_ascii_whitespace().any(|item| {
let version = <PythonVersion as std::str::FromStr>::from_str(item).expect(
"`UV_INTERNAL__TEST_PYTHON_MANAGED` items should be valid Python versions",
);
if version.patch().is_some() {
version.version() == self.interpreter.python_version()
} else {
(version.major(), version.minor()) == self.interpreter.python_tuple()
}
});
}
ManagedPythonInstallations::from_settings(None)
.is_ok_and(|installations| installations.contains(&self.interpreter))
}
pub(crate) fn is_alternative_implementation(&self) -> bool {
!matches!(
self.implementation(),
LenientImplementationName::Known(ImplementationName::CPython)
) || self.os().is_emscripten()
}
pub fn arch(&self) -> Arch {
self.interpreter.arch()
}
pub fn libc(&self) -> Libc {
self.interpreter.libc()
}
pub fn os(&self) -> Os {
self.interpreter.os()
}
pub fn interpreter(&self) -> &Interpreter {
&self.interpreter
}
pub fn into_interpreter(self) -> Interpreter {
self.interpreter
}
fn should_check_outdated_prerelease_warning(&self, request: &PythonRequest) -> bool {
if request.allows_prereleases() {
return false;
}
let interpreter = self.interpreter();
if interpreter.python_version().pre().is_none() {
return false;
}
if !self.is_managed() {
return false;
}
if !interpreter
.implementation_name()
.eq_ignore_ascii_case("cpython")
{
return false;
}
true
}
fn warn_if_outdated_prerelease(
&self,
request: &PythonRequest,
download_list: &ManagedPythonDownloadList,
) {
if !self.should_check_outdated_prerelease_warning(request) {
return;
}
let interpreter = self.interpreter();
let version = interpreter.python_version();
let release = version.only_release();
let Ok(download_request) = PythonDownloadRequest::try_from(&interpreter.key()) else {
return;
};
let download_request = download_request.with_prereleases(false);
let has_stable_download = {
let mut downloads = download_list.iter_matching(&download_request);
downloads.any(|download| {
let download_version = download.key().version().into_version();
download_version.pre().is_none() && download_version.only_release() >= release
})
};
if !has_stable_download {
return;
}
if let Some(upgrade_request) = download_request
.unset_defaults()
.without_patch()
.simplified_display()
{
warn_user!(
"You're using a pre-release version of Python ({}) but a stable version is available. Use `uv python upgrade {}` to upgrade.",
version,
upgrade_request
);
} else {
warn_user!(
"You're using a pre-release version of Python ({}) but a stable version is available. Run `uv python upgrade` to update your managed interpreters.",
version,
);
}
}
pub async fn download_and_warn_if_outdated_prerelease(
&self,
request: &PythonRequest,
client_builder: &BaseClientBuilder<'_>,
cache: &Cache,
python_downloads_json_url: Option<&str>,
) -> Result<(), Error> {
if !self.should_check_outdated_prerelease_warning(request) {
return Ok(());
}
let download_list =
ManagedPythonDownloadList::new(client_builder, cache, python_downloads_json_url)
.await?;
self.warn_if_outdated_prerelease(request, &download_list);
Ok(())
}
pub fn satisfies_preference(&self, preference: &PythonPreference) -> bool {
let source = self.source;
let interpreter = &self.interpreter;
match preference {
PythonPreference::OnlyManaged => {
if self.is_managed() {
true
} else if source.is_explicit() {
debug!(
"Allowing unmanaged Python interpreter at `{}` (in conflict with the `python-preference`) since it is from source: {source}",
interpreter.sys_executable().display()
);
true
} else {
debug!(
"Ignoring Python interpreter at `{}`: only managed interpreters allowed",
interpreter.sys_executable().display()
);
false
}
}
PythonPreference::Managed | PythonPreference::System => true,
PythonPreference::OnlySystem => {
if !self.is_managed() {
true
} else if source.is_explicit() {
debug!(
"Allowing managed Python interpreter at `{}` (in conflict with the `python-preference`) since it is from source: {source}",
interpreter.sys_executable().display()
);
true
} else {
debug!(
"Ignoring Python interpreter at `{}`: only system interpreters allowed",
interpreter.sys_executable().display()
);
false
}
}
}
}
pub(crate) fn satisfies_environment_preference(
&self,
preference: EnvironmentPreference,
) -> bool {
match (
preference,
self.interpreter.is_virtualenv() || (matches!(self.source, PythonSource::CondaPrefix)),
) {
(EnvironmentPreference::Any, _) => true,
(EnvironmentPreference::OnlyVirtual, true) => true,
(EnvironmentPreference::OnlyVirtual, false) => {
debug!(
"Ignoring Python interpreter at `{}`: only virtual environments allowed",
self.interpreter.sys_executable().display()
);
false
}
(EnvironmentPreference::ExplicitSystem, true) => true,
(EnvironmentPreference::ExplicitSystem, false) => {
if matches!(
self.source,
PythonSource::ProvidedPath | PythonSource::ParentInterpreter
) {
debug!(
"Allowing explicitly requested system Python interpreter at `{}`",
self.interpreter.sys_executable().display()
);
true
} else {
debug!(
"Ignoring Python interpreter at `{}`: system interpreter not explicitly requested",
self.interpreter.sys_executable().display()
);
false
}
}
(EnvironmentPreference::OnlySystem, true) => {
debug!(
"Ignoring Python interpreter at `{}`: system interpreter required",
self.interpreter.sys_executable().display()
);
false
}
(EnvironmentPreference::OnlySystem, false) => true,
}
}
fn matches_version_request(&self, request: &VersionRequest) -> bool {
let request = request.clone().into_request_for_source(self.source);
self.interpreter.matches_version_request(&request)
}
}
pub fn find_environment(
request: &PythonRequest,
preference: EnvironmentPreference,
python_preference: PythonPreference,
python_arch: Option<PythonArchitecture>,
cache: &Cache,
) -> Result<PythonEnvironment, Error> {
let installation =
match find_python_installation(request, preference, python_preference, python_arch, cache)?
{
Ok(installation) => installation,
Err(err) => {
return Err(
EnvironmentNotFound::new(err.request, err.environment_preference).into(),
);
}
};
Ok(PythonEnvironment::from_interpreter(
installation.into_interpreter(),
))
}