Skip to content
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

Add --dry-run flag to uv pip install #1890

Closed
wants to merge 5 commits into from
Closed
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
10 changes: 9 additions & 1 deletion crates/uv/src/commands/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::process::ExitCode;
use std::time::Duration;
use std::{fmt::Display, process::ExitCode};

pub(crate) use clean::clean;
use distribution_types::InstalledMetadata;
Expand All @@ -8,6 +8,7 @@ pub(crate) use pip_compile::{extra_name_with_clap_error, pip_compile, Upgrade};
pub(crate) use pip_install::pip_install;
pub(crate) use pip_sync::pip_sync;
pub(crate) use pip_uninstall::pip_uninstall;
use uv_normalize::PackageName;
pub(crate) use venv::venv;

mod clean;
Expand Down Expand Up @@ -70,3 +71,10 @@ pub(super) struct ChangeEvent<T: InstalledMetadata> {
dist: T,
kind: ChangeEventKind,
}

#[derive(Debug)]
pub(super) struct DryRunEvent<T: Display> {
name: PackageName,
version: T,
kind: ChangeEventKind,
}
162 changes: 154 additions & 8 deletions crates/uv/src/commands/pip_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use std::collections::HashSet;
use std::fmt::Write;

use std::path::Path;
use std::time::Instant;

use anstream::eprint;
use anyhow::{anyhow, Context, Result};
Expand Down Expand Up @@ -40,7 +41,7 @@ use crate::commands::{elapsed, ChangeEvent, ChangeEventKind, ExitStatus};
use crate::printer::Printer;
use crate::requirements::{ExtrasSpecification, RequirementsSource, RequirementsSpecification};

use super::Upgrade;
use super::{DryRunEvent, Upgrade};

/// Install packages into the current environment.
#[allow(clippy::too_many_arguments)]
Expand All @@ -64,6 +65,7 @@ pub(crate) async fn pip_install(
exclude_newer: Option<DateTime<Utc>>,
cache: Cache,
mut printer: Printer,
dry_run: bool,
) -> Result<ExitStatus> {
let start = std::time::Instant::now();

Expand Down Expand Up @@ -136,6 +138,9 @@ pub(crate) async fn pip_install(
)
.dimmed()
)?;
if dry_run {
writeln!(printer, "Would make no changes")?;
}
return Ok(ExitStatus::Success);
}

Expand Down Expand Up @@ -276,6 +281,7 @@ pub(crate) async fn pip_install(
&cache,
&venv,
printer,
dry_run,
)
.await?;

