Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions crates/uv-dispatch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,10 @@ impl BuildContext for BuildDispatch<'_> {
self.build_options
}

fn build_isolation(&self) -> BuildIsolation<'_> {
self.build_isolation
}

fn config_settings(&self) -> &ConfigSettings {
self.config_settings
}
Expand Down
74 changes: 74 additions & 0 deletions crates/uv-installer/src/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use uv_distribution_types::{
RequirementSource, Resolution, ResolvedDist, SourceDist,
};
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_platform_tags::{IncompatibleTag, TagCompatibility, Tags};
use uv_pypi_types::VerbatimParsedUrl;
use uv_python::PythonEnvironment;
Expand Down Expand Up @@ -658,3 +659,76 @@ pub struct Plan {
/// _not_ necessary to satisfy the requirements.
pub extraneous: Vec<InstalledDist>,
}

impl Plan {
/// Returns `true` if the plan is empty.
pub fn is_empty(&self) -> bool {
self.cached.is_empty()
&& self.remote.is_empty()
&& self.reinstalls.is_empty()
&& self.extraneous.is_empty()
}

/// Partition the remote distributions based on a predicate function.
///
/// Returns a tuple of plans, where the first plan contains the remote distributions that match
/// the predicate, and the second plan contains those that do not.
///
/// Any extraneous and cached distributions will be returned in the first plan, while the second
/// plan will contain any `false` matches from the remote distributions, along with any
/// reinstalls for those distributions.
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The behavior here is a bit subtle. I tried to document it clearly.

pub fn partition<F>(self, mut f: F) -> (Self, Self)
where
F: FnMut(&PackageName) -> bool,
{
let Self {
cached,
remote,
reinstalls,
extraneous,
} = self;

// Partition the remote distributions based on the predicate function.
let (left_remote, right_remote) = remote
.into_iter()
.partition::<Vec<_>, _>(|dist| f(dist.name()));

// If any remote distributions are not matched, but are already installed, ensure that
// they're uninstalled as part of the right plan. (Uninstalling them as part of the left
// plan risks uninstalling them from the environment _prior_ to the replacement being built.)
let (left_reinstalls, right_reinstalls) = reinstalls
.into_iter()
.partition::<Vec<_>, _>(|dist| !right_remote.iter().any(|d| d.name() == dist.name()));

// If the right plan is non-empty, then remove extraneous distributions as part of the
// right plan, so they're present until the very end. Otherwise, we risk removing extraneous
// packages that are actually build dependencies.
let (left_extraneous, right_extraneous) = if right_remote.is_empty() {
(extraneous, vec![])
} else {
(vec![], extraneous)
};

// Always include the cached distributions in the left plan.
let (left_cached, right_cached) = (cached, vec![]);

// Include all cached and extraneous distributions in the left plan.
let left_plan = Self {
cached: left_cached,
remote: left_remote,
reinstalls: left_reinstalls,
extraneous: left_extraneous,
};

// The right plan will only contain the remote distributions that did not match the predicate,
// along with any reinstalls for those distributions.
let right_plan = Self {
cached: right_cached,
remote: right_remote,
reinstalls: right_reinstalls,
extraneous: right_extraneous,
};

(left_plan, right_plan)
}
}
5 changes: 4 additions & 1 deletion crates/uv-types/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use uv_pep508::PackageName;
use uv_python::{Interpreter, PythonEnvironment};
use uv_workspace::WorkspaceCache;

use crate::BuildArena;
use crate::{BuildArena, BuildIsolation};

