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

feat: error on non-existent extra from lock file #10925

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
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: 10 additions & 0 deletions crates/uv-resolver/src/lock/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,11 @@ impl Lock {
})
}

/// Returns the package whose name matches [`PackageName`].
pub fn find_package(&self, name: &PackageName) -> Option<&Package> {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

We could make it find_packages instead to iterate once and retrieve the packages we are interested in.

self.packages.iter().find(|package| package.name() == name)
}

/// Returns the supported environments that were used to generate this
/// lock.
///
Expand Down Expand Up @@ -2585,6 +2590,11 @@ impl Package {
fn is_dynamic(&self) -> bool {
self.id.version.is_none()
}

/// Returns `true` if the package contains the [`ExtraName`].
pub fn contains_extra(&self, name: &ExtraName) -> bool {
self.optional_dependencies.contains_key(name)
}
}

/// Attempts to construct a `VerbatimUrl` from the given normalized `Path`.
Expand Down
50 changes: 50 additions & 0 deletions crates/uv/src/commands/project/install_target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ use std::borrow::Cow;
use std::path::Path;
use std::str::FromStr;

use crate::commands::project::ProjectError;
use itertools::Either;
use uv_configuration::ExtrasSpecification;
use uv_distribution_types::Index;
use uv_normalize::PackageName;
use uv_pypi_types::{LenientRequirement, VerbatimParsedUrl};
Expand Down Expand Up @@ -230,4 +232,52 @@ impl<'lock> InstallTarget<'lock> {
),
}
}

