Skip to content

Automatically install Python version needed for tool #7827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions crates/uv-resolver/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Formatter;
use std::ops::{Bound, Deref};
use std::sync::Arc;

use indexmap::IndexSet;
use itertools::Itertools;
use pubgrub::{DefaultStringReporter, DerivationTree, Derived, External, Range, Reporter};
use rustc_hash::FxHashMap;

Expand Down Expand Up @@ -197,6 +199,55 @@ impl NoSolutionError {
pub fn header(&self) -> NoSolutionHeader {
NoSolutionHeader::new(self.markers.clone())
}

pub fn required_python_version(&self) -> Option<Version> {
let mut required_pythons = NoSolutionError::find_required_python_versions(&self.error);
required_pythons.sort();
// Return the largest required Python version
required_pythons.last().cloned()
}

/// Traverses a derivation tree to find required Python instances
fn find_required_python_versions(derivation_tree: &ErrorTree) -> Vec<Version> {
fn find(derivation_tree: &ErrorTree) -> Vec<Version> {
match derivation_tree {
DerivationTree::Derived(derived) => {
let mut result = find(derived.cause1.as_ref());
result.extend(find(derived.cause2.as_ref()));
result
}
DerivationTree::External(External::FromDependencyOf(
pkg_1,
ver_1,
pkg_2,
ver_2,
)) => match (pkg_1.deref(), pkg_2.deref()) {
(PubGrubPackageInner::Python(_), _) => {
if let Some((Bound::Included(version), _)) =
ver_1.iter().collect_vec().first()
{
vec![version.clone()]
} else {
Vec::new()
}
}
(_, PubGrubPackageInner::Python(_)) => {
if let Some((Bound::Included(version), _)) =
ver_2.iter().collect_vec().first()
{
vec![version.clone()]
} else {
Vec::new()
}
}
(_, _) => Vec::new(),
},
DerivationTree::External(_) => Vec::new(),
}
}

find(derivation_tree)
}
}

impl std::error::Error for NoSolutionError {}
Expand Down
64 changes: 56 additions & 8 deletions crates/uv/src/commands/tool/install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ use crate::commands::pip::loggers::{DefaultInstallLogger, DefaultResolveLogger};

use crate::commands::project::{
resolve_environment, resolve_names, sync_environment, update_environment,
EnvironmentSpecification,
EnvironmentSpecification, ProjectError,
};
use crate::commands::tool::common::remove_entrypoints;
use crate::commands::tool::Target;
use crate::commands::{pip, ExitStatus, SharedState};
use crate::commands::{reporters::PythonDownloadReporter, tool::common::install_executables};
use crate::commands::{ExitStatus, SharedState};
use crate::printer::Printer;
use crate::settings::ResolverInstallerSettings;

Expand Down Expand Up @@ -328,12 +328,13 @@ pub(crate) async fn install(
}

// Create a `RequirementsSpecification` from the resolved requirements, to avoid re-resolving.
let spec_requirements: Vec<UnresolvedRequirementSpecification> = requirements
.iter()
.cloned()
.map(UnresolvedRequirementSpecification::from)
.collect();
let spec = RequirementsSpecification {
requirements: requirements
.iter()
.cloned()
.map(UnresolvedRequirementSpecification::from)
.collect(),
requirements: spec_requirements.clone(),
..spec
};

Expand Down Expand Up @@ -380,7 +381,54 @@ pub(crate) async fn install(
&cache,
printer,
)
.await?;
.await;

let resolution = match resolution {
Ok(resolution) => resolution,
Err(err) => match err {
ProjectError::Operation(pip::operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(ref no_solution_err),
)) => {
let (None, Some(version)) =
(python_request, no_solution_err.required_python_version())
else {
return Err(err.into());
};

let interpreter = PythonInstallation::find_or_download(
Some(&PythonRequest::parse(version.to_string().as_str())),
EnvironmentPreference::OnlySystem,
python_preference,
python_downloads,
&client_builder,
&cache,
Some(&reporter),
)
.await?
.into_interpreter();

let new_spec = RequirementsSpecification {
requirements: spec_requirements,
..RequirementsSpecification::default()
};

resolve_environment(
EnvironmentSpecification::from(new_spec),
&interpreter,
settings.as_ref().into(),
&state,
Box::new(DefaultResolveLogger),
connectivity,
concurrency,
native_tls,
&cache,
printer,
)
.await?
}
_ => return Err(err.into()),
},
};

let environment = installed_tools.create_environment(&from.name, interpreter)?;

Expand Down
22 changes: 22 additions & 0 deletions crates/uv/tests/tool_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3007,3 +3007,25 @@ fn tool_install_at_latest_upgrade() {
"###);
});
}

#[test]
fn tool_install_python() {
let context = TestContext::new("3.8");
let tool_dir = context.temp_dir.child("tools");
let bin_dir = context.temp_dir.child("bin");

uv_snapshot!(context.filters(), context.tool_install()
.arg("posting")
.arg("--python")
.arg("3.8")
.env("UV_TOOL_DIR", tool_dir.as_os_str())
.env("XDG_BIN_HOME", bin_dir.as_os_str())
.env("PATH", bin_dir.as_os_str()), @r###"
success: true
exit_code: 0
----- stdout -----

----- stderr -----

"###);
}
Loading