/// Avoids cyclic crate dependencies between resolver, installer and builder.
///
Expand Down Expand Up @@ -87,6 +87,9 @@ pub trait BuildContext {
/// This method exists to avoid fetching source distributions if we know we can't build them.
fn build_options(&self) -> &BuildOptions;

/// The isolation mode used for building source distributions.
fn build_isolation(&self) -> BuildIsolation<'_>;

/// The [`ConfigSettings`] used to build distributions.
fn config_settings(&self) -> &ConfigSettings;

Expand Down
25 changes: 22 additions & 3 deletions crates/uv/src/commands/pip/loggers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,13 @@ pub(crate) trait InstallLogger {
fn on_audit(&self, count: usize, start: std::time::Instant, printer: Printer) -> fmt::Result;

/// Log the completion of the preparation phase.
fn on_prepare(&self, count: usize, start: std::time::Instant, printer: Printer) -> fmt::Result;
fn on_prepare(
&self,
count: usize,
suffix: Option<&str>,
start: std::time::Instant,
printer: Printer,
) -> fmt::Result;

/// Log the completion of the uninstallation phase.
fn on_uninstall(
Expand Down Expand Up @@ -64,14 +70,25 @@ impl InstallLogger for DefaultInstallLogger {
}
}

fn on_prepare(&self, count: usize, start: std::time::Instant, printer: Printer) -> fmt::Result {
fn on_prepare(
&self,
count: usize,
suffix: Option<&str>,
start: std::time::Instant,
printer: Printer,
) -> fmt::Result {
let s = if count == 1 { "" } else { "s" };
writeln!(
printer.stderr(),
"{}",
format!(
"Prepared {} {}",
format!("{count} package{s}").bold(),
if let Some(suffix) = suffix {
format!("{count} package{s} {suffix}")
} else {
format!("{count} package{s}")
}
.bold(),
format!("in {}", elapsed(start.elapsed())).dimmed()
)
.dimmed()
Expand Down Expand Up @@ -192,6 +209,7 @@ impl InstallLogger for SummaryInstallLogger {
fn on_prepare(
&self,
_count: usize,
_suffix: Option<&str>,
_start: std::time::Instant,
_printer: Printer,
) -> fmt::Result {
Expand Down Expand Up @@ -262,6 +280,7 @@ impl InstallLogger for UpgradeInstallLogger {
fn on_prepare(
&self,
_count: usize,
_suffix: Option<&str>,
_start: std::time::Instant,
_printer: Printer,
) -> fmt::Result {
Expand Down
140 changes: 128 additions & 12 deletions crates/uv/src/commands/pip/operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,132 @@ pub(crate) async fn install(
return Ok(Changelog::default());
}

// Partition into two sets: those that require build isolation, and those that disable it. This
// is effectively a heuristic to make `--no-build-isolation` work "more often" by way of giving
// `--no-build-isolation` packages "access" to the rest of the environment.
let (isolated_phase, shared_phase) = Plan {
cached,
remote,
reinstalls,
extraneous,
}
.partition(|name| build_dispatch.build_isolation().is_isolated(Some(name)));

let has_isolated_phase = !isolated_phase.is_empty();
let has_shared_phase = !shared_phase.is_empty();

let mut installs = vec![];
let mut uninstalls = vec![];

// Execute the isolated-build phase.
if has_isolated_phase {
let (isolated_installs, isolated_uninstalls) = execute_plan(
isolated_phase,
None,
resolution,
build_options,
link_mode,
hasher,
tags,
client,
in_flight,
concurrency,
build_dispatch,
cache,
venv,
logger.as_ref(),
installer_metadata,
printer,
preview,
)
.await?;
installs.extend(isolated_installs);
uninstalls.extend(isolated_uninstalls);
}

if has_shared_phase {
let (shared_installs, shared_uninstalls) = execute_plan(
shared_phase,
if has_isolated_phase {
Some(InstallPhase::Shared)
} else {
None
},
resolution,
build_options,
link_mode,
hasher,
tags,
client,
in_flight,
concurrency,
build_dispatch,
cache,
venv,
logger.as_ref(),
installer_metadata,
printer,
preview,
)
.await?;
installs.extend(shared_installs);
uninstalls.extend(shared_uninstalls);
}

if compile {
compile_bytecode(venv, &concurrency, cache, printer).await?;
}

// Construct a summary of the changes made to the environment.
let changelog = Changelog::new(installs, uninstalls);

// Notify the user of any environment modifications.
logger.on_complete(&changelog, printer)?;

Ok(changelog)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InstallPhase {
/// A dedicated phase for building and installing packages with build-isolation disabled.
Shared,
}

impl InstallPhase {
fn label(self) -> &'static str {
match self {
Self::Shared => "without build isolation",
}
}
}

/// Execute a [`Plan`] to install distributions into a Python environment.
async fn execute_plan(
plan: Plan,
phase: Option<InstallPhase>,
resolution: &Resolution,
build_options: &BuildOptions,
link_mode: LinkMode,
hasher: &HashStrategy,
tags: &Tags,
client: &RegistryClient,
in_flight: &InFlight,
concurrency: Concurrency,
build_dispatch: &BuildDispatch<'_>,
cache: &Cache,
venv: &PythonEnvironment,
logger: &dyn InstallLogger,
installer_metadata: bool,
printer: Printer,
preview: uv_configuration::Preview,
) -> Result<(Vec<CachedDist>, Vec<InstalledDist>), Error> {
let Plan {
cached,
remote,
reinstalls,
extraneous,
} = plan;

// Download, build, and unzip any missing distributions.
let wheels = if remote.is_empty() {
vec![]
Expand All @@ -523,7 +649,7 @@ pub(crate) async fn install(
.prepare(remote.clone(), in_flight, resolution)
.await?;

logger.on_prepare(wheels.len(), start, printer)?;
logger.on_prepare(wheels.len(), phase.map(InstallPhase::label), start, printer)?;

wheels
};
Expand Down Expand Up @@ -587,17 +713,7 @@ pub(crate) async fn install(
logger.on_install(installs.len(), start, printer)?;
}

if compile {
compile_bytecode(venv, &concurrency, cache, printer).await?;
}

// Construct a summary of the changes made to the environment.
let changelog = Changelog::new(installs, uninstalls);

// Notify the user of any environment modifications.
logger.on_complete(&changelog, printer)?;

Ok(changelog)
Ok((installs, uninstalls))
}

/// Display a message about the interpreter that was selected for the operation.
Expand Down
10 changes: 6 additions & 4 deletions crates/uv/tests/it/pip_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8693,18 +8693,20 @@ fn install_build_isolation_package() -> Result<()> {
uv_snapshot!(context.filters(), context.pip_install()
.arg("--no-build-isolation-package")
.arg("iniconfig")
.arg(package.path()), @r###"
.arg(package.path()), @r"
success: true
exit_code: 0
----- stdout -----

----- stderr -----
Resolved 2 packages in [TIME]
Prepared 2 packages in [TIME]
Installed 2 packages in [TIME]
Prepared 1 package in [TIME]
Installed 1 package in [TIME]
Prepared 1 package without build isolation in [TIME]
Installed 1 package in [TIME]
+ iniconfig==2.0.0 (from https://files.pythonhosted.org/packages/d7/4b/cbd8e699e64a6f16ca3a8220661b5f83792b3017d0f79807cb8708d33913/iniconfig-2.0.0.tar.gz)
+ project==0.1.0 (from file://[TEMP_DIR]/project)
"###);
");

Ok(())
}
Expand Down
Loading
Loading