/// Validate the extras requested by the [`ExtrasSpecification`].
#[allow(clippy::result_large_err)]
pub(crate) fn validate_extras(self, extras: &ExtrasSpecification) -> Result<(), ProjectError> {
let extras = match extras {
ExtrasSpecification::Some(extras) => {
if extras.is_empty() {
return Ok(());
}
extras
}
ExtrasSpecification::Exclude(extras) => {
if extras.is_empty() {
return Ok(());
}
&Vec::from_iter(extras.clone())
}
_ => return Ok(()),
};

match self {
Self::Project { lock, .. }
| Self::Workspace { lock, .. }
| Self::NonProjectWorkspace { lock, .. } => {
let member_packages: Vec<&Package> = self
.roots()
.filter_map(|package| lock.find_package(package))
.collect();

for extra in extras {
if !member_packages
.iter()
.any(|package| package.contains_extra(extra))
{
return match self {
Self::Project { .. } => {
Err(ProjectError::MissingExtraProject(extra.clone()))
}
_ => Err(ProjectError::MissingExtraWorkspace(extra.clone())),
};
}
}
}
Self::Script { .. } => return Err(ProjectError::MissingExtraScript(extras[0].clone())),
}

Ok(())
}
}
11 changes: 10 additions & 1 deletion crates/uv/src/commands/project/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use uv_distribution_types::{
use uv_fs::{Simplified, CWD};
use uv_git::ResolvedRepositoryReference;
use uv_installer::{SatisfiesResult, SitePackages};
use uv_normalize::{GroupName, PackageName, DEV_DEPENDENCIES};
use uv_normalize::{ExtraName, GroupName, PackageName, DEV_DEPENDENCIES};
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::MarkerTreeContents;
use uv_pypi_types::{ConflictPackage, ConflictSet, Conflicts, Requirement};
Expand Down Expand Up @@ -149,6 +149,15 @@ pub(crate) enum ProjectError {
#[error("Default group `{0}` (from `tool.uv.default-groups`) is not defined in the project's `dependency-group` table")]
MissingDefaultGroup(GroupName),

#[error("Extra `{0}` is not defined in the project's `optional-dependencies` table")]
MissingExtraProject(ExtraName),

#[error("Extra `{0}` is not defined in any project's `optional-dependencies` table")]
MissingExtraWorkspace(ExtraName),
Comment on lines +152 to +156
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Wording could probably be adapted here, as the check happens at lock file level, but not sure exactly how we would want to phrase this.


#[error("PEP 723 scripts do not support optional dependencies, but extra `{0}` was specified")]
MissingExtraScript(ExtraName),

#[error("Supported environments must be disjoint, but the following markers overlap: `{0}` and `{1}`.\n\n{hint}{colon} replace `{1}` with `{2}`.", hint = "hint".bold().cyan(), colon = ":".bold())]
OverlappingMarkers(String, String, String),

Expand Down
2 changes: 2 additions & 0 deletions crates/uv/src/commands/project/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ pub(super) async fn do_sync(
printer: Printer,
preview: PreviewMode,
) -> Result<(), ProjectError> {
target.validate_extras(extras)?;

// Use isolated state for universal resolution. When resolving, we don't enforce that the
// prioritized distributions match the current platform. So if we lock here, then try to
// install from the same state, and we end up performing a resolution during the sync (i.e.,
Expand Down
15 changes: 11 additions & 4 deletions crates/uv/tests/it/lock_conflict.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4404,11 +4404,18 @@ conflicts = [
"#,
)?;

// I believe there are multiple valid solutions here, but the main
// thing is that `x2` should _not_ activate the `idna==3.4` dependency
// in `proxy1`. The `--extra=x2` should be a no-op, since there is no
// `x2` extra in the top level `pyproject.toml`.
// Error out, as x2 extra is only on the child.
uv_snapshot!(context.filters(), context.sync().arg("--extra=x2"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 7 packages in [TIME]
error: Extra `x2` is not defined in the project's `optional-dependencies` table
"###);

uv_snapshot!(context.filters(), context.sync(), @r###"
success: true
exit_code: 0
----- stdout -----
Expand Down
230 changes: 229 additions & 1 deletion crates/uv/tests/it/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2402,6 +2402,101 @@ fn sync_group_self() -> Result<()> {
Ok(())
}

#[test]
fn sync_non_existent_extra() -> Result<()> {
let context = TestContext::new("3.12");

let pyproject_toml = context.temp_dir.child("pyproject.toml");
pyproject_toml.write_str(
r#"
[project]
name = "project"
version = "0.1.0"
requires-python = ">=3.12"
[project.optional-dependencies]
types = ["sniffio>1"]
async = ["anyio>3"]
"#,
)?;

context.lock().assert().success();

// Requesting a non-existent extra should fail.
uv_snapshot!(context.filters(), context.sync().arg("--extra").arg("baz"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 4 packages in [TIME]
error: Extra `baz` is not defined in the project's `optional-dependencies` table
"###);

// Requesting a non-existent extra with frozen lock file should fail.
uv_snapshot!(context.filters(), context.sync().arg("--frozen").arg("--extra").arg("baz"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
error: Extra `baz` is not defined in the project's `optional-dependencies` table
"###);

// Excluding a non-existing extra when requesting all extras should fail.
uv_snapshot!(context.filters(), context.sync().arg("--all-extras").arg("--no-extra").arg("baz"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 4 packages in [TIME]
error: Extra `baz` is not defined in the project's `optional-dependencies` table
"###);

Ok(())
}

#[test]
fn sync_non_existent_extra_no_optional_dependencies() -> Result<()> {
let context = TestContext::new("3.12");

let pyproject_toml = context.temp_dir.child("pyproject.toml");
pyproject_toml.write_str(
r#"
[project]
name = "project"
version = "0.1.0"
requires-python = ">=3.12"
"#,
)?;

context.lock().assert().success();

// Requesting a non-existent extra should fail.
uv_snapshot!(context.filters(), context.sync().arg("--extra").arg("baz"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 1 package in [TIME]
error: Extra `baz` is not defined in the project's `optional-dependencies` table
"###);

// Excluding a non-existing extra when requesting all extras should fail.
uv_snapshot!(context.filters(), context.sync().arg("--all-extras").arg("--no-extra").arg("baz"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 1 package in [TIME]
error: Extra `baz` is not defined in the project's `optional-dependencies` table
"###);

Ok(())
}

/// Regression test for <https://github.com/astral-sh/uv/issues/6316>.
///
/// Previously, we would read metadata statically from pyproject.toml and write that to `uv.lock`. In
Expand Down Expand Up @@ -4889,7 +4984,7 @@ fn sync_all_extras() -> Result<()> {
+ typing-extensions==4.10.0
"###);

// Sync all extras.
// Sync all extras excluding an extra that exists in both the parent and child.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--all-extras").arg("--no-extra").arg("types"), @r###"
success: true
exit_code: 0
Expand All @@ -4901,6 +4996,139 @@ fn sync_all_extras() -> Result<()> {
- typing-extensions==4.10.0
"###);

// Sync an extra that doesn't exist.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--extra").arg("foo"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 8 packages in [TIME]
error: Extra `foo` is not defined in any project's `optional-dependencies` table
"###);

// Sync all extras excluding an extra that doesn't exist.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--all-extras").arg("--no-extra").arg("foo"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 8 packages in [TIME]
error: Extra `foo` is not defined in any project's `optional-dependencies` table
"###);

Ok(())
}

/// Sync all members in a workspace with dynamic extras.
#[test]
fn sync_all_extras_dynamic() -> Result<()> {
let context = TestContext::new("3.12");

let pyproject_toml = context.temp_dir.child("pyproject.toml");
pyproject_toml.write_str(
r#"
[project]
name = "project"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = ["child"]

[project.optional-dependencies]
types = ["sniffio>1"]
async = ["anyio>3"]

[build-system]
requires = ["setuptools>=42"]
build-backend = "setuptools.build_meta"

[tool.uv.workspace]
members = ["child"]

[tool.uv.sources]
child = { workspace = true }
"#,
)?;
context
.temp_dir
.child("src")
.child("project")
.child("__init__.py")
.touch()?;

// Add a workspace member.
let child = context.temp_dir.child("child");
child.child("pyproject.toml").write_str(
r#"
[project]
name = "child"
version = "0.1.0"
requires-python = ">=3.12"
dynamic = ["optional-dependencies"]

[tool.setuptools.dynamic.optional-dependencies]
dev = { file = "requirements-dev.txt" }

[build-system]
requires = ["setuptools>=42"]
build-backend = "setuptools.build_meta"
"#,
)?;
child
.child("src")
.child("child")
.child("__init__.py")
.touch()?;

child
.child("requirements-dev.txt")
.write_str("typing-extensions==4.10.0")?;

// Generate a lockfile.
context.lock().assert().success();

// Sync an extra that exists in the parent.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--extra").arg("types"), @r###"
success: true
exit_code: 0
----- stdout -----

----- stderr -----
Resolved 6 packages in [TIME]
Prepared 3 packages in [TIME]
Installed 3 packages in [TIME]
+ child==0.1.0 (from file://[TEMP_DIR]/child)
+ project==0.1.0 (from file://[TEMP_DIR]/)
+ sniffio==1.3.1
"###);

// Sync a dynamic extra that exists in the child.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--extra").arg("dev"), @r###"
success: true
exit_code: 0
----- stdout -----

----- stderr -----
Resolved 6 packages in [TIME]
Prepared 1 package in [TIME]
Uninstalled 1 package in [TIME]
Installed 1 package in [TIME]
- sniffio==1.3.1
+ typing-extensions==4.10.0
"###);

// Sync a dynamic extra that doesn't exist in the child.
uv_snapshot!(context.filters(), context.sync().arg("--all-packages").arg("--extra").arg("foo"), @r###"
success: false
exit_code: 2
----- stdout -----

----- stderr -----
Resolved 6 packages in [TIME]
error: Extra `foo` is not defined in any project's `optional-dependencies` table
"###);

Ok(())
}

Expand Down
Loading