Skip to content

Commit

Permalink
Allow incompatible requires-python for source distributions with st…
Browse files Browse the repository at this point in the history
…atic metadata (#8768)

## Summary

At present, when we have a Python requirement and we see a wheel, we
verify that the Python requirement is compatible with the wheel. For
source distributions, though, we verify that both the Python requirement
_and_ the currently-installed version are compatible, because we assume
that we'll need to build the source distribution in order to get
metadata. However, we can often extract source distribution metadata
_without_ building (e.g., if there's a `pyproject.toml` with no dynamic
keys).

This PR thus modifies the source distribution handling to defer that
incompatibility ("We couldn't get metadata for this project, because it
has no static metadata and requires a higher Python version to run /
build") until we actually try to build the package. As a result, you can
now resolve source distribution-only packages using Python versions
below their `requires-python`, as long as they include static metadata.

Closes #8767.
  • Loading branch information
charliermarsh authored Nov 3, 2024
1 parent 647494b commit bf79d98
Show file tree
Hide file tree
Showing 11 changed files with 279 additions and 128 deletions.
4 changes: 4 additions & 0 deletions crates/uv-dispatch/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,10 @@ impl<'a> BuildDispatch<'a> {
impl<'a> BuildContext for BuildDispatch<'a> {
type SourceDistBuilder = SourceBuild;

fn interpreter(&self) -> &Interpreter {
self.interpreter
}

fn cache(&self) -> &Cache {
self.cache
}
Expand Down
10 changes: 9 additions & 1 deletion crates/uv-distribution-types/src/buildable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use std::path::Path;
use url::Url;
use uv_distribution_filename::SourceDistExtension;
use uv_git::GitUrl;
use uv_pep440::Version;
use uv_pep440::{Version, VersionSpecifiers};
use uv_pep508::VerbatimUrl;

use uv_normalize::PackageName;
Expand Down Expand Up @@ -64,6 +64,14 @@ impl BuildableSource<'_> {
Self::Url(url) => matches!(url, SourceUrl::Directory(_)),
}
}

/// Return the Python version specifier required by the source, if available.
pub fn requires_python(&self) -> Option<&VersionSpecifiers> {
let Self::Dist(SourceDist::Registry(dist)) = self else {
return None;
};
dist.file.requires_python.as_ref()
}
}

impl std::fmt::Display for BuildableSource<'_> {
Expand Down
4 changes: 3 additions & 1 deletion crates/uv-distribution/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use uv_client::WrappedReqwestError;
use uv_distribution_filename::WheelFilenameError;
use uv_fs::Simplified;
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_pep440::{Version, VersionSpecifiers};
use uv_pypi_types::{HashDigest, ParsedUrlError};

#[derive(Debug, thiserror::Error)]
Expand Down Expand Up @@ -96,6 +96,8 @@ pub enum Error {
NotFound(Url),
#[error("Attempted to re-extract the source distribution for `{0}`, but the hashes didn't match. Run `{}` to clear the cache.", "uv cache clean".green())]
CacheHeal(String),
#[error("The source distribution requires Python {0}, but {1} is installed")]
RequiresPython(VersionSpecifiers, Version),

/// A generic request middleware error happened while making a request.
/// Refer to the error message for more details.
Expand Down
38 changes: 30 additions & 8 deletions crates/uv-distribution/src/source/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
//! Fetch and build source distributions from remote sources.
use std::borrow::Cow;
use std::ops::Bound;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Arc;

use crate::distribution_database::ManagedClient;
use crate::error::Error;
use crate::metadata::{ArchiveMetadata, GitWorkspaceMember, Metadata};
use crate::reporter::Facade;
use crate::source::built_wheel_metadata::BuiltWheelMetadata;
use crate::source::revision::Revision;
use crate::{Reporter, RequiresDist};
use fs_err::tokio as fs;
use futures::{FutureExt, TryStreamExt};
use reqwest::Response;
Expand All @@ -26,19 +34,12 @@ use uv_distribution_types::{
use uv_extract::hash::Hasher;
use uv_fs::{rename_with_retry, write_atomic, LockedFile};
use uv_metadata::read_archive_metadata;
use uv_pep440::release_specifiers_to_ranges;
use uv_platform_tags::Tags;
use uv_pypi_types::{HashDigest, Metadata12, RequiresTxt, ResolutionMetadata};
use uv_types::{BuildContext, SourceBuildTrait};
use zip::ZipArchive;

use crate::distribution_database::ManagedClient;
use crate::error::Error;
use crate::metadata::{ArchiveMetadata, GitWorkspaceMember, Metadata};
use crate::reporter::Facade;
use crate::source::built_wheel_metadata::BuiltWheelMetadata;
use crate::source::revision::Revision;
use crate::{Reporter, RequiresDist};

mod built_wheel_metadata;
mod revision;

Expand Down Expand Up @@ -1798,6 +1799,27 @@ impl<'a, T: BuildContext> SourceDistributionBuilder<'a, T> {
) -> Result<Option<ResolutionMetadata>, Error> {
debug!("Preparing metadata for: {source}");

// Ensure that the _installed_ Python version is compatible with the `requires-python`
// specifier.
if let Some(requires_python) = source.requires_python() {
let installed = self.build_context.interpreter().python_version();
let target = release_specifiers_to_ranges(requires_python.clone())
.bounding_range()
.map(|bounding_range| bounding_range.0.cloned())
.unwrap_or(Bound::Unbounded);
let is_compatible = match target {
Bound::Included(target) => *installed >= target,
Bound::Excluded(target) => *installed > target,
Bound::Unbounded => true,
};
if !is_compatible {
return Err(Error::RequiresPython(
requires_python.clone(),
installed.clone(),
));
}
}

// Set up the builder.
let mut builder = self
.build_context
Expand Down
44 changes: 43 additions & 1 deletion crates/uv-resolver/src/pubgrub/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rustc_hash::FxHashMap;
use uv_configuration::IndexStrategy;
use uv_distribution_types::{Index, IndexCapabilities, IndexLocations, IndexUrl};
use uv_normalize::PackageName;
use uv_pep440::Version;
use uv_pep440::{Version, VersionSpecifiers};

use crate::candidate_selector::CandidateSelector;
use crate::error::ErrorTree;
Expand Down Expand Up @@ -699,6 +699,14 @@ impl PubGrubReportFormatter<'_> {
reason: reason.clone(),
});
}
IncompletePackage::RequiresPython(requires_python, python_version) => {
hints.insert(PubGrubHint::IncompatibleBuildRequirement {
package: package.clone(),
version: version.clone(),
requires_python: requires_python.clone(),
python_version: python_version.clone(),
});
}
}
break;
}
Expand Down Expand Up @@ -862,6 +870,17 @@ pub(crate) enum PubGrubHint {
// excluded from `PartialEq` and `Hash`
reason: String,
},
/// The source distribution has a `requires-python` requirement that is not met by the installed
/// Python version (and static metadata is not available).
IncompatibleBuildRequirement {
package: PubGrubPackage,
// excluded from `PartialEq` and `Hash`
version: Version,
// excluded from `PartialEq` and `Hash`
requires_python: VersionSpecifiers,
// excluded from `PartialEq` and `Hash`
python_version: Version,
},
/// The `Requires-Python` requirement was not satisfied.
RequiresPython {
source: PythonRequirementSource,
Expand Down Expand Up @@ -932,6 +951,9 @@ enum PubGrubHintCore {
InvalidVersionStructure {
package: PubGrubPackage,
},
IncompatibleBuildRequirement {
package: PubGrubPackage,
},
RequiresPython {
source: PythonRequirementSource,
requires_python: RequiresPython,
Expand Down Expand Up @@ -985,6 +1007,9 @@ impl From<PubGrubHint> for PubGrubHintCore {
PubGrubHint::InvalidVersionStructure { package, .. } => {
Self::InvalidVersionStructure { package }
}
PubGrubHint::IncompatibleBuildRequirement { package, .. } => {
Self::IncompatibleBuildRequirement { package }
}
PubGrubHint::RequiresPython {
source,
requires_python,
Expand Down Expand Up @@ -1187,6 +1212,23 @@ impl std::fmt::Display for PubGrubHint {
package_requires_python.bold(),
)
}
Self::IncompatibleBuildRequirement {
package,
version,
requires_python,
python_version,
} => {
write!(
f,
"{}{} The source distribution for {}=={} does not include static metadata. Generating metadata for this package requires Python {}, but Python {} is installed.",
"hint".bold().cyan(),
":".bold(),
package.bold(),
version.bold(),
requires_python.bold(),
python_version.bold(),
)
}
Self::RequiresPython {
source: PythonRequirementSource::Interpreter,
requires_python: _,
Expand Down
13 changes: 12 additions & 1 deletion crates/uv-resolver/src/resolver/availability.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::fmt::{Display, Formatter};

use uv_distribution_types::IncompatibleDist;
use uv_pep440::Version;
use uv_pep440::{Version, VersionSpecifiers};

/// The reason why a package or a version cannot be used.
#[derive(Debug, Clone, Eq, PartialEq)]
Expand Down Expand Up @@ -40,6 +40,9 @@ pub(crate) enum UnavailableVersion {
InvalidStructure,
/// The wheel metadata was not found in the cache and the network is not available.
Offline,
/// The source distribution has a `requires-python` requirement that is not met by the installed
/// Python version (and static metadata is not available).
RequiresPython(VersionSpecifiers),
}

impl UnavailableVersion {
Expand All @@ -51,6 +54,9 @@ impl UnavailableVersion {
UnavailableVersion::InconsistentMetadata => "inconsistent metadata".into(),
UnavailableVersion::InvalidStructure => "an invalid package format".into(),
UnavailableVersion::Offline => "to be downloaded from a registry".into(),
UnavailableVersion::RequiresPython(requires_python) => {
format!("Python {requires_python}")
}
}
}

Expand All @@ -62,6 +68,7 @@ impl UnavailableVersion {
UnavailableVersion::InconsistentMetadata => format!("has {self}"),
UnavailableVersion::InvalidStructure => format!("has {self}"),
UnavailableVersion::Offline => format!("needs {self}"),
UnavailableVersion::RequiresPython(..) => format!("requires {self}"),
}
}

Expand All @@ -73,6 +80,7 @@ impl UnavailableVersion {
UnavailableVersion::InconsistentMetadata => format!("have {self}"),
UnavailableVersion::InvalidStructure => format!("have {self}"),
UnavailableVersion::Offline => format!("need {self}"),
UnavailableVersion::RequiresPython(..) => format!("require {self}"),
}
}
}
Expand Down Expand Up @@ -143,6 +151,9 @@ pub(crate) enum IncompletePackage {
InconsistentMetadata(String),
/// The wheel has an invalid structure.
InvalidStructure(String),
/// The source distribution has a `requires-python` requirement that is not met by the installed
/// Python version (and static metadata is not available).
RequiresPython(VersionSpecifiers, Version),
}

#[derive(Debug, Clone)]
Expand Down
Loading

0 comments on commit bf79d98

Please sign in to comment.