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 support for --dry-run mode in uv lock #7783

Merged
merged 9 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 6 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
5 changes: 5 additions & 0 deletions crates/uv-cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2779,6 +2779,11 @@ pub struct LockArgs {
help_heading = "Python options"
)]
pub python: Option<String>,

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

#[derive(Args)]
Expand Down
153 changes: 111 additions & 42 deletions crates/uv/src/commands/project/lock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,12 @@ impl LockResult {
}

/// Resolve the project requirements into a lockfile.
#[allow(clippy::fn_params_excessive_bools)]
pub(crate) async fn lock(
project_dir: &Path,
locked: bool,
frozen: bool,
dry_run: bool,
python: Option<String>,
settings: ResolverSettings,
python_preference: PythonPreference,
Expand All @@ -80,6 +82,12 @@ pub(crate) async fn lock(
cache: &Cache,
printer: Printer,
) -> anyhow::Result<ExitStatus> {
if dry_run && frozen {
warn_user_once!("`--dry_run` is a no-op when used with `--frozen`");
} else if dry_run && locked {
warn_user_once!("`--dry_run` is a no-op when used with `--locked`");
}

// Find the project requirements.
let workspace = Workspace::discover(project_dir, &DiscoveryOptions::default()).await?;

Expand All @@ -97,36 +105,85 @@ pub(crate) async fn lock(
.await?
.into_interpreter();

// Perform the lock operation.
match do_safe_lock(
locked,
frozen,
&workspace,
&interpreter,
settings.as_ref(),
Box::new(DefaultResolveLogger),
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await
{
Ok(lock) => {
if let LockResult::Changed(Some(previous), lock) = &lock {
report_upgrades(previous, lock, printer)?;
if dry_run {
let state = SharedState::default();

let existing = read(&workspace).await?;

let result = do_lock(
&workspace,
&interpreter,
existing,
dry_run,
settings.as_ref(),
&state,
Box::new(DefaultResolveLogger),
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await?;

match result {
LockResult::Changed(Some(previous), lock) => {
writeln!(
printer.stderr(),
"{}",
"Planned lockfile modifications:".bold()
)?;
report_upgrades(&previous, &lock, printer, true)?;
}
LockResult::Changed(None, _) => {
writeln!(
printer.stderr(),
"{}",
"Existing lockfile not detected".bold()
)?;
}
LockResult::Unchanged(_) => {
writeln!(
printer.stderr(),
"{}",
"No lockfile changes detected".bold()
)?;
}
Ok(ExitStatus::Success)
}
Err(ProjectError::Operation(pip::operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(err),
))) => {
let report = miette::Report::msg(format!("{err}")).context(err.header());
eprint!("{report:?}");
Ok(ExitStatus::Failure)

Ok(ExitStatus::Success)
} else {
// Perform the lock operation.
match do_safe_lock(
locked,
frozen,
&workspace,
&interpreter,
settings.as_ref(),
Box::new(DefaultResolveLogger),
connectivity,
concurrency,
native_tls,
cache,
printer,
)
.await
{
Ok(lock) => {
if let LockResult::Changed(Some(previous), lock) = &lock {
report_upgrades(previous, lock, printer, false)?;
}
Ok(ExitStatus::Success)
}
Err(ProjectError::Operation(pip::operations::Error::Resolve(
uv_resolver::ResolveError::NoSolution(err),
))) => {
let report = miette::Report::msg(format!("{err}")).context(err.header());
eprint!("{report:?}");
Ok(ExitStatus::Failure)
}
Err(err) => Err(err.into()),
}
Err(err) => Err(err.into()),
}
}

Expand Down Expand Up @@ -172,6 +229,7 @@ pub(super) async fn do_safe_lock(
workspace,
interpreter,
Some(existing),
false,
settings,
&state,
logger,
Expand All @@ -198,6 +256,7 @@ pub(super) async fn do_safe_lock(
workspace,
interpreter,
existing,
false,
settings,
&state,
logger,
Expand All @@ -223,6 +282,7 @@ async fn do_lock(
workspace: &Workspace,
interpreter: &Interpreter,
existing_lock: Option<Lock>,
dry_run: bool,
settings: ResolverSettingsRef<'_>,
state: &SharedState,
logger: Box<dyn ResolveLogger>,
Expand Down Expand Up @@ -445,6 +505,7 @@ async fn do_lock(
index_locations,
build_options,
upgrade,
dry_run,
&options,
&database,
printer,
Expand Down Expand Up @@ -619,6 +680,7 @@ impl ValidatedLock {
index_locations: &IndexLocations,
build_options: &BuildOptions,
upgrade: &Upgrade,
dry_run: bool,
options: &Options,
database: &DistributionDatabase<'_, Context>,
printer: Printer,
Expand Down Expand Up @@ -691,17 +753,19 @@ impl ValidatedLock {
};
}

match upgrade {
Upgrade::None => {}
Upgrade::All => {
// If the user specified `--upgrade`, then we can't use the existing lockfile.
debug!("Ignoring existing lockfile due to `--upgrade`");
return Ok(Self::Unusable(lock));
}
Upgrade::Packages(_) => {
// If the user specified `--upgrade-package`, then at best we can prefer some of
// the existing versions.
return Ok(Self::Preferable(lock));
if !dry_run {
Copy link
Contributor Author

@tfsingh tfsingh Sep 29, 2024

Choose a reason for hiding this comment

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

If we don't do this check, when we use --dry-run with -U the caller (do_lock) will indicate there was an update even if there wasn't one.

I'm not the happiest with this change as it pollutes the do_lock and validate APIs. That being said, I'm not sure of a better approach (doesn't make sense to include dry_run as a variant/member of one of the enums/structs passed in imo, they all seem to be used quite widely) — open to suggestions!

match upgrade {
Upgrade::None => {}
Upgrade::All => {
// If the user specified `--upgrade`, then we can't use the existing lockfile.
debug!("Ignoring existing lockfile due to `--upgrade`");
return Ok(Self::Unusable(lock));
}
Upgrade::Packages(_) => {
// If the user specified `--upgrade-package`, then at best we can prefer some of
// the existing versions.
return Ok(Self::Preferable(lock));
}
}
}

Expand Down Expand Up @@ -873,7 +937,12 @@ pub(crate) async fn read(workspace: &Workspace) -> Result<Option<Lock>, ProjectE
}

/// Reports on the versions that were upgraded in the new lockfile.
fn report_upgrades(existing_lock: &Lock, new_lock: &Lock, printer: Printer) -> anyhow::Result<()> {
fn report_upgrades(
existing_lock: &Lock,
new_lock: &Lock,
printer: Printer,
dry_run: bool,
) -> anyhow::Result<()> {
let existing_packages: FxHashMap<&PackageName, BTreeSet<&Version>> =
existing_lock.packages().iter().fold(
FxHashMap::with_capacity_and_hasher(existing_lock.packages().len(), FxBuildHasher),
Expand Down Expand Up @@ -917,7 +986,7 @@ fn report_upgrades(existing_lock: &Lock, new_lock: &Lock, printer: Printer) -> a
writeln!(
printer.stderr(),
"{} {name} {existing_versions} -> {new_versions}",
"Updated".green().bold()
if dry_run { "Update" } else { "Updated" }.green().bold()
)?;
}
}
Expand All @@ -930,7 +999,7 @@ fn report_upgrades(existing_lock: &Lock, new_lock: &Lock, printer: Printer) -> a
writeln!(
printer.stderr(),
"{} {name} {existing_versions}",
"Removed".red().bold()
if dry_run { "Remove" } else { "Removed" }.red().bold()
)?;
}
(None, Some(new_versions)) => {
Expand All @@ -942,7 +1011,7 @@ fn report_upgrades(existing_lock: &Lock, new_lock: &Lock, printer: Printer) -> a
writeln!(
printer.stderr(),
"{} {name} {new_versions}",
"Added".green().bold()
if dry_run { "Add" } else { "Added" }.green().bold()
)?;
}
(None, None) => {
Expand Down
1 change: 1 addition & 0 deletions crates/uv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1312,6 +1312,7 @@ async fn run_project(
project_dir,
args.locked,
args.frozen,
args.dry_run,
args.python,
args.settings,
globals.python_preference,
Expand Down
3 changes: 3 additions & 0 deletions crates/uv/src/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,7 @@ impl SyncSettings {
pub(crate) struct LockSettings {
pub(crate) locked: bool,
pub(crate) frozen: bool,
pub(crate) dry_run: bool,
pub(crate) python: Option<String>,
pub(crate) refresh: Refresh,
pub(crate) settings: ResolverSettings,
Expand All @@ -772,12 +773,14 @@ impl LockSettings {
build,
refresh,
python,
dry_run,
} = args;

Self {
locked,
frozen,
python,
dry_run,
refresh: Refresh::from(refresh),
settings: ResolverSettings::combine(resolver_options(resolver, build), filesystem),
}
Expand Down
Loading
Loading