Expand Down Expand Up @@ -489,6 +495,7 @@ async fn install(
cache: &Cache,
venv: &Virtualenv,
mut printer: Printer,
dry_run: bool,
) -> Result<(), Error> {
let start = std::time::Instant::now();

Expand All @@ -500,12 +507,7 @@ async fn install(
.map(ResolvedEditable::Built)
.collect::<Vec<_>>();

let Plan {
local,
remote,
reinstalls,
extraneous: _,
} = Planner::with_requirements(&requirements)
let plan = Planner::with_requirements(&requirements)
.with_editable_requirements(editables)
.build(
site_packages,
Expand All @@ -518,6 +520,17 @@ async fn install(
)
.context("Failed to determine installation plan")?;

if dry_run {
return report_dry_run(resolution, plan, start, printer);
}

let Plan {
local,
remote,
reinstalls,
extraneous: _,
} = plan;

// Nothing to do.
if remote.is_empty() && local.is_empty() && reinstalls.is_empty() {
let s = if resolution.len() == 1 { "" } else { "s" };
Expand All @@ -531,7 +544,6 @@ async fn install(
)
.dimmed()
)?;

return Ok(());
}

Expand Down Expand Up @@ -681,6 +693,140 @@ async fn install(
Ok(())
}

fn report_dry_run(
resolution: &Resolution,
plan: Plan,
start: Instant,
mut printer: Printer,
) -> Result<(), Error> {
let Plan {
local,
remote,
reinstalls,
extraneous: _,
} = plan;

// Nothing to do.
if remote.is_empty() && local.is_empty() && reinstalls.is_empty() {
let s = if resolution.len() == 1 { "" } else { "s" };
writeln!(
printer,
"{}",
format!(
"Audited {} in {}",
format!("{} package{}", resolution.len(), s).bold(),
elapsed(start.elapsed())
)
.dimmed()
)?;
writeln!(printer, "Would make no changes")?;
return Ok(());
}

// Map any registry-based requirements back to those returned by the resolver.
let remote = remote
.iter()
.map(|dist| {
resolution
.get(&dist.name)
.cloned()
.expect("Resolution should contain all packages")
})
.collect::<Vec<_>>();

// Download, build, and unzip any missing distributions.
let wheels = if remote.is_empty() {
vec![]
} else {
let s = if remote.len() == 1 { "" } else { "s" };
writeln!(
printer,
"{}",
format!(
"Would download {}",
format!("{} package{}", remote.len(), s).bold(),
)
.dimmed()
)?;
remote
};

// Remove any existing installations.
if !reinstalls.is_empty() {
let s = if reinstalls.len() == 1 { "" } else { "s" };
writeln!(
printer,
"{}",
format!(
"Would uninstall {}",
format!("{} package{}", reinstalls.len(), s).bold(),
)
.dimmed()
)?;
}

// Install the resolved distributions.
let installs = wheels.len() + local.len();

if installs > 0 {
let s = if installs == 1 { "" } else { "s" };
writeln!(
printer,
"{}",
format!(
"Would install {}",
format!("{} package{}", installs, s).bold(),
)
.dimmed()
)?;
}

for event in reinstalls
.into_iter()
.map(|distribution| DryRunEvent {
name: distribution.name().clone(),
version: distribution.version().to_string(),
kind: ChangeEventKind::Removed,
})
.chain(wheels.into_iter().map(|distribution| DryRunEvent {
name: distribution.name().clone(),
version: distribution.version().unwrap().to_string(),
kind: ChangeEventKind::Added,
}))
.chain(local.into_iter().map(|distribution| DryRunEvent {
name: distribution.name().clone(),
version: distribution.installed_version().to_string(),
kind: ChangeEventKind::Added,
Comment on lines +786 to +799
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a bit of a hack but the best I could come up without really digging around.

}))
.sorted_unstable_by(|a, b| a.name.cmp(&b.name).then_with(|| a.kind.cmp(&b.kind)))
{
match event.kind {
ChangeEventKind::Added => {
writeln!(
printer,
" {} {}{}{}",
"+".green(),
event.name.as_ref().bold(),
"==".dimmed(),
event.version.dimmed()
)?;
}
ChangeEventKind::Removed => {
writeln!(
printer,
" {} {}{}{}",
"-".red(),
event.name.as_ref().bold(),
"==".dimmed(),
event.version.dimmed()
)?;
}
}
}

Ok(())
}

/// Validate the installed packages in the virtual environment.
fn validate(resolution: &Resolution, venv: &Virtualenv, mut printer: Printer) -> Result<(), Error> {
let site_packages = SitePackages::from_executable(venv)?;
Expand Down
6 changes: 6 additions & 0 deletions crates/uv/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,11 @@ struct PipInstallArgs {
/// format (e.g., `2006-12-02`).
#[arg(long, value_parser = date_or_datetime, hide = true)]
exclude_newer: Option<DateTime<Utc>>,

/// Perform a dry run, i.e., don't actually install anything but resolve the dependencies and
/// print the resulting plan.
#[clap(long)]
dry_run: bool,
}

#[derive(Args)]
Expand Down Expand Up @@ -979,6 +984,7 @@ async fn run() -> Result<ExitStatus> {
args.exclude_newer,
cache,
printer,
args.dry_run,
)
.await
}
Expand Down
35 changes: 35 additions & 0 deletions crates/uv/tests/pip_install.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1012,3 +1012,38 @@ fn install_upgrade() {
"###
);
}

#[test]
fn dry_run_install() -> Result<(), Box<dyn std::error::Error>> {
let context = TestContext::new("3.12");

// Set up a requirements.txt with some packages
let requirements_txt = context.temp_dir.child("requirements.txt");
requirements_txt.touch()?;
requirements_txt.write_str("Flask==2.3.2")?;

// Run the installation command with our dry-run and strict flags set
uv_snapshot!(command(&context)
.arg("-r")
.arg("requirements.txt")
.arg("--dry-run")
.arg("--strict"), @r###"
success: true
exit_code: 0
----- stdout -----

----- stderr -----
Resolved 7 packages in [TIME]
Would install 7 packages
~ jinja2==3.1.2
~ itsdangerous==2.1.2
~ blinker==1.7.0
~ markupsafe==2.1.3
~ flask==2.3.2
~ werkzeug==3.0.1
~ click==8.1.7
"###
);

Ok(())
}