repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/dependency_groups.rs
crates/uv-pypi-types/src/dependency_groups.rs
use serde::{Deserialize, Deserializer, Serialize}; use std::collections::BTreeMap; use std::str::FromStr; use uv_normalize::GroupName; #[derive(Debug, Clone, PartialEq, Serialize)] pub struct DependencyGroups(BTreeMap<GroupName, Vec<DependencyGroupSpecifier>>); impl DependencyGroups { /// Returns the names of the dependency groups. pub fn keys(&self) -> impl Iterator<Item = &GroupName> { self.0.keys() } /// Returns the dependency group with the given name. pub fn get(&self, group: &GroupName) -> Option<&Vec<DependencyGroupSpecifier>> { self.0.get(group) } /// Returns `true` if the dependency group is in the list. pub fn contains_key(&self, group: &GroupName) -> bool { self.0.contains_key(group) } /// Returns an iterator over the dependency groups. pub fn iter(&self) -> impl Iterator<Item = (&GroupName, &Vec<DependencyGroupSpecifier>)> { self.0.iter() } } impl<'a> IntoIterator for &'a DependencyGroups { type Item = (&'a GroupName, &'a Vec<DependencyGroupSpecifier>); type IntoIter = std::collections::btree_map::Iter<'a, GroupName, Vec<DependencyGroupSpecifier>>; fn into_iter(self) -> Self::IntoIter { self.0.iter() } } /// Ensure that all keys in the TOML table are unique. impl<'de> serde::de::Deserialize<'de> for DependencyGroups { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct GroupVisitor; impl<'de> serde::de::Visitor<'de> for GroupVisitor { type Value = DependencyGroups; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a table with unique dependency group names") } fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error> where M: serde::de::MapAccess<'de>, { let mut sources = BTreeMap::new(); while let Some((key, value)) = access.next_entry::<GroupName, Vec<DependencyGroupSpecifier>>()? { match sources.entry(key) { std::collections::btree_map::Entry::Occupied(entry) => { return Err(serde::de::Error::custom(format!( "duplicate dependency group: `{}`", entry.key() ))); } std::collections::btree_map::Entry::Vacant(entry) => { entry.insert(value); } } } Ok(DependencyGroups(sources)) } } deserializer.deserialize_map(GroupVisitor) } } /// A specifier item in a [PEP 735](https://peps.python.org/pep-0735/) Dependency Group. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub enum DependencyGroupSpecifier { /// A PEP 508-compatible requirement string. Requirement(String), /// A reference to another dependency group. IncludeGroup { /// The name of the group to include. include_group: GroupName, }, /// A Dependency Object Specifier. Object(BTreeMap<String, String>), } impl<'de> Deserialize<'de> for DependencyGroupSpecifier { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = DependencyGroupSpecifier; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string or a map with the `include-group` key") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: serde::de::Error, { Ok(DependencyGroupSpecifier::Requirement(value.to_owned())) } fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error> where M: serde::de::MapAccess<'de>, { let mut map_data = BTreeMap::new(); while let Some((key, value)) = map.next_entry()? { map_data.insert(key, value); } if map_data.is_empty() { return Err(serde::de::Error::custom("missing field `include-group`")); } if let Some(include_group) = map_data .get("include-group") .map(String::as_str) .map(GroupName::from_str) .transpose() .map_err(serde::de::Error::custom)? { Ok(DependencyGroupSpecifier::IncludeGroup { include_group }) } else { Ok(DependencyGroupSpecifier::Object(map_data)) } } } deserializer.deserialize_any(Visitor) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/marker_environment.rs
crates/uv-pypi-types/src/marker_environment.rs
use tracing::debug; use uv_pep508::MarkerEnvironment; /// A wrapper type around [`MarkerEnvironment`] that ensures the Python version markers are /// release-only, to match the resolver's semantics. #[derive(Debug, Clone, Eq, PartialEq)] pub struct ResolverMarkerEnvironment(MarkerEnvironment); impl ResolverMarkerEnvironment { /// Returns the underlying [`MarkerEnvironment`]. pub fn markers(&self) -> &MarkerEnvironment { &self.0 } } impl From<MarkerEnvironment> for ResolverMarkerEnvironment { fn from(value: MarkerEnvironment) -> Self { // Strip `python_version`. let python_version = value.python_version().only_release(); let value = if python_version == **value.python_version() { value } else { debug!( "Stripping pre-release from `python_version`: {}", value.python_version() ); value.with_python_version(python_version) }; // Strip `python_full_version`. let python_full_version = value.python_full_version().only_release(); let value = if python_full_version == **value.python_full_version() { value } else { debug!( "Stripping pre-release from `python_full_version`: {}", value.python_full_version() ); value.with_python_full_version(python_full_version) }; Self(value) } } impl std::ops::Deref for ResolverMarkerEnvironment { type Target = MarkerEnvironment; fn deref(&self) -> &Self::Target { &self.0 } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/scheme.rs
crates/uv-pypi-types/src/scheme.rs
use std::path::PathBuf; use serde::{Deserialize, Serialize}; /// The paths associated with an installation scheme, typically returned by `sysconfig.get_paths()`. /// /// See: <https://github.com/pypa/pip/blob/ae5fff36b0aad6e5e0037884927eaa29163c0611/src/pip/_internal/models/scheme.py#L12> /// /// See: <https://docs.python.org/3.12/library/sysconfig.html#installation-paths> #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Scheme { pub purelib: PathBuf, pub platlib: PathBuf, pub scripts: PathBuf, pub data: PathBuf, pub include: PathBuf, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/build_requires.rs
crates/uv-pypi-types/src/metadata/build_requires.rs
use uv_normalize::PackageName; use uv_pep508::Requirement; use crate::VerbatimParsedUrl; /// The `build-system.requires` field in a `pyproject.toml` file. /// /// See: <https://peps.python.org/pep-0518/> #[derive(Debug, Clone)] pub struct BuildRequires { pub name: Option<PackageName>, pub requires_dist: Vec<Requirement<VerbatimParsedUrl>>, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/metadata10.rs
crates/uv-pypi-types/src/metadata/metadata10.rs
use serde::Deserialize; use uv_normalize::PackageName; use crate::MetadataError; use crate::metadata::Headers; /// A subset of the full core metadata specification, including only the /// fields that have been consistent across all versions of the specification. /// /// Core Metadata 1.0 is specified in <https://peps.python.org/pep-0241/>. #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct Metadata10 { pub name: PackageName, pub version: String, } impl Metadata10 { /// Parse the [`Metadata10`] from a `PKG-INFO` file, as included in a source distribution. pub fn parse_pkg_info(content: &[u8]) -> Result<Self, MetadataError> { let headers = Headers::parse(content)?; let name = PackageName::from_owned( headers .get_first_value("Name") .ok_or(MetadataError::FieldNotFound("Name"))?, )?; let version = headers .get_first_value("Version") .ok_or(MetadataError::FieldNotFound("Version"))?; Ok(Self { name, version }) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/mod.rs
crates/uv-pypi-types/src/metadata/mod.rs
mod build_requires; mod metadata10; mod metadata23; mod metadata_resolver; mod pyproject_toml; mod requires_dist; mod requires_txt; use std::str::Utf8Error; use mailparse::{MailHeaderMap, MailParseError}; use thiserror::Error; use uv_normalize::InvalidNameError; use uv_pep440::{VersionParseError, VersionSpecifiersParseError}; use uv_pep508::Pep508Error; use crate::VerbatimParsedUrl; pub use build_requires::BuildRequires; pub use metadata_resolver::ResolutionMetadata; pub use metadata10::Metadata10; pub use metadata23::Metadata23; pub use pyproject_toml::PyProjectToml; pub use requires_dist::RequiresDist; pub use requires_txt::RequiresTxt; /// <https://github.com/PyO3/python-pkginfo-rs/blob/d719988323a0cfea86d4737116d7917f30e819e2/src/error.rs> /// /// The error type #[derive(Error, Debug)] pub enum MetadataError { #[error(transparent)] MailParse(#[from] MailParseError), #[error("Invalid `pyproject.toml`")] InvalidPyprojectTomlSyntax(#[source] toml_edit::TomlError), #[error(transparent)] InvalidPyprojectTomlSchema(toml_edit::de::Error), #[error( "`pyproject.toml` is using the `[project]` table, but the required `project.name` field is not set" )] MissingName, #[error("Metadata field {0} not found")] FieldNotFound(&'static str), #[error("Invalid version: {0}")] Pep440VersionError(VersionParseError), #[error(transparent)] Pep440Error(#[from] VersionSpecifiersParseError), #[error(transparent)] Pep508Error(#[from] Box<Pep508Error<VerbatimParsedUrl>>), #[error(transparent)] InvalidName(#[from] InvalidNameError), #[error("Invalid `Metadata-Version` field: {0}")] InvalidMetadataVersion(String), #[error("Reading metadata from `PKG-INFO` requires Metadata 2.2 or later (found: {0})")] UnsupportedMetadataVersion(String), #[error("The following field was marked as dynamic: {0}")] DynamicField(&'static str), #[error( "The project uses Poetry's syntax to declare its dependencies, despite including a `project` table in `pyproject.toml`" )] PoetrySyntax, #[error("Failed to read `requires.txt` contents")] RequiresTxtContents(#[from] std::io::Error), #[error("The description is not valid utf-8")] DescriptionEncoding(#[source] Utf8Error), } impl From<Pep508Error<VerbatimParsedUrl>> for MetadataError { fn from(error: Pep508Error<VerbatimParsedUrl>) -> Self { Self::Pep508Error(Box::new(error)) } } /// The headers of a distribution metadata file. #[derive(Debug)] struct Headers<'a> { headers: Vec<mailparse::MailHeader<'a>>, body_start: usize, } impl<'a> Headers<'a> { /// Parse the headers from the given metadata file content. fn parse(content: &'a [u8]) -> Result<Self, MailParseError> { let (headers, body_start) = mailparse::parse_headers(content)?; Ok(Self { headers, body_start, }) } /// Return the first value associated with the header with the given name. fn get_first_value(&self, name: &str) -> Option<String> { self.headers.get_first_header(name).and_then(|header| { let value = header.get_value(); if value == "UNKNOWN" { None } else { Some(value) } }) } /// Return all values associated with the header with the given name. fn get_all_values(&self, name: &str) -> impl Iterator<Item = String> { self.headers .get_all_values(name) .into_iter() .filter(|value| value != "UNKNOWN") } } /// Parse a `Metadata-Version` field into a (major, minor) tuple. fn parse_version(metadata_version: &str) -> Result<(u8, u8), MetadataError> { let (major, minor) = metadata_version .split_once('.') .ok_or(MetadataError::InvalidMetadataVersion( metadata_version.to_string(), ))?; let major = major .parse::<u8>() .map_err(|_| MetadataError::InvalidMetadataVersion(metadata_version.to_string()))?; let minor = minor .parse::<u8>() .map_err(|_| MetadataError::InvalidMetadataVersion(metadata_version.to_string()))?; Ok((major, minor)) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/metadata_resolver.rs
crates/uv-pypi-types/src/metadata/metadata_resolver.rs
//! Derived from `pypi_types_crate`. use std::str::FromStr; use itertools::Itertools; use serde::{Deserialize, Serialize}; use tracing::warn; use uv_normalize::{ExtraName, PackageName}; use uv_pep440::{Version, VersionSpecifiers}; use uv_pep508::Requirement; use crate::lenient_requirement::LenientRequirement; use crate::metadata::Headers; use crate::metadata::pyproject_toml::PyProjectToml; use crate::{LenientVersionSpecifiers, MetadataError, VerbatimParsedUrl, metadata}; /// A subset of the full core metadata specification, including only the /// fields that are relevant to dependency resolution. /// /// Core Metadata 2.3 is specified in <https://packaging.python.org/specifications/core-metadata/>. #[derive( Serialize, Deserialize, Debug, Clone, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, )] #[serde(rename_all = "kebab-case")] #[rkyv(derive(Debug))] pub struct ResolutionMetadata { // Mandatory fields pub name: PackageName, pub version: Version, // Optional fields pub requires_dist: Box<[Requirement<VerbatimParsedUrl>]>, pub requires_python: Option<VersionSpecifiers>, #[serde(alias = "provides-extras")] pub provides_extra: Box<[ExtraName]>, /// Whether the version field is dynamic. #[serde(default)] pub dynamic: bool, } /// From <https://github.com/PyO3/python-pkginfo-rs/blob/d719988323a0cfea86d4737116d7917f30e819e2/src/metadata.rs#LL78C2-L91C26> impl ResolutionMetadata { /// Parse the [`ResolutionMetadata`] from a `METADATA` file, as included in a built distribution (wheel). pub fn parse_metadata(content: &[u8]) -> Result<Self, MetadataError> { let headers = Headers::parse(content)?; let name = PackageName::from_owned( headers .get_first_value("Name") .ok_or(MetadataError::FieldNotFound("Name"))?, )?; let version = Version::from_str( &headers .get_first_value("Version") .ok_or(MetadataError::FieldNotFound("Version"))?, ) .map_err(MetadataError::Pep440VersionError)?; let requires_dist = headers .get_all_values("Requires-Dist") .map(|requires_dist| LenientRequirement::from_str(&requires_dist)) .map_ok(Requirement::from) .collect::<Result<Box<_>, _>>()?; let requires_python = headers .get_first_value("Requires-Python") .map(|requires_python| LenientVersionSpecifiers::from_str(&requires_python)) .transpose()? .map(VersionSpecifiers::from); let provides_extra = headers .get_all_values("Provides-Extra") .filter_map( |provides_extra| match ExtraName::from_owned(provides_extra) { Ok(extra_name) => Some(extra_name), Err(err) => { warn!("Ignoring invalid extra: {err}"); None } }, ) .collect::<Box<_>>(); let dynamic = headers .get_all_values("Dynamic") .any(|field| field == "Version"); Ok(Self { name, version, requires_dist, requires_python, provides_extra, dynamic, }) } /// Read the [`ResolutionMetadata`] from a source distribution's `PKG-INFO` file, if it uses Metadata 2.2 /// or later _and_ none of the required fields (`Requires-Python`, `Requires-Dist`, and /// `Provides-Extra`) are marked as dynamic. pub fn parse_pkg_info(content: &[u8]) -> Result<Self, MetadataError> { let headers = Headers::parse(content)?; // To rely on a source distribution's `PKG-INFO` file, the `Metadata-Version` field must be // present and set to a value of at least `2.2`. let metadata_version = headers .get_first_value("Metadata-Version") .ok_or(MetadataError::FieldNotFound("Metadata-Version"))?; // Parse the version into (major, minor). let (major, minor) = metadata::parse_version(&metadata_version)?; if (major, minor) < (2, 2) || (major, minor) >= (3, 0) { return Err(MetadataError::UnsupportedMetadataVersion(metadata_version)); } // If any of the fields we need are marked as dynamic, we can't use the `PKG-INFO` file. let mut dynamic = false; for field in headers.get_all_values("Dynamic") { match field.as_str() { "Requires-Python" => return Err(MetadataError::DynamicField("Requires-Python")), "Requires-Dist" => return Err(MetadataError::DynamicField("Requires-Dist")), "Provides-Extra" => return Err(MetadataError::DynamicField("Provides-Extra")), "Version" => dynamic = true, _ => (), } } // The `Name` and `Version` fields are required, and can't be dynamic. let name = PackageName::from_owned( headers .get_first_value("Name") .ok_or(MetadataError::FieldNotFound("Name"))?, )?; let version = Version::from_str( &headers .get_first_value("Version") .ok_or(MetadataError::FieldNotFound("Version"))?, ) .map_err(MetadataError::Pep440VersionError)?; // The remaining fields are required to be present. let requires_dist = headers .get_all_values("Requires-Dist") .map(|requires_dist| LenientRequirement::from_str(&requires_dist)) .map_ok(Requirement::from) .collect::<Result<Box<_>, _>>()?; let requires_python = headers .get_first_value("Requires-Python") .map(|requires_python| LenientVersionSpecifiers::from_str(&requires_python)) .transpose()? .map(VersionSpecifiers::from); let provides_extra = headers .get_all_values("Provides-Extra") .filter_map( |provides_extra| match ExtraName::from_owned(provides_extra) { Ok(extra_name) => Some(extra_name), Err(err) => { warn!("Ignoring invalid extra: {err}"); None } }, ) .collect::<Box<_>>(); Ok(Self { name, version, requires_dist, requires_python, provides_extra, dynamic, }) } /// Extract the metadata from a `pyproject.toml` file, as specified in PEP 621. /// /// If we're coming from a source distribution, we may already know the version (unlike for a /// source tree), so we can tolerate dynamic versions. pub fn parse_pyproject_toml( pyproject_toml: PyProjectToml, sdist_version: Option<&Version>, ) -> Result<Self, MetadataError> { let project = pyproject_toml .project .ok_or(MetadataError::FieldNotFound("project"))?; // If any of the fields we need were declared as dynamic, we can't use the `pyproject.toml` file. let mut dynamic = false; for field in project.dynamic.unwrap_or_default() { match field.as_str() { "dependencies" => return Err(MetadataError::DynamicField("dependencies")), "optional-dependencies" => { return Err(MetadataError::DynamicField("optional-dependencies")); } "requires-python" => return Err(MetadataError::DynamicField("requires-python")), // When building from a source distribution, the version is known from the filename and // fixed by it, so we can pretend it's static. "version" => { if sdist_version.is_none() { return Err(MetadataError::DynamicField("version")); } dynamic = true; } _ => (), } } // If dependencies are declared with Poetry, and `project.dependencies` is omitted, treat // the dependencies as dynamic. The inclusion of a `project` table without defining // `project.dependencies` is almost certainly an error. if project.dependencies.is_none() && pyproject_toml.tool.and_then(|tool| tool.poetry).is_some() { return Err(MetadataError::PoetrySyntax); } let name = project.name; let version = project .version // When building from a source distribution, the version is known from the filename and // fixed by it, so we can pretend it's static. .or_else(|| sdist_version.cloned()) .ok_or(MetadataError::FieldNotFound("version"))?; // Parse the Python version requirements. let requires_python = project .requires_python .map(|requires_python| { LenientVersionSpecifiers::from_str(&requires_python).map(VersionSpecifiers::from) }) .transpose()?; // Extract the requirements. let requires_dist = project .dependencies .unwrap_or_default() .into_iter() .map(|requires_dist| LenientRequirement::from_str(&requires_dist)) .map_ok(Requirement::from) .chain( project .optional_dependencies .as_ref() .iter() .flat_map(|index| { index.iter().flat_map(|(extras, requirements)| { requirements .iter() .map(|requires_dist| LenientRequirement::from_str(requires_dist)) .map_ok(Requirement::from) .map_ok(move |requirement| requirement.with_extra_marker(extras)) }) }), ) .collect::<Result<Box<_>, _>>()?; // Extract the optional dependencies. let provides_extra = project .optional_dependencies .unwrap_or_default() .into_keys() .collect::<Box<_>>(); Ok(Self { name, version, requires_dist, requires_python, provides_extra, dynamic, }) } } #[cfg(test)] mod tests { use std::str::FromStr; use uv_normalize::PackageName; use uv_pep440::Version; use super::*; use crate::MetadataError; #[test] fn test_parse_metadata() { let s = "Metadata-Version: 1.0"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Name")))); let s = "Metadata-Version: 1.0\nName: asdf"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Version")))); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0\nAuthor: 中文\n\n一个 Python 包"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); let s = "Metadata-Version: 1.0\nName: =?utf-8?q?foobar?=\nVersion: 1.0"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()).unwrap(); assert_eq!(meta.name, PackageName::from_str("foobar").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); let s = "Metadata-Version: 1.0\nName: =?utf-8?q?=C3=A4_space?= <x@y.org>\nVersion: 1.0"; let meta = ResolutionMetadata::parse_metadata(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::InvalidName(_)))); } #[test] fn test_parse_pkg_info() { let s = "Metadata-Version: 2.1"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()); assert!(matches!( meta, Err(MetadataError::UnsupportedMetadataVersion(_)) )); let s = "Metadata-Version: 2.2\nName: asdf"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Version")))); let s = "Metadata-Version: 2.3\nName: asdf"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Version")))); let s = "Metadata-Version: 2.3\nName: asdf\nVersion: 1.0"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); let s = "Metadata-Version: 2.3\nName: asdf\nVersion: 1.0\nDynamic: Requires-Dist"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()).unwrap_err(); assert!(matches!(meta, MetadataError::DynamicField("Requires-Dist"))); let s = "Metadata-Version: 2.3\nName: asdf\nVersion: 1.0\nRequires-Dist: foo"; let meta = ResolutionMetadata::parse_pkg_info(s.as_bytes()).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); assert_eq!(*meta.requires_dist, ["foo".parse().unwrap()]); } #[test] fn test_parse_pyproject_toml() { let s = r#" [project] name = "asdf" "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None); assert!(matches!(meta, Err(MetadataError::FieldNotFound("version")))); let s = r#" [project] name = "asdf" dynamic = ["version"] "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None); assert!(matches!(meta, Err(MetadataError::DynamicField("version")))); let s = r#" [project] name = "asdf" version = "1.0" "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); assert!(meta.requires_python.is_none()); assert!(meta.requires_dist.is_empty()); assert!(meta.provides_extra.is_empty()); let s = r#" [project] name = "asdf" version = "1.0" requires-python = ">=3.6" "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); assert_eq!(meta.requires_python, Some(">=3.6".parse().unwrap())); assert!(meta.requires_dist.is_empty()); assert!(meta.provides_extra.is_empty()); let s = r#" [project] name = "asdf" version = "1.0" requires-python = ">=3.6" dependencies = ["foo"] "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); assert_eq!(meta.requires_python, Some(">=3.6".parse().unwrap())); assert_eq!(*meta.requires_dist, ["foo".parse().unwrap()]); assert!(meta.provides_extra.is_empty()); let s = r#" [project] name = "asdf" version = "1.0" requires-python = ">=3.6" dependencies = ["foo"] [project.optional-dependencies] dotenv = ["bar"] "#; let pyproject = PyProjectToml::from_toml(s).unwrap(); let meta = ResolutionMetadata::parse_pyproject_toml(pyproject, None).unwrap(); assert_eq!(meta.name, PackageName::from_str("asdf").unwrap()); assert_eq!(meta.version, Version::new([1, 0])); assert_eq!(meta.requires_python, Some(">=3.6".parse().unwrap())); assert_eq!( *meta.requires_dist, [ "foo".parse().unwrap(), "bar; extra == \"dotenv\"".parse().unwrap() ] ); assert_eq!(*meta.provides_extra, ["dotenv".parse().unwrap()]); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/pyproject_toml.rs
crates/uv-pypi-types/src/metadata/pyproject_toml.rs
use std::str::FromStr; use indexmap::IndexMap; use serde::Deserialize; use serde::de::IntoDeserializer; use uv_normalize::{ExtraName, PackageName}; use uv_pep440::Version; use crate::MetadataError; /// A `pyproject.toml` as specified in PEP 517. #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub struct PyProjectToml { pub project: Option<Project>, pub(super) tool: Option<Tool>, } impl PyProjectToml { pub fn from_toml(toml: &str) -> Result<Self, MetadataError> { let pyproject_toml = toml_edit::Document::from_str(toml) .map_err(MetadataError::InvalidPyprojectTomlSyntax)?; let pyproject_toml = Self::deserialize(pyproject_toml.into_deserializer()) .map_err(MetadataError::InvalidPyprojectTomlSchema)?; Ok(pyproject_toml) } } /// PEP 621 project metadata. /// /// This is a subset of the full metadata specification, and only includes the fields that are /// relevant for dependency resolution. /// /// See <https://packaging.python.org/en/latest/specifications/pyproject-toml>. #[derive(Deserialize, Debug, Clone)] #[serde(try_from = "PyprojectTomlWire")] pub struct Project { /// The name of the project pub name: PackageName, /// The version of the project as supported by PEP 440 pub version: Option<Version>, /// The Python version requirements of the project pub requires_python: Option<String>, /// Project dependencies pub dependencies: Option<Vec<String>>, /// Optional dependencies pub optional_dependencies: Option<IndexMap<ExtraName, Vec<String>>>, /// Specifies which fields listed by PEP 621 were intentionally unspecified /// so another tool can/will provide such metadata dynamically. pub dynamic: Option<Vec<String>>, } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] struct PyprojectTomlWire { name: Option<PackageName>, version: Option<Version>, requires_python: Option<String>, dependencies: Option<Vec<String>>, optional_dependencies: Option<IndexMap<ExtraName, Vec<String>>>, dynamic: Option<Vec<String>>, } impl TryFrom<PyprojectTomlWire> for Project { type Error = MetadataError; fn try_from(wire: PyprojectTomlWire) -> Result<Self, Self::Error> { let name = wire.name.ok_or(MetadataError::MissingName)?; Ok(Self { name, version: wire.version, requires_python: wire.requires_python, dependencies: wire.dependencies, optional_dependencies: wire.optional_dependencies, dynamic: wire.dynamic, }) } } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] pub(super) struct Tool { pub(super) poetry: Option<ToolPoetry>, } #[derive(Deserialize, Debug, Clone)] #[serde(rename_all = "kebab-case")] #[allow(clippy::empty_structs_with_brackets)] pub(super) struct ToolPoetry {}
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/requires_txt.rs
crates/uv-pypi-types/src/metadata/requires_txt.rs
use std::io::BufRead; use std::str::FromStr; use uv_normalize::ExtraName; use uv_pep508::{ExtraOperator, MarkerExpression, MarkerTree, MarkerValueExtra, Requirement}; use crate::{LenientRequirement, MetadataError, VerbatimParsedUrl}; /// `requires.txt` metadata as defined in <https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#dependency-metadata>. /// /// This is a subset of the full metadata specification, and only includes the fields that are /// included in the legacy `requires.txt` file. #[derive(Debug, Clone)] pub struct RequiresTxt { pub requires_dist: Vec<Requirement<VerbatimParsedUrl>>, pub provides_extra: Vec<ExtraName>, } impl RequiresTxt { /// Parse the [`RequiresTxt`] from a `requires.txt` file, as included in an `egg-info`. /// /// See: <https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#dependency-metadata> pub fn parse(content: &[u8]) -> Result<Self, MetadataError> { let mut requires_dist = vec![]; let mut provides_extra = vec![]; let mut current_marker = MarkerTree::default(); for line in content.lines() { let line = line.map_err(MetadataError::RequiresTxtContents)?; let line = line.trim(); if line.is_empty() { continue; } // When encountering a new section, parse the extra and marker from the header, e.g., // `[:sys_platform == "win32"]` or `[dev]`. if line.starts_with('[') { let line = line.trim_start_matches('[').trim_end_matches(']'); // Split into extra and marker, both of which can be empty. let (extra, marker) = { let (extra, marker) = match line.split_once(':') { Some((extra, marker)) => (Some(extra), Some(marker)), None => (Some(line), None), }; let extra = extra.filter(|extra| !extra.is_empty()); let marker = marker.filter(|marker| !marker.is_empty()); (extra, marker) }; // Parse the extra. let extra = if let Some(extra) = extra { if let Ok(extra) = ExtraName::from_str(extra) { provides_extra.push(extra.clone()); Some(MarkerValueExtra::Extra(extra)) } else { Some(MarkerValueExtra::Arbitrary(extra.to_string())) } } else { None }; // Parse the marker. let marker = marker.map(MarkerTree::parse_str).transpose()?; // Create the marker tree. match (extra, marker) { (Some(extra), Some(mut marker)) => { marker.and(MarkerTree::expression(MarkerExpression::Extra { operator: ExtraOperator::Equal, name: extra, })); current_marker = marker; } (Some(extra), None) => { current_marker = MarkerTree::expression(MarkerExpression::Extra { operator: ExtraOperator::Equal, name: extra, }); } (None, Some(marker)) => { current_marker = marker; } (None, None) => { current_marker = MarkerTree::default(); } } continue; } // Parse the requirement. let requirement = Requirement::<VerbatimParsedUrl>::from(LenientRequirement::from_str(line)?); // Add the markers and extra, if necessary. requires_dist.push(Requirement { marker: current_marker, ..requirement }); } Ok(Self { requires_dist, provides_extra, }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_requires_txt() { let s = r" Werkzeug>=0.14 Jinja2>=2.10 [dev] pytest>=3 sphinx [dotenv] python-dotenv "; let meta = RequiresTxt::parse(s.as_bytes()).unwrap(); assert_eq!( meta.requires_dist, vec![ "Werkzeug>=0.14".parse().unwrap(), "Jinja2>=2.10".parse().unwrap(), "pytest>=3; extra == \"dev\"".parse().unwrap(), "sphinx; extra == \"dev\"".parse().unwrap(), "python-dotenv; extra == \"dotenv\"".parse().unwrap(), ] ); let s = r" Werkzeug>=0.14 [dev:] Jinja2>=2.10 [:sys_platform == 'win32'] pytest>=3 [] sphinx [dotenv:sys_platform == 'darwin'] python-dotenv "; let meta = RequiresTxt::parse(s.as_bytes()).unwrap(); assert_eq!( meta.requires_dist, vec![ "Werkzeug>=0.14".parse().unwrap(), "Jinja2>=2.10 ; extra == \"dev\"".parse().unwrap(), "pytest>=3; sys_platform == 'win32'".parse().unwrap(), "sphinx".parse().unwrap(), "python-dotenv; sys_platform == 'darwin' and extra == \"dotenv\"" .parse() .unwrap(), ] ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/metadata23.rs
crates/uv-pypi-types/src/metadata/metadata23.rs
//! Vendored from <https://github.com/PyO3/python-pkginfo-rs> use std::fmt::Display; use std::fmt::Write; use std::str; use std::str::FromStr; use crate::MetadataError; use crate::metadata::Headers; /// Code Metadata 2.3 as specified in /// <https://packaging.python.org/specifications/core-metadata/>. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Metadata23 { /// Version of the file format; legal values are `1.0`, `1.1`, `1.2`, `2.1`, `2.2`, `2.3` and /// `2.4`. pub metadata_version: String, /// The name of the distribution. pub name: String, /// A string containing the distribution's version number. pub version: String, /// A Platform specification describing an operating system supported by the distribution /// which is not listed in the “Operating System” Trove classifiers. pub platforms: Vec<String>, /// Binary distributions containing a PKG-INFO file will use the Supported-Platform field /// in their metadata to specify the OS and CPU for which the binary distribution was compiled. pub supported_platforms: Vec<String>, /// A one-line summary of what the distribution does. pub summary: Option<String>, /// A longer description of the distribution that can run to several paragraphs. pub description: Option<String>, /// A string stating the markup syntax (if any) used in the distribution's description, /// so that tools can intelligently render the description. /// /// Known values: `text/plain`, `text/markdown` and `text/x-rst`. pub description_content_type: Option<String>, /// A list of additional keywords, separated by commas, to be used to /// assist searching for the distribution in a larger catalog. pub keywords: Option<String>, /// A string containing the URL for the distribution's home page. /// /// Deprecated by PEP 753. pub home_page: Option<String>, /// A string containing the URL from which this version of the distribution can be downloaded. /// /// Deprecated by PEP 753. pub download_url: Option<String>, /// A string containing the author's name at a minimum; additional contact information may be /// provided. pub author: Option<String>, /// A string containing the author's e-mail address. It can contain a name and e-mail address in /// the legal forms for an RFC-822 `From:` header. pub author_email: Option<String>, /// A string containing the maintainer's name at a minimum; additional contact information may /// be provided. /// /// Note that this field is intended for use when a project is being maintained by someone other /// than the original author: /// it should be omitted if it is identical to `author`. pub maintainer: Option<String>, /// A string containing the maintainer's e-mail address. /// It can contain a name and e-mail address in the legal forms for a RFC-822 `From:` header. /// /// Note that this field is intended for use when a project is being maintained by someone other /// than the original author: it should be omitted if it is identical to `author_email`. pub maintainer_email: Option<String>, /// Text indicating the license covering the distribution where the license is not a selection /// from the `License` Trove classifiers or an SPDX license expression. pub license: Option<String>, /// An SPDX expression indicating the license covering the distribution. /// /// Introduced by PEP 639, requires metadata version 2.4. pub license_expression: Option<String>, /// Paths to files containing the text of the licenses covering the distribution. /// /// Introduced by PEP 639, requires metadata version 2.4. pub license_files: Vec<String>, /// Each entry is a string giving a single classification value for the distribution. pub classifiers: Vec<String>, /// Each entry contains a string naming some other distutils project required by this /// distribution. pub requires_dist: Vec<String>, /// Each entry contains a string naming a Distutils project which is contained within this /// distribution. pub provides_dist: Vec<String>, /// Each entry contains a string describing a distutils project's distribution which this /// distribution renders obsolete, /// meaning that the two projects should not be installed at the same time. pub obsoletes_dist: Vec<String>, /// This field specifies the Python version(s) that the distribution is guaranteed to be /// compatible with. pub requires_python: Option<String>, /// Each entry contains a string describing some dependency in the system that the distribution /// is to be used. pub requires_external: Vec<String>, /// A string containing a browsable URL for the project and a label for it, separated by a /// comma. pub project_urls: Vec<String>, /// A string containing the name of an optional feature. Must be a valid Python identifier. /// May be used to make a dependency conditional on whether the optional feature has been /// requested. pub provides_extra: Vec<String>, /// A string containing the name of another core metadata field. pub dynamic: Vec<String>, } impl Metadata23 { /// Parse distribution metadata from metadata `MetadataError` pub fn parse(content: &[u8]) -> Result<Self, MetadataError> { let headers = Headers::parse(content)?; let metadata_version = headers .get_first_value("Metadata-Version") .ok_or(MetadataError::FieldNotFound("Metadata-Version"))?; let name = headers .get_first_value("Name") .ok_or(MetadataError::FieldNotFound("Name"))?; let version = headers .get_first_value("Version") .ok_or(MetadataError::FieldNotFound("Version"))?; let platforms = headers.get_all_values("Platform").collect(); let supported_platforms = headers.get_all_values("Supported-Platform").collect(); let summary = headers.get_first_value("Summary"); let body = str::from_utf8(&content[headers.body_start..]) .map_err(MetadataError::DescriptionEncoding)?; let description = if body.trim().is_empty() { headers.get_first_value("Description") } else { Some(body.to_string()) }; let keywords = headers.get_first_value("Keywords"); let home_page = headers.get_first_value("Home-Page"); let download_url = headers.get_first_value("Download-URL"); let author = headers.get_first_value("Author"); let author_email = headers.get_first_value("Author-email"); let license = headers.get_first_value("License"); let license_expression = headers.get_first_value("License-Expression"); let license_files = headers.get_all_values("License-File").collect(); let classifiers = headers.get_all_values("Classifier").collect(); let requires_dist = headers.get_all_values("Requires-Dist").collect(); let provides_dist = headers.get_all_values("Provides-Dist").collect(); let obsoletes_dist = headers.get_all_values("Obsoletes-Dist").collect(); let maintainer = headers.get_first_value("Maintainer"); let maintainer_email = headers.get_first_value("Maintainer-email"); let requires_python = headers.get_first_value("Requires-Python"); let requires_external = headers.get_all_values("Requires-External").collect(); let project_urls = headers.get_all_values("Project-URL").collect(); let provides_extra = headers.get_all_values("Provides-Extra").collect(); let description_content_type = headers.get_first_value("Description-Content-Type"); let dynamic = headers.get_all_values("Dynamic").collect(); Ok(Self { metadata_version, name, version, platforms, supported_platforms, summary, description, description_content_type, keywords, home_page, download_url, author, author_email, maintainer, maintainer_email, license, license_expression, license_files, classifiers, requires_dist, provides_dist, obsoletes_dist, requires_python, requires_external, project_urls, provides_extra, dynamic, }) } /// Convert to the pseudo-email format used by Python's METADATA. /// /// > The standard file format for metadata (including in wheels and installed projects) is /// > based on the format of email headers. However, email formats have been revised several /// > times, and exactly which email RFC applies to packaging metadata is not specified. In the /// > absence of a precise definition, the practical standard is set by what the standard /// > library `email.parser` module can parse using the `compat32` policy. /// - <https://packaging.python.org/en/latest/specifications/core-metadata/#core-metadata-specifications> /// /// # Example /// /// ```text /// Metadata-Version: 2.3 /// Name: hello-world /// Version: 0.1.0 /// License: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, /// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A [...] /// ``` pub fn core_metadata_format(&self) -> String { fn write_str(writer: &mut String, key: &str, value: impl Display) { let value = value.to_string(); let mut lines = value.lines(); if let Some(line) = lines.next() { let _ = writeln!(writer, "{key}: {line}"); } else { // The value is an empty string let _ = writeln!(writer, "{key}: "); } for line in lines { // Python implementations vary // https://github.com/pypa/pyproject-metadata/pull/150/files#diff-7d938dbc255a08c2cfab1b4f1f8d1f6519c9312dd0a39d7793fa778474f1fbd1L135-R141 let _ = writeln!(writer, "{}{}", " ".repeat(key.len() + 2), line); } } fn write_opt_str(writer: &mut String, key: &str, value: Option<&impl Display>) { if let Some(value) = value { write_str(writer, key, value); } } fn write_all( writer: &mut String, key: &str, values: impl IntoIterator<Item = impl Display>, ) { for value in values { write_str(writer, key, value); } } let mut writer = String::new(); write_str(&mut writer, "Metadata-Version", &self.metadata_version); write_str(&mut writer, "Name", &self.name); write_str(&mut writer, "Version", &self.version); write_all(&mut writer, "Platform", &self.platforms); write_all(&mut writer, "Supported-Platform", &self.supported_platforms); write_all(&mut writer, "Summary", &self.summary); write_opt_str(&mut writer, "Keywords", self.keywords.as_ref()); write_opt_str(&mut writer, "Home-Page", self.home_page.as_ref()); write_opt_str(&mut writer, "Download-URL", self.download_url.as_ref()); write_opt_str(&mut writer, "Author", self.author.as_ref()); write_opt_str(&mut writer, "Author-email", self.author_email.as_ref()); write_opt_str(&mut writer, "License", self.license.as_ref()); write_opt_str( &mut writer, "License-Expression", self.license_expression.as_ref(), ); write_all(&mut writer, "License-File", &self.license_files); write_all(&mut writer, "Classifier", &self.classifiers); write_all(&mut writer, "Requires-Dist", &self.requires_dist); write_all(&mut writer, "Provides-Dist", &self.provides_dist); write_all(&mut writer, "Obsoletes-Dist", &self.obsoletes_dist); write_opt_str(&mut writer, "Maintainer", self.maintainer.as_ref()); write_opt_str( &mut writer, "Maintainer-email", self.maintainer_email.as_ref(), ); write_opt_str( &mut writer, "Requires-Python", self.requires_python.as_ref(), ); write_all(&mut writer, "Requires-External", &self.requires_external); write_all(&mut writer, "Project-URL", &self.project_urls); write_all(&mut writer, "Provides-Extra", &self.provides_extra); write_opt_str( &mut writer, "Description-Content-Type", self.description_content_type.as_ref(), ); write_all(&mut writer, "Dynamic", &self.dynamic); if let Some(description) = &self.description { writer.push('\n'); writer.push_str(description); } writer } } impl FromStr for Metadata23 { type Err = MetadataError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::parse(s.as_bytes()) } } #[cfg(test)] mod tests { use super::*; use crate::MetadataError; #[test] fn test_parse_from_str() { let s = "Metadata-Version: 1.0"; let meta: Result<Metadata23, MetadataError> = s.parse(); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Name")))); let s = "Metadata-Version: 1.0\nName: asdf"; let meta = Metadata23::parse(s.as_bytes()); assert!(matches!(meta, Err(MetadataError::FieldNotFound("Version")))); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0"; let meta = Metadata23::parse(s.as_bytes()).unwrap(); assert_eq!(meta.metadata_version, "1.0"); assert_eq!(meta.name, "asdf"); assert_eq!(meta.version, "1.0"); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0\nDescription: a Python package"; let meta: Metadata23 = s.parse().unwrap(); assert_eq!(meta.description.as_deref(), Some("a Python package")); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0\n\na Python package"; let meta: Metadata23 = s.parse().unwrap(); assert_eq!(meta.description.as_deref(), Some("a Python package")); let s = "Metadata-Version: 1.0\nName: asdf\nVersion: 1.0\nAuthor: 中文\n\n一个 Python 包"; let meta: Metadata23 = s.parse().unwrap(); assert_eq!(meta.author.as_deref(), Some("中文")); assert_eq!(meta.description.as_deref(), Some("一个 Python 包")); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-pypi-types/src/metadata/requires_dist.rs
crates/uv-pypi-types/src/metadata/requires_dist.rs
use std::str::FromStr; use itertools::Itertools; use uv_normalize::{ExtraName, PackageName}; use uv_pep508::Requirement; use crate::metadata::pyproject_toml::PyProjectToml; use crate::{LenientRequirement, MetadataError, VerbatimParsedUrl}; /// Python Package Metadata 2.3 as specified in /// <https://packaging.python.org/specifications/core-metadata/>. /// /// This is a subset of [`ResolutionMetadata`]; specifically, it omits the `version` and `requires-python` /// fields, which aren't necessary when extracting the requirements of a package without installing /// the package itself. #[derive(Debug, Clone)] pub struct RequiresDist { pub name: PackageName, pub requires_dist: Box<[Requirement<VerbatimParsedUrl>]>, pub provides_extra: Box<[ExtraName]>, pub dynamic: bool, } impl RequiresDist { /// Extract the [`RequiresDist`] from a `pyproject.toml` file, as specified in PEP 621. pub fn from_pyproject_toml(pyproject_toml: PyProjectToml) -> Result<Self, MetadataError> { let project = pyproject_toml .project .ok_or(MetadataError::FieldNotFound("project"))?; // If any of the fields we need were declared as dynamic, we can't use the `pyproject.toml` // file. let mut dynamic = false; for field in project.dynamic.unwrap_or_default() { match field.as_str() { "dependencies" => return Err(MetadataError::DynamicField("dependencies")), "optional-dependencies" => { return Err(MetadataError::DynamicField("optional-dependencies")); } "version" => { dynamic = true; } _ => (), } } // If dependencies are declared with Poetry, and `project.dependencies` is omitted, treat // the dependencies as dynamic. The inclusion of a `project` table without defining // `project.dependencies` is almost certainly an error. if project.dependencies.is_none() && pyproject_toml.tool.and_then(|tool| tool.poetry).is_some() { return Err(MetadataError::PoetrySyntax); } let name = project.name; // Extract the requirements. let requires_dist = project .dependencies .unwrap_or_default() .into_iter() .map(|requires_dist| LenientRequirement::from_str(&requires_dist)) .map_ok(Requirement::from) .chain( project .optional_dependencies .as_ref() .iter() .flat_map(|index| { index.iter().flat_map(|(extras, requirements)| { requirements .iter() .map(|requires_dist| LenientRequirement::from_str(requires_dist)) .map_ok(Requirement::from) .map_ok(move |requirement| requirement.with_extra_marker(extras)) }) }), ) .collect::<Result<Box<_>, _>>()?; // Extract the optional dependencies. let provides_extra = project .optional_dependencies .unwrap_or_default() .into_keys() .collect::<Box<_>>(); Ok(Self { name, requires_dist, provides_extra, dynamic, }) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-fs/src/cachedir.rs
crates/uv-fs/src/cachedir.rs
//! Vendored from cachedir 0.3.1 to replace `std::fs` with `fs_err`. use std::io::Write; use std::{io, path}; /// The `CACHEDIR.TAG` file header as defined by the [specification](https://bford.info/cachedir/). const HEADER: &[u8; 43] = b"Signature: 8a477f597d28d172789f06886806bc55"; /// Adds a tag to the specified `directory`. /// /// Will return an error if: /// /// * The `directory` exists and contains a `CACHEDIR.TAG` file, regardless of its content. /// * The file can't be created for any reason (the `directory` doesn't exist, permission error, /// can't write to the file etc.) pub fn add_tag<P: AsRef<path::Path>>(directory: P) -> io::Result<()> { let directory = directory.as_ref(); match fs_err::OpenOptions::new() .write(true) .create_new(true) .open(directory.join("CACHEDIR.TAG")) { Ok(mut cachedir_tag) => cachedir_tag.write_all(HEADER), Err(e) => Err(e), } } /// Ensures the tag exists in `directory`. /// /// This function considers the `CACHEDIR.TAG` file in `directory` existing, regardless of its /// content, as a success. /// /// Will return an error if The tag file doesn't exist and can't be created for any reason /// (the `directory` doesn't exist, permission error, can't write to the file etc.). pub fn ensure_tag<P: AsRef<path::Path>>(directory: P) -> io::Result<()> { match add_tag(&directory) { Err(e) => match e.kind() { io::ErrorKind::AlreadyExists => Ok(()), // If it exists, but we can't write to it for some reason don't fail io::ErrorKind::PermissionDenied if directory.as_ref().join("CACHEDIR.TAG").exists() => { Ok(()) } _ => Err(e), }, other => other, } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-fs/src/path.rs
crates/uv-fs/src/path.rs
use std::borrow::Cow; use std::path::{Component, Path, PathBuf}; use std::sync::LazyLock; use either::Either; use path_slash::PathExt; /// The current working directory. #[allow(clippy::exit, clippy::print_stderr)] pub static CWD: LazyLock<PathBuf> = LazyLock::new(|| { std::env::current_dir().unwrap_or_else(|_e| { eprintln!("Current directory does not exist"); std::process::exit(1); }) }); pub trait Simplified { /// Simplify a [`Path`]. /// /// On Windows, this will strip the `\\?\` prefix from paths. On other platforms, it's a no-op. fn simplified(&self) -> &Path; /// Render a [`Path`] for display. /// /// On Windows, this will strip the `\\?\` prefix from paths. On other platforms, it's /// equivalent to [`std::path::Display`]. fn simplified_display(&self) -> impl std::fmt::Display; /// Canonicalize a path without a `\\?\` prefix on Windows. /// For a path that can't be canonicalized (e.g. on network drive or RAM drive on Windows), /// this will return the absolute path if it exists. fn simple_canonicalize(&self) -> std::io::Result<PathBuf>; /// Render a [`Path`] for user-facing display. /// /// Like [`simplified_display`], but relativizes the path against the current working directory. fn user_display(&self) -> impl std::fmt::Display; /// Render a [`Path`] for user-facing display, where the [`Path`] is relative to a base path. /// /// If the [`Path`] is not relative to the base path, will attempt to relativize the path /// against the current working directory. fn user_display_from(&self, base: impl AsRef<Path>) -> impl std::fmt::Display; /// Render a [`Path`] for user-facing display using a portable representation. /// /// Like [`user_display`], but uses a portable representation for relative paths. fn portable_display(&self) -> impl std::fmt::Display; } impl<T: AsRef<Path>> Simplified for T { fn simplified(&self) -> &Path { dunce::simplified(self.as_ref()) } fn simplified_display(&self) -> impl std::fmt::Display { dunce::simplified(self.as_ref()).display() } fn simple_canonicalize(&self) -> std::io::Result<PathBuf> { dunce::canonicalize(self.as_ref()) } fn user_display(&self) -> impl std::fmt::Display { let path = dunce::simplified(self.as_ref()); // If current working directory is root, display the path as-is. if CWD.ancestors().nth(1).is_none() { return path.display(); } // Attempt to strip the current working directory, then the canonicalized current working // directory, in case they differ. let path = path.strip_prefix(CWD.simplified()).unwrap_or(path); if path.as_os_str() == "" { // Avoid printing an empty string for the current directory return Path::new(".").display(); } path.display() } fn user_display_from(&self, base: impl AsRef<Path>) -> impl std::fmt::Display { let path = dunce::simplified(self.as_ref()); // If current working directory is root, display the path as-is. if CWD.ancestors().nth(1).is_none() { return path.display(); } // Attempt to strip the base, then the current working directory, then the canonicalized // current working directory, in case they differ. let path = path .strip_prefix(base.as_ref()) .unwrap_or_else(|_| path.strip_prefix(CWD.simplified()).unwrap_or(path)); if path.as_os_str() == "" { // Avoid printing an empty string for the current directory return Path::new(".").display(); } path.display() } fn portable_display(&self) -> impl std::fmt::Display { let path = dunce::simplified(self.as_ref()); // Attempt to strip the current working directory, then the canonicalized current working // directory, in case they differ. let path = path.strip_prefix(CWD.simplified()).unwrap_or(path); // Use a portable representation for relative paths. path.to_slash() .map(Either::Left) .unwrap_or_else(|| Either::Right(path.display())) } } pub trait PythonExt { /// Escape a [`Path`] for use in Python code. fn escape_for_python(&self) -> String; } impl<T: AsRef<Path>> PythonExt for T { fn escape_for_python(&self) -> String { self.as_ref() .to_string_lossy() .replace('\\', "\\\\") .replace('"', "\\\"") } } /// Normalize the `path` component of a URL for use as a file path. /// /// For example, on Windows, transforms `C:\Users\ferris\wheel-0.42.0.tar.gz` to /// `/C:/Users/ferris/wheel-0.42.0.tar.gz`. /// /// On other platforms, this is a no-op. pub fn normalize_url_path(path: &str) -> Cow<'_, str> { // Apply percent-decoding to the URL. let path = percent_encoding::percent_decode_str(path) .decode_utf8() .unwrap_or(Cow::Borrowed(path)); // Return the path. if cfg!(windows) { Cow::Owned( path.strip_prefix('/') .unwrap_or(&path) .replace('/', std::path::MAIN_SEPARATOR_STR), ) } else { path } } /// Normalize a path, removing things like `.` and `..`. /// /// Source: <https://github.com/rust-lang/cargo/blob/b48c41aedbd69ee3990d62a0e2006edbb506a480/crates/cargo-util/src/paths.rs#L76C1-L109C2> /// /// CAUTION: Assumes that the path is already absolute. /// /// CAUTION: This does not resolve symlinks (unlike /// [`std::fs::canonicalize`]). This may cause incorrect or surprising /// behavior at times. This should be used carefully. Unfortunately, /// [`std::fs::canonicalize`] can be hard to use correctly, since it can often /// fail, or on Windows returns annoying device paths. /// /// # Errors /// /// When a relative path is provided with `..` components that extend beyond the base directory. /// For example, `./a/../../b` cannot be normalized because it escapes the base directory. pub fn normalize_absolute_path(path: &Path) -> Result<PathBuf, std::io::Error> { let mut components = path.components().peekable(); let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().copied() { components.next(); PathBuf::from(c.as_os_str()) } else { PathBuf::new() }; for component in components { match component { Component::Prefix(..) => unreachable!(), Component::RootDir => { ret.push(component.as_os_str()); } Component::CurDir => {} Component::ParentDir => { if !ret.pop() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!( "cannot normalize a relative path beyond the base directory: {}", path.display() ), )); } } Component::Normal(c) => { ret.push(c); } } } Ok(ret) } /// Normalize a [`Path`], removing things like `.` and `..`. pub fn normalize_path(path: &Path) -> Cow<'_, Path> { // Fast path: if the path is already normalized, return it as-is. if path.components().all(|component| match component { Component::Prefix(_) | Component::RootDir | Component::Normal(_) => true, Component::ParentDir | Component::CurDir => false, }) { Cow::Borrowed(path) } else { Cow::Owned(normalized(path)) } } /// Normalize a [`PathBuf`], removing things like `.` and `..`. pub fn normalize_path_buf(path: PathBuf) -> PathBuf { // Fast path: if the path is already normalized, return it as-is. if path.components().all(|component| match component { Component::Prefix(_) | Component::RootDir | Component::Normal(_) => true, Component::ParentDir | Component::CurDir => false, }) { path } else { normalized(&path) } } /// Normalize a [`Path`]. /// /// Unlike [`normalize_absolute_path`], this works with relative paths and does never error. /// /// Note that we can theoretically go beyond the root dir here (e.g. `/usr/../../foo` becomes /// `/../foo`), but that's not a (correctness) problem, we will fail later with a file not found /// error with a path computed from the user's input. /// /// # Examples /// /// In: `../../workspace-git-path-dep-test/packages/c/../../packages/d` /// Out: `../../workspace-git-path-dep-test/packages/d` /// /// In: `workspace-git-path-dep-test/packages/c/../../packages/d` /// Out: `workspace-git-path-dep-test/packages/d` /// /// In: `./a/../../b` fn normalized(path: &Path) -> PathBuf { let mut normalized = PathBuf::new(); for component in path.components() { match component { Component::Prefix(_) | Component::RootDir | Component::Normal(_) => { // Preserve filesystem roots and regular path components. normalized.push(component); } Component::ParentDir => { match normalized.components().next_back() { None | Some(Component::ParentDir | Component::RootDir) => { // Preserve leading and above-root `..` normalized.push(component); } Some(Component::Normal(_) | Component::Prefix(_) | Component::CurDir) => { // Remove inner `..` normalized.pop(); } } } Component::CurDir => { // Remove `.` } } } normalized } /// Compute a path describing `path` relative to `base`. /// /// `lib/python/site-packages/foo/__init__.py` and `lib/python/site-packages` -> `foo/__init__.py` /// `lib/marker.txt` and `lib/python/site-packages` -> `../../marker.txt` /// `bin/foo_launcher` and `lib/python/site-packages` -> `../../../bin/foo_launcher` /// /// Returns `Err` if there is no relative path between `path` and `base` (for example, if the paths /// are on different drives on Windows). pub fn relative_to( path: impl AsRef<Path>, base: impl AsRef<Path>, ) -> Result<PathBuf, std::io::Error> { // Normalize both paths, to avoid intermediate `..` components. let path = normalize_path(path.as_ref()); let base = normalize_path(base.as_ref()); // Find the longest common prefix, and also return the path stripped from that prefix let (stripped, common_prefix) = base .ancestors() .find_map(|ancestor| { // Simplifying removes the UNC path prefix on windows. dunce::simplified(&path) .strip_prefix(dunce::simplified(ancestor)) .ok() .map(|stripped| (stripped, ancestor)) }) .ok_or_else(|| { std::io::Error::other(format!( "Trivial strip failed: {} vs. {}", path.simplified_display(), base.simplified_display() )) })?; // go as many levels up as required let levels_up = base.components().count() - common_prefix.components().count(); let up = std::iter::repeat_n("..", levels_up).collect::<PathBuf>(); Ok(up.join(stripped)) } /// A path that can be serialized and deserialized in a portable way by converting Windows-style /// backslashes to forward slashes, and using a `.` for an empty path. /// /// This implementation assumes that the path is valid UTF-8; otherwise, it won't roundtrip. #[derive(Debug, Clone, PartialEq, Eq)] pub struct PortablePath<'a>(&'a Path); #[derive(Debug, Clone, PartialEq, Eq)] pub struct PortablePathBuf(Box<Path>); #[cfg(feature = "schemars")] impl schemars::JsonSchema for PortablePathBuf { fn schema_name() -> Cow<'static, str> { Cow::Borrowed("PortablePathBuf") } fn json_schema(_gen: &mut schemars::generate::SchemaGenerator) -> schemars::Schema { PathBuf::json_schema(_gen) } } impl AsRef<Path> for PortablePath<'_> { fn as_ref(&self) -> &Path { self.0 } } impl<'a, T> From<&'a T> for PortablePath<'a> where T: AsRef<Path> + ?Sized, { fn from(path: &'a T) -> Self { PortablePath(path.as_ref()) } } impl std::fmt::Display for PortablePath<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let path = self.0.to_slash_lossy(); if path.is_empty() { write!(f, ".") } else { write!(f, "{path}") } } } impl std::fmt::Display for PortablePathBuf { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let path = self.0.to_slash_lossy(); if path.is_empty() { write!(f, ".") } else { write!(f, "{path}") } } } impl From<&str> for PortablePathBuf { fn from(path: &str) -> Self { if path == "." { Self(PathBuf::new().into_boxed_path()) } else { Self(PathBuf::from(path).into_boxed_path()) } } } impl From<PortablePathBuf> for Box<Path> { fn from(portable: PortablePathBuf) -> Self { portable.0 } } impl From<Box<Path>> for PortablePathBuf { fn from(path: Box<Path>) -> Self { Self(path) } } impl<'a> From<&'a Path> for PortablePathBuf { fn from(path: &'a Path) -> Self { Box::<Path>::from(path).into() } } #[cfg(feature = "serde")] impl serde::Serialize for PortablePathBuf { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { self.to_string().serialize(serializer) } } #[cfg(feature = "serde")] impl serde::Serialize for PortablePath<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { self.to_string().serialize(serializer) } } #[cfg(feature = "serde")] impl<'de> serde::de::Deserialize<'de> for PortablePathBuf { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { let s = String::deserialize(deserializer)?; if s == "." { Ok(Self(PathBuf::new().into_boxed_path())) } else { Ok(Self(PathBuf::from(s).into_boxed_path())) } } } impl AsRef<Path> for PortablePathBuf { fn as_ref(&self) -> &Path { &self.0 } } #[cfg(test)] mod tests { use super::*; #[test] fn test_normalize_url() { if cfg!(windows) { assert_eq!( normalize_url_path("/C:/Users/ferris/wheel-0.42.0.tar.gz"), "C:\\Users\\ferris\\wheel-0.42.0.tar.gz" ); } else { assert_eq!( normalize_url_path("/C:/Users/ferris/wheel-0.42.0.tar.gz"), "/C:/Users/ferris/wheel-0.42.0.tar.gz" ); } if cfg!(windows) { assert_eq!( normalize_url_path("./ferris/wheel-0.42.0.tar.gz"), ".\\ferris\\wheel-0.42.0.tar.gz" ); } else { assert_eq!( normalize_url_path("./ferris/wheel-0.42.0.tar.gz"), "./ferris/wheel-0.42.0.tar.gz" ); } if cfg!(windows) { assert_eq!( normalize_url_path("./wheel%20cache/wheel-0.42.0.tar.gz"), ".\\wheel cache\\wheel-0.42.0.tar.gz" ); } else { assert_eq!( normalize_url_path("./wheel%20cache/wheel-0.42.0.tar.gz"), "./wheel cache/wheel-0.42.0.tar.gz" ); } } #[test] fn test_normalize_path() { let path = Path::new("/a/b/../c/./d"); let normalized = normalize_absolute_path(path).unwrap(); assert_eq!(normalized, Path::new("/a/c/d")); let path = Path::new("/a/../c/./d"); let normalized = normalize_absolute_path(path).unwrap(); assert_eq!(normalized, Path::new("/c/d")); // This should be an error. let path = Path::new("/a/../../c/./d"); let err = normalize_absolute_path(path).unwrap_err(); assert_eq!(err.kind(), std::io::ErrorKind::InvalidInput); } #[test] fn test_relative_to() { assert_eq!( relative_to( Path::new("/home/ferris/carcinization/lib/python/site-packages/foo/__init__.py"), Path::new("/home/ferris/carcinization/lib/python/site-packages"), ) .unwrap(), Path::new("foo/__init__.py") ); assert_eq!( relative_to( Path::new("/home/ferris/carcinization/lib/marker.txt"), Path::new("/home/ferris/carcinization/lib/python/site-packages"), ) .unwrap(), Path::new("../../marker.txt") ); assert_eq!( relative_to( Path::new("/home/ferris/carcinization/bin/foo_launcher"), Path::new("/home/ferris/carcinization/lib/python/site-packages"), ) .unwrap(), Path::new("../../../bin/foo_launcher") ); } #[test] fn test_normalize_relative() { let cases = [ ( "../../workspace-git-path-dep-test/packages/c/../../packages/d", "../../workspace-git-path-dep-test/packages/d", ), ( "workspace-git-path-dep-test/packages/c/../../packages/d", "workspace-git-path-dep-test/packages/d", ), ("./a/../../b", "../b"), ("/usr/../../foo", "/../foo"), ]; for (input, expected) in cases { assert_eq!(normalize_path(Path::new(input)), Path::new(expected)); } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-fs/src/lib.rs
crates/uv-fs/src/lib.rs
use std::borrow::Cow; use std::path::{Path, PathBuf}; use tempfile::NamedTempFile; use tracing::warn; pub use crate::locked_file::*; pub use crate::path::*; pub mod cachedir; mod locked_file; mod path; pub mod which; /// Append an extension to a [`PathBuf`]. /// /// Unlike [`Path::with_extension`], this function does not replace an existing extension. /// /// If there is no file name, the path is returned unchanged. /// /// This mimics the behavior of the unstable [`Path::with_added_extension`] method. pub fn with_added_extension<'a>(path: &'a Path, extension: &str) -> Cow<'a, Path> { let Some(name) = path.file_name() else { // If there is no file name, we cannot add an extension. return Cow::Borrowed(path); }; let mut name = name.to_os_string(); name.push("."); name.push(extension.trim_start_matches('.')); Cow::Owned(path.with_file_name(name)) } /// Attempt to check if the two paths refer to the same file. /// /// Returns `Some(true)` if the files are missing, but would be the same if they existed. pub fn is_same_file_allow_missing(left: &Path, right: &Path) -> Option<bool> { // First, check an exact path comparison. if left == right { return Some(true); } // Second, check the files directly. if let Ok(value) = same_file::is_same_file(left, right) { return Some(value); } // Often, one of the directories won't exist yet so perform the comparison up a level. if let (Some(left_parent), Some(right_parent), Some(left_name), Some(right_name)) = ( left.parent(), right.parent(), left.file_name(), right.file_name(), ) { match same_file::is_same_file(left_parent, right_parent) { Ok(true) => return Some(left_name == right_name), Ok(false) => return Some(false), _ => (), } } // We couldn't determine if they're the same. None } /// Reads data from the path and requires that it be valid UTF-8 or UTF-16. /// /// This uses BOM sniffing to determine if the data should be transcoded /// from UTF-16 to Rust's `String` type (which uses UTF-8). /// /// This should generally only be used when one specifically wants to support /// reading UTF-16 transparently. /// /// If the file path is `-`, then contents are read from stdin instead. #[cfg(feature = "tokio")] pub async fn read_to_string_transcode(path: impl AsRef<Path>) -> std::io::Result<String> { use std::io::Read; use encoding_rs_io::DecodeReaderBytes; let path = path.as_ref(); let raw = if path == Path::new("-") { let mut buf = Vec::with_capacity(1024); std::io::stdin().read_to_end(&mut buf)?; buf } else { fs_err::tokio::read(path).await? }; let mut buf = String::with_capacity(1024); DecodeReaderBytes::new(&*raw) .read_to_string(&mut buf) .map_err(|err| { let path = path.display(); std::io::Error::other(format!("failed to decode file {path}: {err}")) })?; Ok(buf) } /// Create a symlink at `dst` pointing to `src`, replacing any existing symlink. /// /// On Windows, this uses the `junction` crate to create a junction point. The /// operation is _not_ atomic, as we first delete the junction, then create a /// junction at the same path. /// /// Note that because junctions are used, the source must be a directory. /// /// Changes to this function should be reflected in [`create_symlink`]. #[cfg(windows)] pub fn replace_symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { // If the source is a file, we can't create a junction if src.as_ref().is_file() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!( "Cannot create a junction for {}: is not a directory", src.as_ref().display() ), )); } // Remove the existing symlink, if any. match junction::delete(dunce::simplified(dst.as_ref())) { Ok(()) => match fs_err::remove_dir_all(dst.as_ref()) { Ok(()) => {} Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err), }, Err(err) if err.kind() == std::io::ErrorKind::NotFound => {} Err(err) => return Err(err), } // Replace it with a new symlink. junction::create( dunce::simplified(src.as_ref()), dunce::simplified(dst.as_ref()), ) } /// Create a symlink at `dst` pointing to `src`, replacing any existing symlink if necessary. /// /// On Unix, this method creates a temporary file, then moves it into place. #[cfg(unix)] pub fn replace_symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { // Attempt to create the symlink directly. match fs_err::os::unix::fs::symlink(src.as_ref(), dst.as_ref()) { Ok(()) => Ok(()), Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => { // Create a symlink, using a temporary file to ensure atomicity. let temp_dir = tempfile::tempdir_in(dst.as_ref().parent().unwrap())?; let temp_file = temp_dir.path().join("link"); fs_err::os::unix::fs::symlink(src, &temp_file)?; // Move the symlink into the target location. fs_err::rename(&temp_file, dst.as_ref())?; Ok(()) } Err(err) => Err(err), } } /// Create a symlink at `dst` pointing to `src`. /// /// On Windows, this uses the `junction` crate to create a junction point. /// /// Note that because junctions are used, the source must be a directory. /// /// Changes to this function should be reflected in [`replace_symlink`]. #[cfg(windows)] pub fn create_symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { // If the source is a file, we can't create a junction if src.as_ref().is_file() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, format!( "Cannot create a junction for {}: is not a directory", src.as_ref().display() ), )); } junction::create( dunce::simplified(src.as_ref()), dunce::simplified(dst.as_ref()), ) } /// Create a symlink at `dst` pointing to `src`. #[cfg(unix)] pub fn create_symlink(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { fs_err::os::unix::fs::symlink(src.as_ref(), dst.as_ref()) } #[cfg(unix)] pub fn remove_symlink(path: impl AsRef<Path>) -> std::io::Result<()> { fs_err::remove_file(path.as_ref()) } /// Create a symlink at `dst` pointing to `src` on Unix or copy `src` to `dst` on Windows /// /// This does not replace an existing symlink or file at `dst`. /// /// This does not fallback to copying on Unix. /// /// This function should only be used for files. If targeting a directory, use [`replace_symlink`] /// instead; it will use a junction on Windows, which is more performant. pub fn symlink_or_copy_file(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { #[cfg(windows)] { fs_err::copy(src.as_ref(), dst.as_ref())?; } #[cfg(unix)] { fs_err::os::unix::fs::symlink(src.as_ref(), dst.as_ref())?; } Ok(()) } #[cfg(windows)] pub fn remove_symlink(path: impl AsRef<Path>) -> std::io::Result<()> { match junction::delete(dunce::simplified(path.as_ref())) { Ok(()) => match fs_err::remove_dir_all(path.as_ref()) { Ok(()) => Ok(()), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(err) => Err(err), }, Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(err) => Err(err), } } /// Return a [`NamedTempFile`] in the specified directory. /// /// Sets the permissions of the temporary file to `0o666`, to match the non-temporary file default. /// ([`NamedTempfile`] defaults to `0o600`.) #[cfg(unix)] pub fn tempfile_in(path: &Path) -> std::io::Result<NamedTempFile> { use std::os::unix::fs::PermissionsExt; tempfile::Builder::new() .permissions(std::fs::Permissions::from_mode(0o666)) .tempfile_in(path) } /// Return a [`NamedTempFile`] in the specified directory. #[cfg(not(unix))] pub fn tempfile_in(path: &Path) -> std::io::Result<NamedTempFile> { tempfile::Builder::new().tempfile_in(path) } /// Write `data` to `path` atomically using a temporary file and atomic rename. #[cfg(feature = "tokio")] pub async fn write_atomic(path: impl AsRef<Path>, data: impl AsRef<[u8]>) -> std::io::Result<()> { let temp_file = tempfile_in( path.as_ref() .parent() .expect("Write path must have a parent"), )?; fs_err::tokio::write(&temp_file, &data).await?; persist_with_retry(temp_file, path.as_ref()).await } /// Write `data` to `path` atomically using a temporary file and atomic rename. pub fn write_atomic_sync(path: impl AsRef<Path>, data: impl AsRef<[u8]>) -> std::io::Result<()> { let temp_file = tempfile_in( path.as_ref() .parent() .expect("Write path must have a parent"), )?; fs_err::write(&temp_file, &data)?; persist_with_retry_sync(temp_file, path.as_ref()) } /// Copy `from` to `to` atomically using a temporary file and atomic rename. pub fn copy_atomic_sync(from: impl AsRef<Path>, to: impl AsRef<Path>) -> std::io::Result<()> { let temp_file = tempfile_in(to.as_ref().parent().expect("Write path must have a parent"))?; fs_err::copy(from.as_ref(), &temp_file)?; persist_with_retry_sync(temp_file, to.as_ref()) } #[cfg(windows)] fn backoff_file_move() -> backon::ExponentialBackoff { use backon::BackoffBuilder; // This amounts to 10 total seconds of trying the operation. // We start at 10 milliseconds and try 9 times, doubling each time, so the last try will take // about 10*(2^9) milliseconds ~= 5 seconds. All other attempts combined should equal // the length of the last attempt (because it's a sum of powers of 2), so 10 seconds overall. backon::ExponentialBuilder::default() .with_min_delay(std::time::Duration::from_millis(10)) .with_max_times(9) .build() } /// Rename a file, retrying (on Windows) if it fails due to transient operating system errors. #[cfg(feature = "tokio")] pub async fn rename_with_retry( from: impl AsRef<Path>, to: impl AsRef<Path>, ) -> Result<(), std::io::Error> { #[cfg(windows)] { use backon::Retryable; // On Windows, antivirus software can lock files temporarily, making them inaccessible. // This is most common for DLLs, and the common suggestion is to retry the operation with // some backoff. // // See: <https://github.com/astral-sh/uv/issues/1491> & <https://github.com/astral-sh/uv/issues/9531> let from = from.as_ref(); let to = to.as_ref(); let rename = async || fs_err::rename(from, to); rename .retry(backoff_file_move()) .sleep(tokio::time::sleep) .when(|e| e.kind() == std::io::ErrorKind::PermissionDenied) .notify(|err, _dur| { warn!( "Retrying rename from {} to {} due to transient error: {}", from.display(), to.display(), err ); }) .await } #[cfg(not(windows))] { fs_err::tokio::rename(from, to).await } } /// Rename or copy a file, retrying (on Windows) if it fails due to transient operating system /// errors, in a synchronous context. #[cfg_attr(not(windows), allow(unused_variables))] pub fn with_retry_sync( from: impl AsRef<Path>, to: impl AsRef<Path>, operation_name: &str, operation: impl Fn() -> Result<(), std::io::Error>, ) -> Result<(), std::io::Error> { #[cfg(windows)] { use backon::BlockingRetryable; // On Windows, antivirus software can lock files temporarily, making them inaccessible. // This is most common for DLLs, and the common suggestion is to retry the operation with // some backoff. // // See: <https://github.com/astral-sh/uv/issues/1491> & <https://github.com/astral-sh/uv/issues/9531> let from = from.as_ref(); let to = to.as_ref(); operation .retry(backoff_file_move()) .sleep(std::thread::sleep) .when(|err| err.kind() == std::io::ErrorKind::PermissionDenied) .notify(|err, _dur| { warn!( "Retrying {} from {} to {} due to transient error: {}", operation_name, from.display(), to.display(), err ); }) .call() .map_err(|err| { std::io::Error::other(format!( "Failed {} {} to {}: {}", operation_name, from.display(), to.display(), err )) }) } #[cfg(not(windows))] { operation() } } /// Why a file persist failed #[cfg(windows)] enum PersistRetryError { /// Something went wrong while persisting, maybe retry (contains error message) Persist(String), /// Something went wrong trying to retrieve the file to persist, we must bail LostState, } /// Persist a `NamedTempFile`, retrying (on Windows) if it fails due to transient operating system errors, in a synchronous context. pub async fn persist_with_retry( from: NamedTempFile, to: impl AsRef<Path>, ) -> Result<(), std::io::Error> { #[cfg(windows)] { use backon::Retryable; // On Windows, antivirus software can lock files temporarily, making them inaccessible. // This is most common for DLLs, and the common suggestion is to retry the operation with // some backoff. // // See: <https://github.com/astral-sh/uv/issues/1491> & <https://github.com/astral-sh/uv/issues/9531> let to = to.as_ref(); // Ok there's a lot of complex ownership stuff going on here. // // the `NamedTempFile` `persist` method consumes `self`, and returns it back inside // the Error in case of `PersistError`: // https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html#method.persist // So every time we fail, we need to reset the `NamedTempFile` to try again. // // Every time we (re)try we call this outer closure (`let persist = ...`), so it needs to // be at least a `FnMut` (as opposed to `Fnonce`). However the closure needs to return a // totally owned `Future` (so effectively it returns a `FnOnce`). // // But if the `Future` is totally owned it *necessarily* can't write back the `NamedTempFile` // to somewhere the outer `FnMut` can see using references. So we need to use `Arc`s // with interior mutability (`Mutex`) to have the closure and all the Futures it creates share // a single memory location that the `NamedTempFile` can be shuttled in and out of. // // In spite of the Mutex all of this code will run logically serially, so there shouldn't be a // chance for a race where we try to get the `NamedTempFile` but it's actually None. The code // is just written pedantically/robustly. let from = std::sync::Arc::new(std::sync::Mutex::new(Some(from))); let persist = || { // Turn our by-ref-captured Arc into an owned Arc that the Future can capture by-value let from2 = from.clone(); async move { let maybe_file: Option<NamedTempFile> = from2 .lock() .map_err(|_| PersistRetryError::LostState)? .take(); if let Some(file) = maybe_file { file.persist(to).map_err(|err| { let error_message: String = err.to_string(); // Set back the `NamedTempFile` returned back by the Error if let Ok(mut guard) = from2.lock() { *guard = Some(err.file); PersistRetryError::Persist(error_message) } else { PersistRetryError::LostState } }) } else { Err(PersistRetryError::LostState) } } }; let persisted = persist .retry(backoff_file_move()) .sleep(tokio::time::sleep) .when(|err| matches!(err, PersistRetryError::Persist(_))) .notify(|err, _dur| { if let PersistRetryError::Persist(error_message) = err { warn!( "Retrying to persist temporary file to {}: {}", to.display(), error_message, ); } }) .await; match persisted { Ok(_) => Ok(()), Err(PersistRetryError::Persist(error_message)) => Err(std::io::Error::other(format!( "Failed to persist temporary file to {}: {}", to.display(), error_message, ))), Err(PersistRetryError::LostState) => Err(std::io::Error::other(format!( "Failed to retrieve temporary file while trying to persist to {}", to.display() ))), } } #[cfg(not(windows))] { async { fs_err::rename(from, to) }.await } } /// Persist a `NamedTempFile`, retrying (on Windows) if it fails due to transient operating system errors, in a synchronous context. pub fn persist_with_retry_sync( from: NamedTempFile, to: impl AsRef<Path>, ) -> Result<(), std::io::Error> { #[cfg(windows)] { use backon::BlockingRetryable; // On Windows, antivirus software can lock files temporarily, making them inaccessible. // This is most common for DLLs, and the common suggestion is to retry the operation with // some backoff. // // See: <https://github.com/astral-sh/uv/issues/1491> & <https://github.com/astral-sh/uv/issues/9531> let to = to.as_ref(); // the `NamedTempFile` `persist` method consumes `self`, and returns it back inside the Error in case of `PersistError` // https://docs.rs/tempfile/latest/tempfile/struct.NamedTempFile.html#method.persist // So we will update the `from` optional value in safe and borrow-checker friendly way every retry // Allows us to use the NamedTempFile inside a FnMut closure used for backoff::retry let mut from = Some(from); let persist = || { // Needed because we cannot move out of `from`, a captured variable in an `FnMut` closure, and then pass it to the async move block if let Some(file) = from.take() { file.persist(to).map_err(|err| { let error_message = err.to_string(); // Set back the NamedTempFile returned back by the Error from = Some(err.file); PersistRetryError::Persist(error_message) }) } else { Err(PersistRetryError::LostState) } }; let persisted = persist .retry(backoff_file_move()) .sleep(std::thread::sleep) .when(|err| matches!(err, PersistRetryError::Persist(_))) .notify(|err, _dur| { if let PersistRetryError::Persist(error_message) = err { warn!( "Retrying to persist temporary file to {}: {}", to.display(), error_message, ); } }) .call(); match persisted { Ok(_) => Ok(()), Err(PersistRetryError::Persist(error_message)) => Err(std::io::Error::other(format!( "Failed to persist temporary file to {}: {}", to.display(), error_message, ))), Err(PersistRetryError::LostState) => Err(std::io::Error::other(format!( "Failed to retrieve temporary file while trying to persist to {}", to.display() ))), } } #[cfg(not(windows))] { fs_err::rename(from, to) } } /// Iterate over the subdirectories of a directory. /// /// If the directory does not exist, returns an empty iterator. pub fn directories( path: impl AsRef<Path>, ) -> Result<impl Iterator<Item = PathBuf>, std::io::Error> { let entries = match path.as_ref().read_dir() { Ok(entries) => Some(entries), Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, Err(err) => return Err(err), }; Ok(entries .into_iter() .flatten() .filter_map(|entry| match entry { Ok(entry) => Some(entry), Err(err) => { warn!("Failed to read entry: {err}"); None } }) .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir())) .map(|entry| entry.path())) } /// Iterate over the entries in a directory. /// /// If the directory does not exist, returns an empty iterator. pub fn entries(path: impl AsRef<Path>) -> Result<impl Iterator<Item = PathBuf>, std::io::Error> { let entries = match path.as_ref().read_dir() { Ok(entries) => Some(entries), Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, Err(err) => return Err(err), }; Ok(entries .into_iter() .flatten() .filter_map(|entry| match entry { Ok(entry) => Some(entry), Err(err) => { warn!("Failed to read entry: {err}"); None } }) .map(|entry| entry.path())) } /// Iterate over the files in a directory. /// /// If the directory does not exist, returns an empty iterator. pub fn files(path: impl AsRef<Path>) -> Result<impl Iterator<Item = PathBuf>, std::io::Error> { let entries = match path.as_ref().read_dir() { Ok(entries) => Some(entries), Err(err) if err.kind() == std::io::ErrorKind::NotFound => None, Err(err) => return Err(err), }; Ok(entries .into_iter() .flatten() .filter_map(|entry| match entry { Ok(entry) => Some(entry), Err(err) => { warn!("Failed to read entry: {err}"); None } }) .filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_file())) .map(|entry| entry.path())) } /// Returns `true` if a path is a temporary file or directory. pub fn is_temporary(path: impl AsRef<Path>) -> bool { path.as_ref() .file_name() .and_then(|name| name.to_str()) .is_some_and(|name| name.starts_with(".tmp")) } /// Checks if the grandparent directory of the given executable is the base /// of a virtual environment. /// /// The procedure described in PEP 405 includes checking both the parent and /// grandparent directory of an executable, but in practice we've found this to /// be unnecessary. pub fn is_virtualenv_executable(executable: impl AsRef<Path>) -> bool { executable .as_ref() .parent() .and_then(Path::parent) .is_some_and(is_virtualenv_base) } /// Returns `true` if a path is the base path of a virtual environment, /// indicated by the presence of a `pyvenv.cfg` file. /// /// The procedure described in PEP 405 includes scanning `pyvenv.cfg` /// for a `home` key, but in practice we've found this to be /// unnecessary. pub fn is_virtualenv_base(path: impl AsRef<Path>) -> bool { path.as_ref().join("pyvenv.cfg").is_file() } /// Whether the error is due to a lock being held. fn is_known_already_locked_error(err: &std::fs::TryLockError) -> bool { match err { std::fs::TryLockError::WouldBlock => true, std::fs::TryLockError::Error(err) => { // On Windows, we've seen: Os { code: 33, kind: Uncategorized, message: "The process cannot access the file because another process has locked a portion of the file." } if cfg!(windows) && err.raw_os_error() == Some(33) { return true; } false } } } /// An asynchronous reader that reports progress as bytes are read. #[cfg(feature = "tokio")] pub struct ProgressReader<Reader: tokio::io::AsyncRead + Unpin, Callback: Fn(usize) + Unpin> { reader: Reader, callback: Callback, } #[cfg(feature = "tokio")] impl<Reader: tokio::io::AsyncRead + Unpin, Callback: Fn(usize) + Unpin> ProgressReader<Reader, Callback> { /// Create a new [`ProgressReader`] that wraps another reader. pub fn new(reader: Reader, callback: Callback) -> Self { Self { reader, callback } } } #[cfg(feature = "tokio")] impl<Reader: tokio::io::AsyncRead + Unpin, Callback: Fn(usize) + Unpin> tokio::io::AsyncRead for ProgressReader<Reader, Callback> { fn poll_read( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut tokio::io::ReadBuf<'_>, ) -> std::task::Poll<std::io::Result<()>> { std::pin::Pin::new(&mut self.as_mut().reader) .poll_read(cx, buf) .map_ok(|()| { (self.callback)(buf.filled().len()); }) } } /// Recursively copy a directory and its contents. pub fn copy_dir_all(src: impl AsRef<Path>, dst: impl AsRef<Path>) -> std::io::Result<()> { fs_err::create_dir_all(&dst)?; for entry in fs_err::read_dir(src.as_ref())? { let entry = entry?; let ty = entry.file_type()?; if ty.is_dir() { copy_dir_all(entry.path(), dst.as_ref().join(entry.file_name()))?; } else { fs_err::copy(entry.path(), dst.as_ref().join(entry.file_name()))?; } } Ok(()) } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; #[test] fn test_with_added_extension() { // Test with simple package name (no dots) let path = PathBuf::from("python"); let result = with_added_extension(&path, "exe"); assert_eq!(result, PathBuf::from("python.exe")); // Test with package name containing single dot let path = PathBuf::from("awslabs.cdk-mcp-server"); let result = with_added_extension(&path, "exe"); assert_eq!(result, PathBuf::from("awslabs.cdk-mcp-server.exe")); // Test with package name containing multiple dots let path = PathBuf::from("org.example.tool"); let result = with_added_extension(&path, "exe"); assert_eq!(result, PathBuf::from("org.example.tool.exe")); // Test with different extensions let path = PathBuf::from("script"); let result = with_added_extension(&path, "ps1"); assert_eq!(result, PathBuf::from("script.ps1")); // Test with path that has directory components let path = PathBuf::from("some/path/to/awslabs.cdk-mcp-server"); let result = with_added_extension(&path, "exe"); assert_eq!( result, PathBuf::from("some/path/to/awslabs.cdk-mcp-server.exe") ); // Test with empty path (edge case) let path = PathBuf::new(); let result = with_added_extension(&path, "exe"); assert_eq!(result, path); // Should return unchanged } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-fs/src/which.rs
crates/uv-fs/src/which.rs
use std::path::Path; #[cfg(windows)] #[allow(unsafe_code)] // We need to do an FFI call through the windows-* crates. fn get_binary_type(path: &Path) -> windows::core::Result<u32> { use std::os::windows::ffi::OsStrExt; use windows::Win32::Storage::FileSystem::GetBinaryTypeW; use windows::core::PCWSTR; // References: // https://github.com/denoland/deno/blob/01a6379505712be34ebf2cdc874fa7f54a6e9408/runtime/permissions/which.rs#L131-L154 // https://github.com/conradkleinespel/rooster/blob/afa78dc9918535752c4af59d2f812197ad754e5a/src/quale.rs#L51-L77 let mut binary_type = 0u32; let name = path .as_os_str() .encode_wide() .chain(Some(0)) .collect::<Vec<u16>>(); // SAFETY: winapi call unsafe { GetBinaryTypeW(PCWSTR(name.as_ptr()), &raw mut binary_type)? }; Ok(binary_type) } /// Check whether a path in PATH is a valid executable. /// /// Derived from `which`'s `Checker`. pub fn is_executable(path: &Path) -> bool { #[cfg(any(unix, target_os = "wasi", target_os = "redox"))] { if rustix::fs::access(path, rustix::fs::Access::EXEC_OK).is_err() { return false; } } #[cfg(target_os = "windows")] { let Ok(file_type) = fs_err::symlink_metadata(path).map(|metadata| metadata.file_type()) else { return false; }; if !file_type.is_file() && !file_type.is_symlink() { return false; } if path.extension().is_none() && get_binary_type(path).is_err() { return false; } } #[cfg(not(target_os = "windows"))] { use std::os::unix::fs::PermissionsExt; if !fs_err::metadata(path) .map(|metadata| metadata.is_file() && metadata.permissions().mode() & 0o111 != 0) .unwrap_or(false) { return false; } } true }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-fs/src/locked_file.rs
crates/uv-fs/src/locked_file.rs
use std::convert::Into; use std::fmt::Display; use std::path::{Path, PathBuf}; use std::sync::LazyLock; use std::time::Duration; use std::{env, io}; use thiserror::Error; use tracing::{debug, error, info, trace, warn}; use uv_static::EnvVars; use crate::{Simplified, is_known_already_locked_error}; /// Parsed value of `UV_LOCK_TIMEOUT`, with a default of 5 min. static LOCK_TIMEOUT: LazyLock<Duration> = LazyLock::new(|| { let default_timeout = Duration::from_secs(300); let Some(lock_timeout) = env::var_os(EnvVars::UV_LOCK_TIMEOUT) else { return default_timeout; }; if let Some(lock_timeout) = lock_timeout .to_str() .and_then(|lock_timeout| lock_timeout.parse::<u64>().ok()) { Duration::from_secs(lock_timeout) } else { warn!( "Could not parse value of {} as integer: {:?}", EnvVars::UV_LOCK_TIMEOUT, lock_timeout ); default_timeout } }); #[derive(Debug, Error)] pub enum LockedFileError { #[error( "Timeout ({}s) when waiting for lock on `{}` at `{}`, is another uv process running? You can set `{}` to increase the timeout.", timeout.as_secs(), resource, path.user_display(), EnvVars::UV_LOCK_TIMEOUT )] Timeout { timeout: Duration, resource: String, path: PathBuf, }, #[error( "Could not acquire lock for `{}` at `{}`", resource, path.user_display() )] Lock { resource: String, path: PathBuf, #[source] source: io::Error, }, #[error(transparent)] #[cfg(feature = "tokio")] JoinError(#[from] tokio::task::JoinError), #[error("Could not create temporary file")] CreateTemporary(#[source] io::Error), #[error("Could not persist temporary file `{}`", path.user_display())] PersistTemporary { path: PathBuf, #[source] source: io::Error, }, #[error(transparent)] Io(#[from] io::Error), } impl LockedFileError { pub fn as_io_error(&self) -> Option<&io::Error> { match self { Self::Timeout { .. } => None, #[cfg(feature = "tokio")] Self::JoinError(_) => None, Self::Lock { source, .. } => Some(source), Self::CreateTemporary(err) => Some(err), Self::PersistTemporary { source, .. } => Some(source), Self::Io(err) => Some(err), } } } /// Whether to acquire a shared (read) lock or exclusive (write) lock. #[derive(Debug, Clone, Copy)] pub enum LockedFileMode { Shared, Exclusive, } impl LockedFileMode { /// Try to lock the file and return an error if the lock is already acquired by another process /// and cannot be acquired immediately. fn try_lock(self, file: &fs_err::File) -> Result<(), std::fs::TryLockError> { match self { Self::Exclusive => file.try_lock()?, Self::Shared => file.try_lock_shared()?, } Ok(()) } /// Lock the file, blocking until the lock becomes available if necessary. fn lock(self, file: &fs_err::File) -> Result<(), io::Error> { match self { Self::Exclusive => file.lock()?, Self::Shared => file.lock_shared()?, } Ok(()) } } impl Display for LockedFileMode { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Shared => write!(f, "shared"), Self::Exclusive => write!(f, "exclusive"), } } } /// A file lock that is automatically released when dropped. #[cfg(feature = "tokio")] #[derive(Debug)] #[must_use] pub struct LockedFile(fs_err::File); #[cfg(feature = "tokio")] impl LockedFile { /// Inner implementation for [`LockedFile::acquire`]. async fn lock_file( file: fs_err::File, mode: LockedFileMode, resource: &str, ) -> Result<Self, LockedFileError> { trace!( "Checking lock for `{resource}` at `{}`", file.path().user_display() ); // If there's no contention, return directly. let try_lock_exclusive = tokio::task::spawn_blocking(move || (mode.try_lock(&file), file)); let file = match try_lock_exclusive.await? { (Ok(()), file) => { debug!("Acquired {mode} lock for `{resource}`"); return Ok(Self(file)); } (Err(err), file) => { // Log error code and enum kind to help debugging more exotic failures. if !is_known_already_locked_error(&err) { debug!("Try lock {mode} error: {err:?}"); } file } }; // If there's lock contention, wait and break deadlocks with a timeout if necessary. info!( "Waiting to acquire {mode} lock for `{resource}` at `{}`", file.path().user_display(), ); let path = file.path().to_path_buf(); let lock_exclusive = tokio::task::spawn_blocking(move || (mode.lock(&file), file)); let (result, file) = tokio::time::timeout(*LOCK_TIMEOUT, lock_exclusive) .await .map_err(|_| LockedFileError::Timeout { timeout: *LOCK_TIMEOUT, resource: resource.to_string(), path: path.clone(), })??; // Not an fs_err method, we need to build our own path context result.map_err(|err| LockedFileError::Lock { resource: resource.to_string(), path, source: err, })?; debug!("Acquired {mode} lock for `{resource}`"); Ok(Self(file)) } /// Inner implementation for [`LockedFile::acquire_no_wait`]. fn lock_file_no_wait(file: fs_err::File, mode: LockedFileMode, resource: &str) -> Option<Self> { trace!( "Checking lock for `{resource}` at `{}`", file.path().user_display() ); match mode.try_lock(&file) { Ok(()) => { debug!("Acquired {mode} lock for `{resource}`"); Some(Self(file)) } Err(err) => { // Log error code and enum kind to help debugging more exotic failures. if !is_known_already_locked_error(&err) { debug!("Try lock error: {err:?}"); } debug!("Lock is busy for `{resource}`"); None } } } /// Acquire a cross-process lock for a resource using a file at the provided path. pub async fn acquire( path: impl AsRef<Path>, mode: LockedFileMode, resource: impl Display, ) -> Result<Self, LockedFileError> { let file = Self::create(&path)?; let resource = resource.to_string(); Self::lock_file(file, mode, &resource).await } /// Acquire a cross-process lock for a resource using a file at the provided path /// /// Unlike [`LockedFile::acquire`] this function will not wait for the lock to become available. /// /// If the lock is not immediately available, [`None`] is returned. pub fn acquire_no_wait( path: impl AsRef<Path>, mode: LockedFileMode, resource: impl Display, ) -> Option<Self> { let file = Self::create(path).ok()?; let resource = resource.to_string(); Self::lock_file_no_wait(file, mode, &resource) } #[cfg(unix)] fn create(path: impl AsRef<Path>) -> Result<fs_err::File, LockedFileError> { use rustix::io::Errno; #[allow(clippy::disallowed_types)] use std::{fs::File, os::unix::fs::PermissionsExt}; use tempfile::NamedTempFile; /// The permissions the lockfile should end up with const DESIRED_MODE: u32 = 0o666; #[allow(clippy::disallowed_types)] fn try_set_permissions(file: &File, path: &Path) { if let Err(err) = file.set_permissions(std::fs::Permissions::from_mode(DESIRED_MODE)) { warn!( "Failed to set permissions on temporary file `{path}`: {err}", path = path.user_display() ); } } // If path already exists, return it. if let Ok(file) = fs_err::OpenOptions::new() .read(true) .write(true) .open(path.as_ref()) { return Ok(file); } // Otherwise, create a temporary file with 666 permissions. We must set // permissions _after_ creating the file, to override the `umask`. let file = if let Some(parent) = path.as_ref().parent() { NamedTempFile::new_in(parent) } else { NamedTempFile::new() } .map_err(LockedFileError::CreateTemporary)?; try_set_permissions(file.as_file(), file.path()); // Try to move the file to path, but if path exists now, just open path match file.persist_noclobber(path.as_ref()) { Ok(file) => Ok(fs_err::File::from_parts(file, path.as_ref())), Err(err) => { if err.error.kind() == std::io::ErrorKind::AlreadyExists { fs_err::OpenOptions::new() .read(true) .write(true) .open(path.as_ref()) .map_err(Into::into) } else if matches!( Errno::from_io_error(&err.error), Some(Errno::NOTSUP | Errno::INVAL) ) { // Fallback in case `persist_noclobber`, which uses `renameat2` or // `renameatx_np` under the hood, is not supported by the FS. Linux reports this // with `EINVAL` and MacOS with `ENOTSUP`. For these reasons and many others, // there isn't an ErrorKind we can use here, and in fact on MacOS `ENOTSUP` gets // mapped to `ErrorKind::Other` // There is a race here where another process has just created the file, and we // try to open it and get permission errors because the other process hasn't set // the permission bits yet. This will lead to a transient failure, but unlike // alternative approaches it won't ever lead to a situation where two processes // are locking two different files. Also, since `persist_noclobber` is more // likely to not be supported on special filesystems which don't have permission // bits, it's less likely to ever matter. let file = fs_err::OpenOptions::new() .read(true) .write(true) .create(true) .open(path.as_ref())?; // We don't want to `try_set_permissions` in cases where another user's process // has already created the lockfile and changed its permissions because we might // not have permission to change the permissions which would produce a confusing // warning. if file .metadata() .is_ok_and(|metadata| metadata.permissions().mode() != DESIRED_MODE) { try_set_permissions(file.file(), path.as_ref()); } Ok(file) } else { let temp_path = err.file.into_temp_path(); Err(LockedFileError::PersistTemporary { path: <tempfile::TempPath as AsRef<Path>>::as_ref(&temp_path).to_path_buf(), source: err.error, }) } } } } #[cfg(not(unix))] fn create(path: impl AsRef<Path>) -> Result<fs_err::File, LockedFileError> { fs_err::OpenOptions::new() .read(true) .write(true) .create(true) .open(path.as_ref()) .map_err(Into::into) } } #[cfg(feature = "tokio")] impl Drop for LockedFile { /// Unlock the file. fn drop(&mut self) { if let Err(err) = self.0.unlock() { error!( "Failed to unlock resource at `{}`; program may be stuck: {err}", self.0.path().display() ); } else { debug!("Released lock at `{}`", self.0.path().display()); } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-torch/src/lib.rs
crates/uv-torch/src/lib.rs
mod accelerator; mod backend; pub use accelerator::*; pub use backend::*;
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-torch/src/backend.rs
crates/uv-torch/src/backend.rs
//! `uv-torch` is a library for determining the appropriate PyTorch index based on the operating //! system and CUDA driver version. //! //! This library is derived from `light-the-torch` by Philipp Meier, which is available under the //! following BSD-3 Clause license: //! //! ```text //! BSD 3-Clause License //! //! Copyright (c) 2020, Philip Meier //! All rights reserved. //! //! Redistribution and use in source and binary forms, with or without //! modification, are permitted provided that the following conditions are met: //! //! 1. Redistributions of source code must retain the above copyright notice, this //! list of conditions and the following disclaimer. //! //! 2. Redistributions in binary form must reproduce the above copyright notice, //! this list of conditions and the following disclaimer in the documentation //! and/or other materials provided with the distribution. //! //! 3. Neither the name of the copyright holder nor the names of its //! contributors may be used to endorse or promote products derived from //! this software without specific prior written permission. //! //! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" //! AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE //! IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //! DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE //! FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL //! DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR //! SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER //! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, //! OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE //! OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //! ``` use std::borrow::Cow; use std::str::FromStr; use std::sync::LazyLock; use either::Either; use url::Url; use uv_distribution_types::IndexUrl; use uv_normalize::PackageName; use uv_pep440::Version; use uv_platform_tags::Os; use uv_static::EnvVars; use crate::{Accelerator, AcceleratorError, AmdGpuArchitecture}; /// The strategy to use when determining the appropriate PyTorch index. #[derive(Debug, Copy, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub enum TorchMode { /// Select the appropriate PyTorch index based on the operating system and CUDA driver version. Auto, /// Use the CPU-only PyTorch index. Cpu, /// Use the PyTorch index for CUDA 13.0. Cu130, /// Use the PyTorch index for CUDA 12.9. Cu129, /// Use the PyTorch index for CUDA 12.8. Cu128, /// Use the PyTorch index for CUDA 12.6. Cu126, /// Use the PyTorch index for CUDA 12.5. Cu125, /// Use the PyTorch index for CUDA 12.4. Cu124, /// Use the PyTorch index for CUDA 12.3. Cu123, /// Use the PyTorch index for CUDA 12.2. Cu122, /// Use the PyTorch index for CUDA 12.1. Cu121, /// Use the PyTorch index for CUDA 12.0. Cu120, /// Use the PyTorch index for CUDA 11.8. Cu118, /// Use the PyTorch index for CUDA 11.7. Cu117, /// Use the PyTorch index for CUDA 11.6. Cu116, /// Use the PyTorch index for CUDA 11.5. Cu115, /// Use the PyTorch index for CUDA 11.4. Cu114, /// Use the PyTorch index for CUDA 11.3. Cu113, /// Use the PyTorch index for CUDA 11.2. Cu112, /// Use the PyTorch index for CUDA 11.1. Cu111, /// Use the PyTorch index for CUDA 11.0. Cu110, /// Use the PyTorch index for CUDA 10.2. Cu102, /// Use the PyTorch index for CUDA 10.1. Cu101, /// Use the PyTorch index for CUDA 10.0. Cu100, /// Use the PyTorch index for CUDA 9.2. Cu92, /// Use the PyTorch index for CUDA 9.1. Cu91, /// Use the PyTorch index for CUDA 9.0. Cu90, /// Use the PyTorch index for CUDA 8.0. Cu80, /// Use the PyTorch index for ROCm 6.4. #[serde(rename = "rocm6.4")] #[cfg_attr(feature = "clap", clap(name = "rocm6.4"))] Rocm64, /// Use the PyTorch index for ROCm 6.3. #[serde(rename = "rocm6.3")] #[cfg_attr(feature = "clap", clap(name = "rocm6.3"))] Rocm63, /// Use the PyTorch index for ROCm 6.2.4. #[serde(rename = "rocm6.2.4")] #[cfg_attr(feature = "clap", clap(name = "rocm6.2.4"))] Rocm624, /// Use the PyTorch index for ROCm 6.2. #[serde(rename = "rocm6.2")] #[cfg_attr(feature = "clap", clap(name = "rocm6.2"))] Rocm62, /// Use the PyTorch index for ROCm 6.1. #[serde(rename = "rocm6.1")] #[cfg_attr(feature = "clap", clap(name = "rocm6.1"))] Rocm61, /// Use the PyTorch index for ROCm 6.0. #[serde(rename = "rocm6.0")] #[cfg_attr(feature = "clap", clap(name = "rocm6.0"))] Rocm60, /// Use the PyTorch index for ROCm 5.7. #[serde(rename = "rocm5.7")] #[cfg_attr(feature = "clap", clap(name = "rocm5.7"))] Rocm57, /// Use the PyTorch index for ROCm 5.6. #[serde(rename = "rocm5.6")] #[cfg_attr(feature = "clap", clap(name = "rocm5.6"))] Rocm56, /// Use the PyTorch index for ROCm 5.5. #[serde(rename = "rocm5.5")] #[cfg_attr(feature = "clap", clap(name = "rocm5.5"))] Rocm55, /// Use the PyTorch index for ROCm 5.4.2. #[serde(rename = "rocm5.4.2")] #[cfg_attr(feature = "clap", clap(name = "rocm5.4.2"))] Rocm542, /// Use the PyTorch index for ROCm 5.4. #[serde(rename = "rocm5.4")] #[cfg_attr(feature = "clap", clap(name = "rocm5.4"))] Rocm54, /// Use the PyTorch index for ROCm 5.3. #[serde(rename = "rocm5.3")] #[cfg_attr(feature = "clap", clap(name = "rocm5.3"))] Rocm53, /// Use the PyTorch index for ROCm 5.2. #[serde(rename = "rocm5.2")] #[cfg_attr(feature = "clap", clap(name = "rocm5.2"))] Rocm52, /// Use the PyTorch index for ROCm 5.1.1. #[serde(rename = "rocm5.1.1")] #[cfg_attr(feature = "clap", clap(name = "rocm5.1.1"))] Rocm511, /// Use the PyTorch index for ROCm 4.2. #[serde(rename = "rocm4.2")] #[cfg_attr(feature = "clap", clap(name = "rocm4.2"))] Rocm42, /// Use the PyTorch index for ROCm 4.1. #[serde(rename = "rocm4.1")] #[cfg_attr(feature = "clap", clap(name = "rocm4.1"))] Rocm41, /// Use the PyTorch index for ROCm 4.0.1. #[serde(rename = "rocm4.0.1")] #[cfg_attr(feature = "clap", clap(name = "rocm4.0.1"))] Rocm401, /// Use the PyTorch index for Intel XPU. Xpu, } #[derive(Debug, Default, Copy, Clone, Eq, PartialEq)] pub enum TorchSource { /// Download PyTorch builds from the official PyTorch index. #[default] PyTorch, /// Download PyTorch builds from the pyx index. Pyx, } /// The strategy to use when determining the appropriate PyTorch index. #[derive(Debug, Clone, Eq, PartialEq)] pub enum TorchStrategy { /// Select the appropriate PyTorch index based on the operating system and CUDA driver version (e.g., `550.144.03`). Cuda { os: Os, driver_version: Version, source: TorchSource, }, /// Select the appropriate PyTorch index based on the operating system and AMD GPU architecture (e.g., `gfx1100`). Amd { os: Os, gpu_architecture: AmdGpuArchitecture, source: TorchSource, }, /// Select the appropriate PyTorch index based on the operating system and Intel GPU presence. Xpu { os: Os, source: TorchSource }, /// Use the specified PyTorch index. Backend { backend: TorchBackend, source: TorchSource, }, } impl TorchStrategy { /// Determine the [`TorchStrategy`] from the given [`TorchMode`], [`Os`], and [`Accelerator`]. pub fn from_mode( mode: TorchMode, source: TorchSource, os: &Os, ) -> Result<Self, AcceleratorError> { let backend = match mode { TorchMode::Auto => match Accelerator::detect()? { Some(Accelerator::Cuda { driver_version }) => { return Ok(Self::Cuda { os: os.clone(), driver_version: driver_version.clone(), source, }); } Some(Accelerator::Amd { gpu_architecture }) => { return Ok(Self::Amd { os: os.clone(), gpu_architecture, source, }); } Some(Accelerator::Xpu) => { return Ok(Self::Xpu { os: os.clone(), source, }); } None => TorchBackend::Cpu, }, TorchMode::Cpu => TorchBackend::Cpu, TorchMode::Cu130 => TorchBackend::Cu130, TorchMode::Cu129 => TorchBackend::Cu129, TorchMode::Cu128 => TorchBackend::Cu128, TorchMode::Cu126 => TorchBackend::Cu126, TorchMode::Cu125 => TorchBackend::Cu125, TorchMode::Cu124 => TorchBackend::Cu124, TorchMode::Cu123 => TorchBackend::Cu123, TorchMode::Cu122 => TorchBackend::Cu122, TorchMode::Cu121 => TorchBackend::Cu121, TorchMode::Cu120 => TorchBackend::Cu120, TorchMode::Cu118 => TorchBackend::Cu118, TorchMode::Cu117 => TorchBackend::Cu117, TorchMode::Cu116 => TorchBackend::Cu116, TorchMode::Cu115 => TorchBackend::Cu115, TorchMode::Cu114 => TorchBackend::Cu114, TorchMode::Cu113 => TorchBackend::Cu113, TorchMode::Cu112 => TorchBackend::Cu112, TorchMode::Cu111 => TorchBackend::Cu111, TorchMode::Cu110 => TorchBackend::Cu110, TorchMode::Cu102 => TorchBackend::Cu102, TorchMode::Cu101 => TorchBackend::Cu101, TorchMode::Cu100 => TorchBackend::Cu100, TorchMode::Cu92 => TorchBackend::Cu92, TorchMode::Cu91 => TorchBackend::Cu91, TorchMode::Cu90 => TorchBackend::Cu90, TorchMode::Cu80 => TorchBackend::Cu80, TorchMode::Rocm64 => TorchBackend::Rocm64, TorchMode::Rocm63 => TorchBackend::Rocm63, TorchMode::Rocm624 => TorchBackend::Rocm624, TorchMode::Rocm62 => TorchBackend::Rocm62, TorchMode::Rocm61 => TorchBackend::Rocm61, TorchMode::Rocm60 => TorchBackend::Rocm60, TorchMode::Rocm57 => TorchBackend::Rocm57, TorchMode::Rocm56 => TorchBackend::Rocm56, TorchMode::Rocm55 => TorchBackend::Rocm55, TorchMode::Rocm542 => TorchBackend::Rocm542, TorchMode::Rocm54 => TorchBackend::Rocm54, TorchMode::Rocm53 => TorchBackend::Rocm53, TorchMode::Rocm52 => TorchBackend::Rocm52, TorchMode::Rocm511 => TorchBackend::Rocm511, TorchMode::Rocm42 => TorchBackend::Rocm42, TorchMode::Rocm41 => TorchBackend::Rocm41, TorchMode::Rocm401 => TorchBackend::Rocm401, TorchMode::Xpu => TorchBackend::Xpu, }; Ok(Self::Backend { backend, source }) } /// Returns `true` if the [`TorchStrategy`] applies to the given [`PackageName`]. pub fn applies_to(&self, package_name: &PackageName) -> bool { let source = match self { Self::Cuda { source, .. } => *source, Self::Amd { source, .. } => *source, Self::Xpu { source, .. } => *source, Self::Backend { source, .. } => *source, }; match source { TorchSource::PyTorch => { matches!( package_name.as_str(), "pytorch-triton" | "pytorch-triton-rocm" | "pytorch-triton-xpu" | "torch" | "torch-tensorrt" | "torchao" | "torcharrow" | "torchaudio" | "torchcsprng" | "torchdata" | "torchdistx" | "torchserve" | "torchtext" | "torchvision" | "triton" ) } TorchSource::Pyx => { matches!( package_name.as_str(), "deepspeed" | "flash-attn" | "flash-attn-3" | "megablocks" | "natten" | "pyg-lib" | "pytorch-triton" | "pytorch-triton-rocm" | "pytorch-triton-xpu" | "torch" | "torch-cluster" | "torch-scatter" | "torch-sparse" | "torch-spline-conv" | "torch-tensorrt" | "torchao" | "torcharrow" | "torchaudio" | "torchcsprng" | "torchdata" | "torchdistx" | "torchserve" | "torchtext" | "torchvision" | "triton" | "vllm" ) } } } /// Returns `true` if the given [`PackageName`] has a system dependency (e.g., CUDA or ROCm). /// /// For example, `triton` is hosted on the PyTorch indexes, but does not have a system /// dependency on the associated CUDA version (i.e., the `triton` on the `cu128` index doesn't /// depend on CUDA 12.8). pub fn has_system_dependency(&self, package_name: &PackageName) -> bool { matches!( package_name.as_str(), "deepspeed" | "flash-attn" | "flash-attn-3" | "megablocks" | "natten" | "torch" | "torch-tensorrt" | "torchao" | "torcharrow" | "torchaudio" | "torchcsprng" | "torchdata" | "torchdistx" | "torchtext" | "torchvision" | "vllm" ) } /// Return the appropriate index URLs for the given [`TorchStrategy`]. pub fn index_urls(&self) -> impl Iterator<Item = &IndexUrl> { match self { Self::Cuda { os, driver_version, source, } => { // If this is a GPU-enabled package, and CUDA drivers are installed, use PyTorch's CUDA // indexes. // // See: https://github.com/pmeier/light-the-torch/blob/33397cbe45d07b51ad8ee76b004571a4c236e37f/light_the_torch/_patch.py#L36-L49 match os { Os::Manylinux { .. } | Os::Musllinux { .. } => { Either::Left(Either::Left(Either::Left( LINUX_CUDA_DRIVERS .iter() .filter_map(move |(backend, version)| { if driver_version >= version { Some(backend.index_url(*source)) } else { None } }) .chain(std::iter::once(TorchBackend::Cpu.index_url(*source))), ))) } Os::Windows => Either::Left(Either::Left(Either::Right( WINDOWS_CUDA_VERSIONS .iter() .filter_map(move |(backend, version)| { if driver_version >= version { Some(backend.index_url(*source)) } else { None } }) .chain(std::iter::once(TorchBackend::Cpu.index_url(*source))), ))), Os::Macos { .. } | Os::FreeBsd { .. } | Os::NetBsd { .. } | Os::OpenBsd { .. } | Os::Dragonfly { .. } | Os::Illumos { .. } | Os::Haiku { .. } | Os::Android { .. } | Os::Pyodide { .. } | Os::Ios { .. } => Either::Right(Either::Left(std::iter::once( TorchBackend::Cpu.index_url(*source), ))), } } Self::Amd { os, gpu_architecture, source, } => match os { Os::Manylinux { .. } | Os::Musllinux { .. } => Either::Left(Either::Right( LINUX_AMD_GPU_DRIVERS .iter() .filter_map(move |(backend, architecture)| { if gpu_architecture == architecture { Some(backend.index_url(*source)) } else { None } }) .chain(std::iter::once(TorchBackend::Cpu.index_url(*source))), )), Os::Windows | Os::Macos { .. } | Os::FreeBsd { .. } | Os::NetBsd { .. } | Os::OpenBsd { .. } | Os::Dragonfly { .. } | Os::Illumos { .. } | Os::Haiku { .. } | Os::Android { .. } | Os::Pyodide { .. } | Os::Ios { .. } => Either::Right(Either::Left(std::iter::once( TorchBackend::Cpu.index_url(*source), ))), }, Self::Xpu { os, source } => match os { Os::Manylinux { .. } | Os::Windows => Either::Right(Either::Right(Either::Left( std::iter::once(TorchBackend::Xpu.index_url(*source)), ))), Os::Musllinux { .. } | Os::Macos { .. } | Os::FreeBsd { .. } | Os::NetBsd { .. } | Os::OpenBsd { .. } | Os::Dragonfly { .. } | Os::Illumos { .. } | Os::Haiku { .. } | Os::Android { .. } | Os::Pyodide { .. } | Os::Ios { .. } => Either::Right(Either::Left(std::iter::once( TorchBackend::Cpu.index_url(*source), ))), }, Self::Backend { backend, source } => Either::Right(Either::Right(Either::Right( std::iter::once(backend.index_url(*source)), ))), } } } /// The available backends for PyTorch. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum TorchBackend { Cpu, Cu130, Cu129, Cu128, Cu126, Cu125, Cu124, Cu123, Cu122, Cu121, Cu120, Cu118, Cu117, Cu116, Cu115, Cu114, Cu113, Cu112, Cu111, Cu110, Cu102, Cu101, Cu100, Cu92, Cu91, Cu90, Cu80, Rocm64, Rocm63, Rocm624, Rocm62, Rocm61, Rocm60, Rocm57, Rocm56, Rocm55, Rocm542, Rocm54, Rocm53, Rocm52, Rocm511, Rocm42, Rocm41, Rocm401, Xpu, } impl TorchBackend { /// Return the appropriate index URL for the given [`TorchBackend`]. fn index_url(self, source: TorchSource) -> &'static IndexUrl { match self { Self::Cpu => match source { TorchSource::PyTorch => &PYTORCH_CPU_INDEX_URL, TorchSource::Pyx => &PYX_CPU_INDEX_URL, }, Self::Cu130 => match source { TorchSource::PyTorch => &PYTORCH_CU130_INDEX_URL, TorchSource::Pyx => &PYX_CU130_INDEX_URL, }, Self::Cu129 => match source { TorchSource::PyTorch => &PYTORCH_CU129_INDEX_URL, TorchSource::Pyx => &PYX_CU129_INDEX_URL, }, Self::Cu128 => match source { TorchSource::PyTorch => &PYTORCH_CU128_INDEX_URL, TorchSource::Pyx => &PYX_CU128_INDEX_URL, }, Self::Cu126 => match source { TorchSource::PyTorch => &PYTORCH_CU126_INDEX_URL, TorchSource::Pyx => &PYX_CU126_INDEX_URL, }, Self::Cu125 => match source { TorchSource::PyTorch => &PYTORCH_CU125_INDEX_URL, TorchSource::Pyx => &PYX_CU125_INDEX_URL, }, Self::Cu124 => match source { TorchSource::PyTorch => &PYTORCH_CU124_INDEX_URL, TorchSource::Pyx => &PYX_CU124_INDEX_URL, }, Self::Cu123 => match source { TorchSource::PyTorch => &PYTORCH_CU123_INDEX_URL, TorchSource::Pyx => &PYX_CU123_INDEX_URL, }, Self::Cu122 => match source { TorchSource::PyTorch => &PYTORCH_CU122_INDEX_URL, TorchSource::Pyx => &PYX_CU122_INDEX_URL, }, Self::Cu121 => match source { TorchSource::PyTorch => &PYTORCH_CU121_INDEX_URL, TorchSource::Pyx => &PYX_CU121_INDEX_URL, }, Self::Cu120 => match source { TorchSource::PyTorch => &PYTORCH_CU120_INDEX_URL, TorchSource::Pyx => &PYX_CU120_INDEX_URL, }, Self::Cu118 => match source { TorchSource::PyTorch => &PYTORCH_CU118_INDEX_URL, TorchSource::Pyx => &PYX_CU118_INDEX_URL, }, Self::Cu117 => match source { TorchSource::PyTorch => &PYTORCH_CU117_INDEX_URL, TorchSource::Pyx => &PYX_CU117_INDEX_URL, }, Self::Cu116 => match source { TorchSource::PyTorch => &PYTORCH_CU116_INDEX_URL, TorchSource::Pyx => &PYX_CU116_INDEX_URL, }, Self::Cu115 => match source { TorchSource::PyTorch => &PYTORCH_CU115_INDEX_URL, TorchSource::Pyx => &PYX_CU115_INDEX_URL, }, Self::Cu114 => match source { TorchSource::PyTorch => &PYTORCH_CU114_INDEX_URL, TorchSource::Pyx => &PYX_CU114_INDEX_URL, }, Self::Cu113 => match source { TorchSource::PyTorch => &PYTORCH_CU113_INDEX_URL, TorchSource::Pyx => &PYX_CU113_INDEX_URL, }, Self::Cu112 => match source { TorchSource::PyTorch => &PYTORCH_CU112_INDEX_URL, TorchSource::Pyx => &PYX_CU112_INDEX_URL, }, Self::Cu111 => match source { TorchSource::PyTorch => &PYTORCH_CU111_INDEX_URL, TorchSource::Pyx => &PYX_CU111_INDEX_URL, }, Self::Cu110 => match source { TorchSource::PyTorch => &PYTORCH_CU110_INDEX_URL, TorchSource::Pyx => &PYX_CU110_INDEX_URL, }, Self::Cu102 => match source { TorchSource::PyTorch => &PYTORCH_CU102_INDEX_URL, TorchSource::Pyx => &PYX_CU102_INDEX_URL, }, Self::Cu101 => match source { TorchSource::PyTorch => &PYTORCH_CU101_INDEX_URL, TorchSource::Pyx => &PYX_CU101_INDEX_URL, }, Self::Cu100 => match source { TorchSource::PyTorch => &PYTORCH_CU100_INDEX_URL, TorchSource::Pyx => &PYX_CU100_INDEX_URL, }, Self::Cu92 => match source { TorchSource::PyTorch => &PYTORCH_CU92_INDEX_URL, TorchSource::Pyx => &PYX_CU92_INDEX_URL, }, Self::Cu91 => match source { TorchSource::PyTorch => &PYTORCH_CU91_INDEX_URL, TorchSource::Pyx => &PYX_CU91_INDEX_URL, }, Self::Cu90 => match source { TorchSource::PyTorch => &PYTORCH_CU90_INDEX_URL, TorchSource::Pyx => &PYX_CU90_INDEX_URL, }, Self::Cu80 => match source { TorchSource::PyTorch => &PYTORCH_CU80_INDEX_URL, TorchSource::Pyx => &PYX_CU80_INDEX_URL, }, Self::Rocm64 => match source { TorchSource::PyTorch => &PYTORCH_ROCM64_INDEX_URL, TorchSource::Pyx => &PYX_ROCM64_INDEX_URL, }, Self::Rocm63 => match source { TorchSource::PyTorch => &PYTORCH_ROCM63_INDEX_URL, TorchSource::Pyx => &PYX_ROCM63_INDEX_URL, }, Self::Rocm624 => match source { TorchSource::PyTorch => &PYTORCH_ROCM624_INDEX_URL, TorchSource::Pyx => &PYX_ROCM624_INDEX_URL, }, Self::Rocm62 => match source { TorchSource::PyTorch => &PYTORCH_ROCM62_INDEX_URL, TorchSource::Pyx => &PYX_ROCM62_INDEX_URL, }, Self::Rocm61 => match source { TorchSource::PyTorch => &PYTORCH_ROCM61_INDEX_URL, TorchSource::Pyx => &PYX_ROCM61_INDEX_URL, }, Self::Rocm60 => match source { TorchSource::PyTorch => &PYTORCH_ROCM60_INDEX_URL, TorchSource::Pyx => &PYX_ROCM60_INDEX_URL, }, Self::Rocm57 => match source { TorchSource::PyTorch => &PYTORCH_ROCM57_INDEX_URL, TorchSource::Pyx => &PYX_ROCM57_INDEX_URL, }, Self::Rocm56 => match source { TorchSource::PyTorch => &PYTORCH_ROCM56_INDEX_URL, TorchSource::Pyx => &PYX_ROCM56_INDEX_URL, }, Self::Rocm55 => match source { TorchSource::PyTorch => &PYTORCH_ROCM55_INDEX_URL, TorchSource::Pyx => &PYX_ROCM55_INDEX_URL, }, Self::Rocm542 => match source { TorchSource::PyTorch => &PYTORCH_ROCM542_INDEX_URL, TorchSource::Pyx => &PYX_ROCM542_INDEX_URL, }, Self::Rocm54 => match source { TorchSource::PyTorch => &PYTORCH_ROCM54_INDEX_URL, TorchSource::Pyx => &PYX_ROCM54_INDEX_URL, }, Self::Rocm53 => match source { TorchSource::PyTorch => &PYTORCH_ROCM53_INDEX_URL, TorchSource::Pyx => &PYX_ROCM53_INDEX_URL, }, Self::Rocm52 => match source { TorchSource::PyTorch => &PYTORCH_ROCM52_INDEX_URL, TorchSource::Pyx => &PYX_ROCM52_INDEX_URL, }, Self::Rocm511 => match source { TorchSource::PyTorch => &PYTORCH_ROCM511_INDEX_URL, TorchSource::Pyx => &PYX_ROCM511_INDEX_URL, }, Self::Rocm42 => match source { TorchSource::PyTorch => &PYTORCH_ROCM42_INDEX_URL, TorchSource::Pyx => &PYX_ROCM42_INDEX_URL, }, Self::Rocm41 => match source { TorchSource::PyTorch => &PYTORCH_ROCM41_INDEX_URL, TorchSource::Pyx => &PYX_ROCM41_INDEX_URL, }, Self::Rocm401 => match source { TorchSource::PyTorch => &PYTORCH_ROCM401_INDEX_URL, TorchSource::Pyx => &PYX_ROCM401_INDEX_URL, }, Self::Xpu => match source { TorchSource::PyTorch => &PYTORCH_XPU_INDEX_URL, TorchSource::Pyx => &PYX_XPU_INDEX_URL, }, } } /// Extract a [`TorchBackend`] from an index URL. pub fn from_index(index: &Url) -> Option<Self> { let backend_identifier = if index.host_str() == Some("download.pytorch.org") { // E.g., `https://download.pytorch.org/whl/cu124` let mut path_segments = index.path_segments()?; if path_segments.next() != Some("whl") { return None; } path_segments.next()? // TODO(zanieb): We should consolidate this with `is_known_url` somehow } else if index.host_str() == PYX_API_BASE_URL.strip_prefix("https://") { // E.g., `https://api.pyx.dev/simple/astral-sh/cu124` let mut path_segments = index.path_segments()?; if path_segments.next() != Some("simple") { return None; } if path_segments.next() != Some("astral-sh") { return None; } path_segments.next()? } else { return None; }; Self::from_str(backend_identifier).ok() } /// Returns the CUDA [`Version`] for the given [`TorchBackend`]. pub fn cuda_version(&self) -> Option<Version> { match self { Self::Cpu => None, Self::Cu130 => Some(Version::new([13, 0])), Self::Cu129 => Some(Version::new([12, 9])), Self::Cu128 => Some(Version::new([12, 8])), Self::Cu126 => Some(Version::new([12, 6])), Self::Cu125 => Some(Version::new([12, 5])), Self::Cu124 => Some(Version::new([12, 4])), Self::Cu123 => Some(Version::new([12, 3])), Self::Cu122 => Some(Version::new([12, 2])), Self::Cu121 => Some(Version::new([12, 1])), Self::Cu120 => Some(Version::new([12, 0])), Self::Cu118 => Some(Version::new([11, 8])), Self::Cu117 => Some(Version::new([11, 7])), Self::Cu116 => Some(Version::new([11, 6])), Self::Cu115 => Some(Version::new([11, 5])), Self::Cu114 => Some(Version::new([11, 4])), Self::Cu113 => Some(Version::new([11, 3])), Self::Cu112 => Some(Version::new([11, 2])), Self::Cu111 => Some(Version::new([11, 1])), Self::Cu110 => Some(Version::new([11, 0])), Self::Cu102 => Some(Version::new([10, 2])), Self::Cu101 => Some(Version::new([10, 1])), Self::Cu100 => Some(Version::new([10, 0])), Self::Cu92 => Some(Version::new([9, 2])), Self::Cu91 => Some(Version::new([9, 1])), Self::Cu90 => Some(Version::new([9, 0])), Self::Cu80 => Some(Version::new([8, 0])), Self::Rocm64 => None, Self::Rocm63 => None, Self::Rocm624 => None, Self::Rocm62 => None, Self::Rocm61 => None, Self::Rocm60 => None, Self::Rocm57 => None, Self::Rocm56 => None, Self::Rocm55 => None, Self::Rocm542 => None, Self::Rocm54 => None, Self::Rocm53 => None, Self::Rocm52 => None, Self::Rocm511 => None, Self::Rocm42 => None, Self::Rocm41 => None, Self::Rocm401 => None, Self::Xpu => None, } } /// Returns the ROCM [`Version`] for the given [`TorchBackend`]. pub fn rocm_version(&self) -> Option<Version> { match self { Self::Cpu => None, Self::Cu130 => None, Self::Cu129 => None, Self::Cu128 => None, Self::Cu126 => None, Self::Cu125 => None, Self::Cu124 => None, Self::Cu123 => None, Self::Cu122 => None, Self::Cu121 => None, Self::Cu120 => None, Self::Cu118 => None, Self::Cu117 => None, Self::Cu116 => None, Self::Cu115 => None, Self::Cu114 => None, Self::Cu113 => None, Self::Cu112 => None, Self::Cu111 => None, Self::Cu110 => None, Self::Cu102 => None, Self::Cu101 => None, Self::Cu100 => None,
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-torch/src/accelerator.rs
crates/uv-torch/src/accelerator.rs
use std::path::Path; use std::str::FromStr; use tracing::debug; use uv_pep440::Version; use uv_static::EnvVars; #[cfg(windows)] use serde::Deserialize; #[cfg(windows)] use wmi::{COMLibrary, WMIConnection}; #[derive(Debug, thiserror::Error)] pub enum AcceleratorError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Version(#[from] uv_pep440::VersionParseError), #[error(transparent)] Utf8(#[from] std::string::FromUtf8Error), #[error(transparent)] ParseInt(#[from] std::num::ParseIntError), #[error("Unknown AMD GPU architecture: {0}")] UnknownAmdGpuArchitecture(String), } #[derive(Debug, Clone, Eq, PartialEq)] pub enum Accelerator { /// The CUDA driver version (e.g., `550.144.03`). /// /// This is in contrast to the CUDA toolkit version (e.g., `12.8.0`). Cuda { driver_version: Version }, /// The AMD GPU architecture (e.g., `gfx906`). /// /// This is in contrast to the user-space ROCm version (e.g., `6.4.0-47`) or the kernel-mode /// driver version (e.g., `6.12.12`). Amd { gpu_architecture: AmdGpuArchitecture, }, /// The Intel GPU (XPU). /// /// Currently, Intel GPUs do not depend on a driver or toolkit version at this level. Xpu, } impl std::fmt::Display for Accelerator { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { Self::Cuda { driver_version } => write!(f, "CUDA {driver_version}"), Self::Amd { gpu_architecture } => write!(f, "AMD {gpu_architecture}"), Self::Xpu => write!(f, "Intel GPU (XPU)"), } } } impl Accelerator { /// Detect the GPU driver and/or architecture version from the system. /// /// Query, in order: /// 1. The `UV_CUDA_DRIVER_VERSION` environment variable. /// 2. The `UV_AMD_GPU_ARCHITECTURE` environment variable. /// 3. `/sys/module/nvidia/version`, which contains the driver version (e.g., `550.144.03`). /// 4. `/proc/driver/nvidia/version`, which contains the driver version among other information. /// 5. `nvidia-smi --query-gpu=driver_version --format=csv,noheader`. /// 6. `rocm_agent_enumerator`, which lists the AMD GPU architectures. /// 7. `/sys/bus/pci/devices`, filtering for the Intel GPU via PCI. /// 8. Windows Managmeent Instrumentation (WMI), filtering for the Intel GPU via PCI. pub fn detect() -> Result<Option<Self>, AcceleratorError> { // Constants used for PCI device detection. const PCI_BASE_CLASS_MASK: u32 = 0x00ff_0000; const PCI_BASE_CLASS_DISPLAY: u32 = 0x0003_0000; const PCI_VENDOR_ID_INTEL: u32 = 0x8086; // Read from `UV_CUDA_DRIVER_VERSION`. if let Ok(driver_version) = std::env::var(EnvVars::UV_CUDA_DRIVER_VERSION) { let driver_version = Version::from_str(&driver_version)?; debug!("Detected CUDA driver version from `UV_CUDA_DRIVER_VERSION`: {driver_version}"); return Ok(Some(Self::Cuda { driver_version })); } // Read from `UV_AMD_GPU_ARCHITECTURE`. if let Ok(gpu_architecture) = std::env::var(EnvVars::UV_AMD_GPU_ARCHITECTURE) { let gpu_architecture = AmdGpuArchitecture::from_str(&gpu_architecture)?; debug!( "Detected AMD GPU architecture from `UV_AMD_GPU_ARCHITECTURE`: {gpu_architecture}" ); return Ok(Some(Self::Amd { gpu_architecture })); } // Read from `/sys/module/nvidia/version`. match fs_err::read_to_string("/sys/module/nvidia/version") { Ok(content) => { return match parse_sys_module_nvidia_version(&content) { Ok(driver_version) => { debug!( "Detected CUDA driver version from `/sys/module/nvidia/version`: {driver_version}" ); Ok(Some(Self::Cuda { driver_version })) } Err(e) => Err(e), }; } Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e.into()), } // Read from `/proc/driver/nvidia/version` match fs_err::read_to_string("/proc/driver/nvidia/version") { Ok(content) => match parse_proc_driver_nvidia_version(&content) { Ok(Some(driver_version)) => { debug!( "Detected CUDA driver version from `/proc/driver/nvidia/version`: {driver_version}" ); return Ok(Some(Self::Cuda { driver_version })); } Ok(None) => { debug!( "Failed to parse CUDA driver version from `/proc/driver/nvidia/version`" ); } Err(e) => return Err(e), }, Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e.into()), } // Query `nvidia-smi`. if let Ok(output) = std::process::Command::new("nvidia-smi") .arg("--query-gpu=driver_version") .arg("--format=csv,noheader") .output() { if output.status.success() { let stdout = String::from_utf8(output.stdout)?; if let Some(first_line) = stdout.lines().next() { let driver_version = Version::from_str(first_line.trim())?; debug!("Detected CUDA driver version from `nvidia-smi`: {driver_version}"); return Ok(Some(Self::Cuda { driver_version })); } } debug!( "Failed to query CUDA driver version with `nvidia-smi` with status `{}`: {}", output.status, String::from_utf8_lossy(&output.stderr) ); } // Query `rocm_agent_enumerator` to detect the AMD GPU architecture. // // See: https://rocm.docs.amd.com/projects/rocminfo/en/latest/how-to/use-rocm-agent-enumerator.html if let Ok(output) = std::process::Command::new("rocm_agent_enumerator").output() { if output.status.success() { let stdout = String::from_utf8(output.stdout)?; if let Some(gpu_architecture) = stdout .lines() .map(str::trim) .filter_map(|line| AmdGpuArchitecture::from_str(line).ok()) .min() { debug!( "Detected AMD GPU architecture from `rocm_agent_enumerator`: {gpu_architecture}" ); return Ok(Some(Self::Amd { gpu_architecture })); } } else { debug!( "Failed to query AMD GPU architecture with `rocm_agent_enumerator` with status `{}`: {}", output.status, String::from_utf8_lossy(&output.stderr) ); } } // Read from `/sys/bus/pci/devices` to filter for Intel GPU via PCI. match fs_err::read_dir("/sys/bus/pci/devices") { Ok(entries) => { for entry in entries.flatten() { match parse_pci_device_ids(&entry.path()) { Ok((class, vendor)) => { if (class & PCI_BASE_CLASS_MASK) == PCI_BASE_CLASS_DISPLAY && vendor == PCI_VENDOR_ID_INTEL { debug!("Detected Intel GPU from PCI: vendor=0x{:04x}", vendor); return Ok(Some(Self::Xpu)); } } Err(e) => { debug!("Failed to parse PCI device IDs: {e}"); } } } } Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(e.into()), } // Detect Intel GPU via WMI on Windows #[cfg(windows)] { #[derive(Deserialize, Debug)] #[serde(rename = "Win32_VideoController")] #[serde(rename_all = "PascalCase")] struct VideoController { #[serde(rename = "PNPDeviceID")] pnp_device_id: Option<String>, name: Option<String>, } match COMLibrary::new() { Ok(com_library) => match WMIConnection::new(com_library) { Ok(wmi_connection) => match wmi_connection.query::<VideoController>() { Ok(gpu_controllers) => { for gpu_controller in gpu_controllers { if let Some(pnp_device_id) = &gpu_controller.pnp_device_id { if pnp_device_id .contains(&format!("VEN_{PCI_VENDOR_ID_INTEL:04X}")) { debug!( "Detected Intel GPU from WMI: PNPDeviceID={}, Name={:?}", pnp_device_id, gpu_controller.name ); return Ok(Some(Self::Xpu)); } } } } Err(e) => { debug!("Failed to query WMI for video controllers: {e}"); } }, Err(e) => { debug!("Failed to create WMI connection: {e}"); } }, Err(e) => { debug!("Failed to initialize COM library: {e}"); } } } debug!("Failed to detect GPU driver version"); Ok(None) } } /// Parse the CUDA driver version from the content of `/sys/module/nvidia/version`. fn parse_sys_module_nvidia_version(content: &str) -> Result<Version, AcceleratorError> { // Parse, e.g.: // ```text // 550.144.03 // ``` let driver_version = Version::from_str(content.trim())?; Ok(driver_version) } /// Parse the CUDA driver version from the content of `/proc/driver/nvidia/version`. fn parse_proc_driver_nvidia_version(content: &str) -> Result<Option<Version>, AcceleratorError> { // Parse, e.g.: // ```text // NVRM version: NVIDIA UNIX Open Kernel Module for x86_64 550.144.03 Release Build (dvs-builder@U16-I3-D08-1-2) Mon Dec 30 17:26:13 UTC 2024 // GCC version: gcc version 12.3.0 (Ubuntu 12.3.0-1ubuntu1~22.04) // ``` let Some(version) = content.split(" ").nth(1) else { return Ok(None); }; let driver_version = Version::from_str(version.trim())?; Ok(Some(driver_version)) } /// Reads and parses the PCI class and vendor ID from a given device path under `/sys/bus/pci/devices`. fn parse_pci_device_ids(device_path: &Path) -> Result<(u32, u32), AcceleratorError> { // Parse, e.g.: // ```text // - `class`: a hexadecimal string such as `0x030000` // - `vendor`: a hexadecimal string such as `0x8086` // ``` let class_content = fs_err::read_to_string(device_path.join("class"))?; let pci_class = u32::from_str_radix(class_content.trim().trim_start_matches("0x"), 16)?; let vendor_content = fs_err::read_to_string(device_path.join("vendor"))?; let pci_vendor = u32::from_str_radix(vendor_content.trim().trim_start_matches("0x"), 16)?; Ok((pci_class, pci_vendor)) } /// A GPU architecture for AMD GPUs. /// /// See: <https://rocm.docs.amd.com/projects/install-on-linux/en/latest/reference/system-requirements.html> #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] pub enum AmdGpuArchitecture { Gfx900, Gfx906, Gfx908, Gfx90a, Gfx942, Gfx1030, Gfx1100, Gfx1101, Gfx1102, Gfx1200, Gfx1201, } impl FromStr for AmdGpuArchitecture { type Err = AcceleratorError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "gfx900" => Ok(Self::Gfx900), "gfx906" => Ok(Self::Gfx906), "gfx908" => Ok(Self::Gfx908), "gfx90a" => Ok(Self::Gfx90a), "gfx942" => Ok(Self::Gfx942), "gfx1030" => Ok(Self::Gfx1030), "gfx1100" => Ok(Self::Gfx1100), "gfx1101" => Ok(Self::Gfx1101), "gfx1102" => Ok(Self::Gfx1102), "gfx1200" => Ok(Self::Gfx1200), "gfx1201" => Ok(Self::Gfx1201), _ => Err(AcceleratorError::UnknownAmdGpuArchitecture(s.to_string())), } } } impl std::fmt::Display for AmdGpuArchitecture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Gfx900 => write!(f, "gfx900"), Self::Gfx906 => write!(f, "gfx906"), Self::Gfx908 => write!(f, "gfx908"), Self::Gfx90a => write!(f, "gfx90a"), Self::Gfx942 => write!(f, "gfx942"), Self::Gfx1030 => write!(f, "gfx1030"), Self::Gfx1100 => write!(f, "gfx1100"), Self::Gfx1101 => write!(f, "gfx1101"), Self::Gfx1102 => write!(f, "gfx1102"), Self::Gfx1200 => write!(f, "gfx1200"), Self::Gfx1201 => write!(f, "gfx1201"), } } } #[cfg(test)] mod tests { use super::*; #[test] fn proc_driver_nvidia_version() { let content = "NVRM version: NVIDIA UNIX Open Kernel Module for x86_64 550.144.03 Release Build (dvs-builder@U16-I3-D08-1-2) Mon Dec 30 17:26:13 UTC 2024\nGCC version: gcc version 12.3.0 (Ubuntu 12.3.0-1ubuntu1~22.04)"; let result = parse_proc_driver_nvidia_version(content).unwrap(); assert_eq!(result, Some(Version::from_str("550.144.03").unwrap())); let content = "NVRM version: NVIDIA UNIX x86_64 Kernel Module 375.74 Wed Jun 14 01:39:39 PDT 2017\nGCC version: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)"; let result = parse_proc_driver_nvidia_version(content).unwrap(); assert_eq!(result, Some(Version::from_str("375.74").unwrap())); } #[test] fn nvidia_smi_multi_gpu() { // Test that we can parse nvidia-smi output with multiple GPUs (multiple lines) let single_gpu = "572.60\n"; if let Some(first_line) = single_gpu.lines().next() { let version = Version::from_str(first_line.trim()).unwrap(); assert_eq!(version, Version::from_str("572.60").unwrap()); } let multi_gpu = "572.60\n572.60\n"; if let Some(first_line) = multi_gpu.lines().next() { let version = Version::from_str(first_line.trim()).unwrap(); assert_eq!(version, Version::from_str("572.60").unwrap()); } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-small-str/src/lib.rs
crates/uv-small-str/src/lib.rs
use std::borrow::Cow; use std::cmp::PartialEq; use std::ops::Deref; /// An optimized type for immutable identifiers. Represented as an [`arcstr::ArcStr`] internally. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SmallString(arcstr::ArcStr); impl From<arcstr::ArcStr> for SmallString { #[inline] fn from(s: arcstr::ArcStr) -> Self { Self(s) } } impl From<&str> for SmallString { #[inline] fn from(s: &str) -> Self { Self(s.into()) } } impl From<String> for SmallString { #[inline] fn from(s: String) -> Self { Self(s.into()) } } impl From<Cow<'_, str>> for SmallString { fn from(s: Cow<'_, str>) -> Self { match s { Cow::Borrowed(s) => Self::from(s), Cow::Owned(s) => Self::from(s), } } } impl AsRef<str> for SmallString { #[inline] fn as_ref(&self) -> &str { &self.0 } } impl core::borrow::Borrow<str> for SmallString { #[inline] fn borrow(&self) -> &str { self } } impl Deref for SmallString { type Target = str; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl core::fmt::Debug for SmallString { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::Debug::fmt(&self.0, f) } } impl core::fmt::Display for SmallString { #[inline] fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { core::fmt::Display::fmt(&self.0, f) } } /// A [`serde::Serialize`] implementation for [`SmallString`]. impl serde::Serialize for SmallString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de> serde::Deserialize<'de> for SmallString { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl serde::de::Visitor<'_> for Visitor { type Value = SmallString; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { Ok(v.into()) } } deserializer.deserialize_str(Visitor) } } /// An [`rkyv`] implementation for [`SmallString`]. impl rkyv::Archive for SmallString { type Archived = rkyv::string::ArchivedString; type Resolver = rkyv::string::StringResolver; #[inline] fn resolve(&self, resolver: Self::Resolver, out: rkyv::Place<Self::Archived>) { rkyv::string::ArchivedString::resolve_from_str(&self.0, resolver, out); } } impl<S> rkyv::Serialize<S> for SmallString where S: rkyv::rancor::Fallible + rkyv::ser::Allocator + rkyv::ser::Writer + ?Sized, S::Error: rkyv::rancor::Source, { fn serialize(&self, serializer: &mut S) -> Result<Self::Resolver, S::Error> { rkyv::string::ArchivedString::serialize_from_str(&self.0, serializer) } } impl<D: rkyv::rancor::Fallible + ?Sized> rkyv::Deserialize<SmallString, D> for rkyv::string::ArchivedString { fn deserialize(&self, _deserializer: &mut D) -> Result<SmallString, D::Error> { Ok(SmallString::from(self.as_str())) } } impl PartialEq<SmallString> for rkyv::string::ArchivedString { fn eq(&self, other: &SmallString) -> bool { **other == **self } } impl PartialOrd<SmallString> for rkyv::string::ArchivedString { fn partial_cmp(&self, other: &SmallString) -> Option<::core::cmp::Ordering> { Some(self.as_str().cmp(other)) } } /// An [`schemars::JsonSchema`] implementation for [`SmallString`]. #[cfg(feature = "schemars")] impl schemars::JsonSchema for SmallString { fn inline_schema() -> bool { true } fn schema_name() -> Cow<'static, str> { String::schema_name() } fn json_schema(generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema { String::json_schema(generator) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/downloads.rs
crates/uv-types/src/downloads.rs
use std::sync::Arc; use uv_distribution_types::{CachedDist, DistributionId}; use uv_once_map::OnceMap; #[derive(Default, Clone)] pub struct InFlight { /// The in-flight distribution downloads. pub downloads: Arc<OnceMap<DistributionId, Result<CachedDist, String>>>, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/lib.rs
crates/uv-types/src/lib.rs
//! Fundamental types shared across uv crates. pub use builds::*; pub use downloads::*; pub use hash::*; pub use requirements::*; pub use traits::*; mod builds; mod downloads; mod hash; mod requirements; mod traits;
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/requirements.rs
crates/uv-types/src/requirements.rs
use uv_distribution_types::Requirement; use uv_normalize::ExtraName; /// A set of requirements as requested by a parent requirement. /// /// For example, given `flask[dotenv]`, the `RequestedRequirements` would include the `dotenv` /// extra, along with all of the requirements that are included in the `flask` distribution /// including their unevaluated markers. #[derive(Debug, Clone)] pub struct RequestedRequirements { /// The set of extras included on the originating requirement. extras: Box<[ExtraName]>, /// The set of requirements that were requested by the originating requirement. requirements: Box<[Requirement]>, /// Whether the dependencies were direct or transitive. direct: bool, } impl RequestedRequirements { /// Instantiate a [`RequestedRequirements`] with the given `extras` and `requirements`. pub fn new(extras: Box<[ExtraName]>, requirements: Box<[Requirement]>, direct: bool) -> Self { Self { extras, requirements, direct, } } /// Return the extras that were included on the originating requirement. pub fn extras(&self) -> &[ExtraName] { &self.extras } /// Return the requirements that were included on the originating requirement. pub fn requirements(&self) -> &[Requirement] { &self.requirements } /// Return whether the dependencies were direct or transitive. pub fn direct(&self) -> bool { self.direct } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/builds.rs
crates/uv-types/src/builds.rs
use std::path::Path; use std::sync::Arc; use dashmap::DashMap; use uv_configuration::{BuildKind, SourceStrategy}; use uv_normalize::PackageName; use uv_python::PythonEnvironment; /// Whether to enforce build isolation when building source distributions. #[derive(Debug, Default, Copy, Clone)] pub enum BuildIsolation<'a> { #[default] Isolated, Shared(&'a PythonEnvironment), SharedPackage(&'a PythonEnvironment, &'a [PackageName]), } impl BuildIsolation<'_> { /// Returns `true` if build isolation is enforced for the given package name. pub fn is_isolated(&self, package: Option<&PackageName>) -> bool { match self { Self::Isolated => true, Self::Shared(_) => false, Self::SharedPackage(_, packages) => { package.is_none_or(|package| !packages.iter().any(|p| p == package)) } } } /// Returns the shared environment for a given package, if build isolation is not enforced. pub fn shared_environment(&self, package: Option<&PackageName>) -> Option<&PythonEnvironment> { match self { Self::Isolated => None, Self::Shared(env) => Some(env), Self::SharedPackage(env, packages) => { if package.is_some_and(|package| packages.iter().any(|p| p == package)) { Some(env) } else { None } } } } } /// A key for the build cache, which includes the interpreter, source root, subdirectory, source /// strategy, and build kind. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct BuildKey { pub base_python: Box<Path>, pub source_root: Box<Path>, pub subdirectory: Option<Box<Path>>, pub source_strategy: SourceStrategy, pub build_kind: BuildKind, } /// An arena of in-process builds. #[derive(Debug)] pub struct BuildArena<T>(Arc<DashMap<BuildKey, T>>); impl<T> Default for BuildArena<T> { fn default() -> Self { Self(Arc::new(DashMap::new())) } } impl<T> Clone for BuildArena<T> { fn clone(&self) -> Self { Self(self.0.clone()) } } impl<T> BuildArena<T> { /// Insert a build entry into the arena. pub fn insert(&self, key: BuildKey, value: T) { self.0.insert(key, value); } /// Remove a build entry from the arena. pub fn remove(&self, key: &BuildKey) -> Option<T> { self.0.remove(key).map(|entry| entry.1) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/hash.rs
crates/uv-types/src/hash.rs
use std::str::FromStr; use std::sync::Arc; use rustc_hash::FxHashMap; use uv_configuration::HashCheckingMode; use uv_distribution_types::{ DistributionMetadata, HashGeneration, HashPolicy, Name, Requirement, RequirementSource, Resolution, UnresolvedRequirement, VersionId, }; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pypi_types::{HashDigest, HashDigests, HashError, ResolverMarkerEnvironment}; use uv_redacted::DisplaySafeUrl; #[derive(Debug, Default, Clone)] pub enum HashStrategy { /// No hash policy is specified. #[default] None, /// Hashes should be generated (specifically, a SHA-256 hash), but not validated. Generate(HashGeneration), /// Hashes should be validated, if present, but ignored if absent. /// /// If necessary, hashes should be generated to ensure that the archive is valid. Verify(Arc<FxHashMap<VersionId, Vec<HashDigest>>>), /// Hashes should be validated against a pre-defined list of hashes. /// /// If necessary, hashes should be generated to ensure that the archive is valid. Require(Arc<FxHashMap<VersionId, Vec<HashDigest>>>), } impl HashStrategy { /// Return the [`HashPolicy`] for the given distribution. pub fn get<T: DistributionMetadata>(&self, distribution: &T) -> HashPolicy<'_> { match self { Self::None => HashPolicy::None, Self::Generate(mode) => HashPolicy::Generate(*mode), Self::Verify(hashes) => { if let Some(hashes) = hashes.get(&distribution.version_id()) { HashPolicy::Validate(hashes.as_slice()) } else { HashPolicy::None } } Self::Require(hashes) => HashPolicy::Validate( hashes .get(&distribution.version_id()) .map(Vec::as_slice) .unwrap_or_default(), ), } } /// Return the [`HashPolicy`] for the given registry-based package. pub fn get_package(&self, name: &PackageName, version: &Version) -> HashPolicy<'_> { match self { Self::None => HashPolicy::None, Self::Generate(mode) => HashPolicy::Generate(*mode), Self::Verify(hashes) => { if let Some(hashes) = hashes.get(&VersionId::from_registry(name.clone(), version.clone())) { HashPolicy::Validate(hashes.as_slice()) } else { HashPolicy::None } } Self::Require(hashes) => HashPolicy::Validate( hashes .get(&VersionId::from_registry(name.clone(), version.clone())) .map(Vec::as_slice) .unwrap_or_default(), ), } } /// Return the [`HashPolicy`] for the given direct URL package. pub fn get_url(&self, url: &DisplaySafeUrl) -> HashPolicy<'_> { match self { Self::None => HashPolicy::None, Self::Generate(mode) => HashPolicy::Generate(*mode), Self::Verify(hashes) => { if let Some(hashes) = hashes.get(&VersionId::from_url(url)) { HashPolicy::Validate(hashes.as_slice()) } else { HashPolicy::None } } Self::Require(hashes) => HashPolicy::Validate( hashes .get(&VersionId::from_url(url)) .map(Vec::as_slice) .unwrap_or_default(), ), } } /// Returns `true` if the given registry-based package is allowed. pub fn allows_package(&self, name: &PackageName, version: &Version) -> bool { match self { Self::None => true, Self::Generate(_) => true, Self::Verify(_) => true, Self::Require(hashes) => { hashes.contains_key(&VersionId::from_registry(name.clone(), version.clone())) } } } /// Returns `true` if the given direct URL package is allowed. pub fn allows_url(&self, url: &DisplaySafeUrl) -> bool { match self { Self::None => true, Self::Generate(_) => true, Self::Verify(_) => true, Self::Require(hashes) => hashes.contains_key(&VersionId::from_url(url)), } } /// Generate the required hashes from a set of [`UnresolvedRequirement`] entries. /// /// When the environment is not given, this treats all marker expressions /// that reference the environment as true. In other words, it does /// environment independent expression evaluation. (Which in turn devolves /// to "only evaluate marker expressions that reference an extra name.") pub fn from_requirements<'a>( requirements: impl Iterator<Item = (&'a UnresolvedRequirement, &'a [String])>, constraints: impl Iterator<Item = (&'a Requirement, &'a [String])>, marker_env: Option<&ResolverMarkerEnvironment>, mode: HashCheckingMode, ) -> Result<Self, HashStrategyError> { let mut constraint_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default(); // First, index the constraints by name. for (requirement, digests) in constraints { if !requirement .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[]) { continue; } // Every constraint must be a pinned version. let Some(id) = Self::pin(requirement) else { if mode.is_require() { return Err(HashStrategyError::UnpinnedRequirement( requirement.to_string(), mode, )); } continue; }; let digests = if digests.is_empty() { // If there are no hashes, and the distribution is URL-based, attempt to extract // it from the fragment. requirement .hashes() .map(HashDigests::from) .map(|hashes| hashes.to_vec()) .unwrap_or_default() } else { // Parse the hashes. digests .iter() .map(|digest| HashDigest::from_str(digest)) .collect::<Result<Vec<_>, _>>()? }; if digests.is_empty() { continue; } constraint_hashes.insert(id, digests); } // For each requirement, map from name to allowed hashes. We use the last entry for each // package. let mut requirement_hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default(); for (requirement, digests) in requirements { if !requirement .evaluate_markers(marker_env.map(ResolverMarkerEnvironment::markers), &[]) { continue; } // Every requirement must be either a pinned version or a direct URL. let id = match &requirement { UnresolvedRequirement::Named(requirement) => { if let Some(id) = Self::pin(requirement) { id } else { if mode.is_require() { return Err(HashStrategyError::UnpinnedRequirement( requirement.to_string(), mode, )); } continue; } } UnresolvedRequirement::Unnamed(requirement) => { // Direct URLs are always allowed. VersionId::from_url(&requirement.url.verbatim) } }; let digests = if digests.is_empty() { // If there are no hashes, and the distribution is URL-based, attempt to extract // it from the fragment. requirement .hashes() .map(HashDigests::from) .map(|hashes| hashes.to_vec()) .unwrap_or_default() } else { // Parse the hashes. digests .iter() .map(|digest| HashDigest::from_str(digest)) .collect::<Result<Vec<_>, _>>()? }; let digests = if let Some(constraint) = constraint_hashes.remove(&id) { if digests.is_empty() { // If there are _only_ hashes on the constraints, use them. constraint } else { // If there are constraint and requirement hashes, take the intersection. let intersection: Vec<_> = digests .into_iter() .filter(|digest| constraint.contains(digest)) .collect(); if intersection.is_empty() { return Err(HashStrategyError::NoIntersection( requirement.to_string(), mode, )); } intersection } } else { digests }; // Under `--require-hashes`, every requirement must include a hash. if digests.is_empty() { if mode.is_require() { return Err(HashStrategyError::MissingHashes( requirement.to_string(), mode, )); } continue; } requirement_hashes.insert(id, digests); } // Merge the hashes, preferring requirements over constraints, since overlapping // requirements were already merged. let hashes: FxHashMap<VersionId, Vec<HashDigest>> = constraint_hashes .into_iter() .chain(requirement_hashes) .collect(); match mode { HashCheckingMode::Verify => Ok(Self::Verify(Arc::new(hashes))), HashCheckingMode::Require => Ok(Self::Require(Arc::new(hashes))), } } /// Generate the required hashes from a [`Resolution`]. pub fn from_resolution( resolution: &Resolution, mode: HashCheckingMode, ) -> Result<Self, HashStrategyError> { let mut hashes = FxHashMap::<VersionId, Vec<HashDigest>>::default(); for (dist, digests) in resolution.hashes() { if digests.is_empty() { // Under `--require-hashes`, every requirement must include a hash. if mode.is_require() { return Err(HashStrategyError::MissingHashes( dist.name().to_string(), mode, )); } continue; } hashes.insert(dist.version_id(), digests.to_vec()); } match mode { HashCheckingMode::Verify => Ok(Self::Verify(Arc::new(hashes))), HashCheckingMode::Require => Ok(Self::Require(Arc::new(hashes))), } } /// Pin a [`Requirement`] to a [`PackageId`], if possible. fn pin(requirement: &Requirement) -> Option<VersionId> { match &requirement.source { RequirementSource::Registry { specifier, .. } => { // Must be a single specifier. let [specifier] = specifier.as_ref() else { return None; }; // Must be pinned to a specific version. if *specifier.operator() != uv_pep440::Operator::Equal { return None; } Some(VersionId::from_registry( requirement.name.clone(), specifier.version().clone(), )) } RequirementSource::Url { url, .. } | RequirementSource::Git { url, .. } | RequirementSource::Path { url, .. } | RequirementSource::Directory { url, .. } => Some(VersionId::from_url(url)), } } } #[derive(thiserror::Error, Debug)] pub enum HashStrategyError { #[error(transparent)] Hash(#[from] HashError), #[error( "In `{1}` mode, all requirements must have their versions pinned with `==`, but found: {0}" )] UnpinnedRequirement(String, HashCheckingMode), #[error("In `{1}` mode, all requirements must have a hash, but none were provided for: {0}")] MissingHashes(String, HashCheckingMode), #[error( "In `{1}` mode, all requirements must have a hash, but there were no overlapping hashes between the requirements and constraints for: {0}" )] NoIntersection(String, HashCheckingMode), }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-types/src/traits.rs
crates/uv-types/src/traits.rs
use std::fmt::{Debug, Display, Formatter}; use std::future::Future; use std::ops::Deref; use std::path::{Path, PathBuf}; use anyhow::Result; use rustc_hash::FxHashSet; use uv_cache::Cache; use uv_configuration::{BuildKind, BuildOptions, BuildOutput, SourceStrategy}; use uv_distribution_filename::DistFilename; use uv_distribution_types::{ CachedDist, ConfigSettings, DependencyMetadata, DistributionId, ExtraBuildRequires, ExtraBuildVariables, IndexCapabilities, IndexLocations, InstalledDist, IsBuildBackendError, PackageConfigSettings, Requirement, Resolution, SourceDist, }; use uv_git::GitResolver; use uv_normalize::PackageName; use uv_python::{Interpreter, PythonEnvironment}; use uv_workspace::WorkspaceCache; use crate::{BuildArena, BuildIsolation}; /// Avoids cyclic crate dependencies between resolver, installer and builder. /// /// To resolve the dependencies of a packages, we may need to build one or more source /// distributions. To building a source distribution, we need to create a virtual environment from /// the same base python as we use for the root resolution, resolve the build requirements /// (potentially which nested source distributions, recursing a level deeper), installing /// them and then build. The installer, the resolver and the source distribution builder are each in /// their own crate. To avoid circular crate dependencies, this type dispatches between the three /// crates with its three main methods ([`BuildContext::resolve`], [`BuildContext::install`] and /// [`BuildContext::setup_build`]). /// /// The overall main crate structure looks like this: /// /// ```text /// ┌────────────────┐ /// │ uv │ /// └───────▲────────┘ /// │ /// │ /// ┌───────┴────────┐ /// ┌─────────►│ uv-dispatch │◄─────────┐ /// │ └───────▲────────┘ │ /// │ │ │ /// │ │ │ /// ┌───────┴────────┐ ┌───────┴────────┐ ┌────────┴────────────────┐ /// │ uv-resolver │ │ uv-installer │ │ uv-build-frontend │ /// └───────▲────────┘ └───────▲────────┘ └────────▲────────────────┘ /// │ │ │ /// └─────────────┐ │ ┌──────────────┘ /// ┌──┴────┴────┴───┐ /// │ uv-types │ /// └────────────────┘ /// ``` /// /// Put in a different way, the types here allow `uv-resolver` to depend on `uv-build` and /// `uv-build-frontend` to depend on `uv-resolver` without having actual crate dependencies between /// them. pub trait BuildContext { type SourceDistBuilder: SourceBuildTrait; // Note: this function is async deliberately, because downstream code may need to // run async code to get the interpreter, to resolve the Python version. /// Return a reference to the interpreter. fn interpreter(&self) -> impl Future<Output = &Interpreter> + '_; /// Return a reference to the cache. fn cache(&self) -> &Cache; /// Return a reference to the Git resolver. fn git(&self) -> &GitResolver; /// Return a reference to the build arena. fn build_arena(&self) -> &BuildArena<Self::SourceDistBuilder>; /// Return a reference to the discovered registry capabilities. fn capabilities(&self) -> &IndexCapabilities; /// Return a reference to any pre-defined static metadata. fn dependency_metadata(&self) -> &DependencyMetadata; /// Whether source distribution building or pre-built wheels is disabled. /// /// This [`BuildContext::setup_build`] calls will fail if builds are disabled. /// 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; /// The [`ConfigSettings`] used to build a specific package. fn config_settings_package(&self) -> &PackageConfigSettings; /// Whether to incorporate `tool.uv.sources` when resolving requirements. fn sources(&self) -> SourceStrategy; /// The index locations being searched. fn locations(&self) -> &IndexLocations; /// Workspace discovery caching. fn workspace_cache(&self) -> &WorkspaceCache; /// Get the extra build requirements. fn extra_build_requires(&self) -> &ExtraBuildRequires; /// Get the extra build variables. fn extra_build_variables(&self) -> &ExtraBuildVariables; /// Resolve the given requirements into a ready-to-install set of package versions. fn resolve<'a>( &'a self, requirements: &'a [Requirement], build_stack: &'a BuildStack, ) -> impl Future<Output = Result<Resolution, impl IsBuildBackendError>> + 'a; /// Install the given set of package versions into the virtual environment. The environment must /// use the same base Python as [`BuildContext::interpreter`] fn install<'a>( &'a self, resolution: &'a Resolution, venv: &'a PythonEnvironment, build_stack: &'a BuildStack, ) -> impl Future<Output = Result<Vec<CachedDist>, impl IsBuildBackendError>> + 'a; /// Set up a source distribution build by installing the required dependencies. A wrapper for /// `uv_build::SourceBuild::setup`. /// /// For PEP 517 builds, this calls `get_requires_for_build_wheel`. /// /// `version_id` is for error reporting only. /// `dist` is for safety checks and may be null for editable builds. fn setup_build<'a>( &'a self, source: &'a Path, subdirectory: Option<&'a Path>, install_path: &'a Path, version_id: Option<&'a str>, dist: Option<&'a SourceDist>, sources: SourceStrategy, build_kind: BuildKind, build_output: BuildOutput, build_stack: BuildStack, ) -> impl Future<Output = Result<Self::SourceDistBuilder, impl IsBuildBackendError>> + 'a; /// Build by calling directly into the uv build backend without PEP 517, if possible. /// /// Checks if the source tree uses uv as build backend. If not, it returns `Ok(None)`, otherwise /// it builds and returns the name of the built file. /// /// `version_id` is for error reporting only. fn direct_build<'a>( &'a self, source: &'a Path, subdirectory: Option<&'a Path>, output_dir: &'a Path, sources: SourceStrategy, build_kind: BuildKind, version_id: Option<&'a str>, ) -> impl Future<Output = Result<Option<DistFilename>, impl IsBuildBackendError>> + 'a; } /// A wrapper for `uv_build::SourceBuild` to avoid cyclical crate dependencies. /// /// You can either call only `wheel()` to build the wheel directly, call only `metadata()` to get /// the metadata without performing the actual or first call `metadata()` and then `wheel()`. pub trait SourceBuildTrait { /// A wrapper for `uv_build::SourceBuild::get_metadata_without_build`. /// /// For PEP 517 builds, this calls `prepare_metadata_for_build_wheel` /// /// Returns the metadata directory if we're having a PEP 517 build and the /// `prepare_metadata_for_build_wheel` hook exists fn metadata(&mut self) -> impl Future<Output = Result<Option<PathBuf>, AnyErrorBuild>>; /// A wrapper for `uv_build::SourceBuild::build`. /// /// For PEP 517 builds, this calls `build_wheel`. /// /// Returns the filename of the built wheel inside the given `wheel_dir`. The filename is a /// string and not a `WheelFilename` because the on disk filename might not be normalized in the /// same way as uv would. fn wheel<'a>( &'a self, wheel_dir: &'a Path, ) -> impl Future<Output = Result<String, AnyErrorBuild>> + 'a; } /// A wrapper for [`uv_installer::SitePackages`] pub trait InstalledPackagesProvider: Clone + Send + Sync + 'static { fn iter(&self) -> impl Iterator<Item = &InstalledDist>; fn get_packages(&self, name: &PackageName) -> Vec<&InstalledDist>; } /// An [`InstalledPackagesProvider`] with no packages in it. #[derive(Clone)] pub struct EmptyInstalledPackages; impl InstalledPackagesProvider for EmptyInstalledPackages { fn iter(&self) -> impl Iterator<Item = &InstalledDist> { std::iter::empty() } fn get_packages(&self, _name: &PackageName) -> Vec<&InstalledDist> { Vec::new() } } /// [`anyhow::Error`]-like wrapper type for [`BuildDispatch`] method return values, that also makes /// [`IsBuildBackendError`] work as [`thiserror`] `#[source]`. /// /// The errors types have the same problem as [`BuildDispatch`] generally: The `uv-resolver`, /// `uv-installer` and `uv-build-frontend` error types all reference each other: /// Resolution and installation may need to build packages, while the build frontend needs to /// resolve and install for the PEP 517 build environment. /// /// Usually, [`anyhow::Error`] is opaque error type of choice. In this case though, we error type /// that we can inspect on whether it's a build backend error with [`IsBuildBackendError`], and /// [`anyhow::Error`] does not allow attaching more traits. The next choice would be /// `Box<dyn std::error::Error + IsBuildFrontendError + Send + Sync + 'static>`, but [`thiserror`] /// complains about the internal `AsDynError` not being implemented when being used as `#[source]`. /// This struct is an otherwise transparent error wrapper that thiserror recognizes. pub struct AnyErrorBuild(Box<dyn IsBuildBackendError>); impl Debug for AnyErrorBuild { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Debug::fmt(&self.0, f) } } impl Display for AnyErrorBuild { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) } } impl std::error::Error for AnyErrorBuild { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { self.0.source() } #[allow(deprecated)] fn description(&self) -> &str { self.0.description() } #[allow(deprecated)] fn cause(&self) -> Option<&dyn std::error::Error> { self.0.cause() } } impl<T: IsBuildBackendError> From<T> for AnyErrorBuild { fn from(err: T) -> Self { Self(Box::new(err)) } } impl Deref for AnyErrorBuild { type Target = dyn IsBuildBackendError; fn deref(&self) -> &Self::Target { &*self.0 } } /// The stack of packages being built. #[derive(Debug, Clone, Default)] pub struct BuildStack(FxHashSet<DistributionId>); impl BuildStack { /// Return an empty stack. pub fn empty() -> Self { Self(FxHashSet::default()) } pub fn contains(&self, id: &DistributionId) -> bool { self.0.contains(id) } /// Push a package onto the stack. pub fn insert(&mut self, id: DistributionId) -> bool { self.0.insert(id) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/build_requires.rs
crates/uv-distribution-types/src/build_requires.rs
use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; use uv_cache_key::{CacheKey, CacheKeyHasher}; use uv_normalize::PackageName; use crate::{Name, Requirement, RequirementSource, Resolution}; #[derive(Debug, thiserror::Error)] pub enum ExtraBuildRequiresError { #[error( "`{0}` was declared as an extra build dependency with `match-runtime = true`, but was not found in the resolution" )] NotFound(PackageName), #[error( "Dependencies marked with `match-runtime = true` cannot include version specifiers, but found: `{0}{1}`" )] VersionSpecifiersNotAllowed(PackageName, Box<RequirementSource>), #[error( "Dependencies marked with `match-runtime = true` cannot include URL constraints, but found: `{0}{1}`" )] UrlNotAllowed(PackageName, Box<RequirementSource>), } /// Lowered extra build dependencies with source resolution applied. #[derive(Debug, Clone, Default)] pub struct ExtraBuildRequires(BTreeMap<PackageName, Vec<ExtraBuildRequirement>>); impl std::ops::Deref for ExtraBuildRequires { type Target = BTreeMap<PackageName, Vec<ExtraBuildRequirement>>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for ExtraBuildRequires { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl IntoIterator for ExtraBuildRequires { type Item = (PackageName, Vec<ExtraBuildRequirement>); type IntoIter = std::collections::btree_map::IntoIter<PackageName, Vec<ExtraBuildRequirement>>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl FromIterator<(PackageName, Vec<ExtraBuildRequirement>)> for ExtraBuildRequires { fn from_iter<T: IntoIterator<Item = (PackageName, Vec<ExtraBuildRequirement>)>>( iter: T, ) -> Self { Self(iter.into_iter().collect()) } } #[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)] pub struct ExtraBuildRequirement { /// The underlying [`Requirement`] for the build requirement. pub requirement: Requirement, /// Whether this build requirement should match the runtime environment. pub match_runtime: bool, } impl From<ExtraBuildRequirement> for Requirement { fn from(value: ExtraBuildRequirement) -> Self { value.requirement } } impl CacheKey for ExtraBuildRequirement { fn cache_key(&self, state: &mut CacheKeyHasher) { self.requirement.cache_key(state); self.match_runtime.cache_key(state); } } impl ExtraBuildRequires { /// Apply runtime constraints from a resolution to the extra build requirements. pub fn match_runtime(self, resolution: &Resolution) -> Result<Self, ExtraBuildRequiresError> { self.into_iter() .filter(|(_, requirements)| !requirements.is_empty()) .filter(|(name, _)| resolution.distributions().any(|dist| dist.name() == name)) .map(|(name, requirements)| { let requirements = requirements .into_iter() .map(|requirement| match requirement { ExtraBuildRequirement { requirement, match_runtime: true, } => { // Reject requirements with `match-runtime = true` that include any form // of constraint. if let RequirementSource::Registry { specifier, .. } = &requirement.source { if !specifier.is_empty() { return Err( ExtraBuildRequiresError::VersionSpecifiersNotAllowed( requirement.name.clone(), Box::new(requirement.source.clone()), ), ); } } else { return Err(ExtraBuildRequiresError::VersionSpecifiersNotAllowed( requirement.name.clone(), Box::new(requirement.source.clone()), )); } let dist = resolution .distributions() .find(|dist| dist.name() == &requirement.name) .ok_or_else(|| { ExtraBuildRequiresError::NotFound(requirement.name.clone()) })?; let requirement = Requirement { source: RequirementSource::from(dist), ..requirement }; Ok::<_, ExtraBuildRequiresError>(ExtraBuildRequirement { requirement, match_runtime: true, }) } requirement => Ok(requirement), }) .collect::<Result<Vec<_>, _>>()?; Ok::<_, ExtraBuildRequiresError>((name, requirements)) }) .collect::<Result<Self, _>>() } } /// A map of extra build variables, from variable name to value. pub type BuildVariables = BTreeMap<String, String>; /// Extra environment variables to set during builds, on a per-package basis. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct ExtraBuildVariables(BTreeMap<PackageName, BuildVariables>); impl std::ops::Deref for ExtraBuildVariables { type Target = BTreeMap<PackageName, BuildVariables>; fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for ExtraBuildVariables { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl IntoIterator for ExtraBuildVariables { type Item = (PackageName, BuildVariables); type IntoIter = std::collections::btree_map::IntoIter<PackageName, BuildVariables>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } impl FromIterator<(PackageName, BuildVariables)> for ExtraBuildVariables { fn from_iter<T: IntoIterator<Item = (PackageName, BuildVariables)>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } impl CacheKey for ExtraBuildVariables { fn cache_key(&self, state: &mut CacheKeyHasher) { for (package, vars) in &self.0 { package.as_str().cache_key(state); for (key, value) in vars { key.cache_key(state); value.cache_key(state); } } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/cached.rs
crates/uv-distribution-types/src/cached.rs
use std::path::Path; use uv_cache_info::CacheInfo; use uv_distribution_filename::WheelFilename; use uv_normalize::PackageName; use uv_pypi_types::{HashDigest, HashDigests, VerbatimParsedUrl}; use crate::{ BuildInfo, BuiltDist, Dist, DistributionMetadata, Hashed, InstalledMetadata, InstalledVersion, Name, ParsedUrl, SourceDist, VersionOrUrlRef, }; /// A built distribution (wheel) that exists in the local cache. #[derive(Debug, Clone, Hash, PartialEq, Eq)] #[allow(clippy::large_enum_variant)] pub enum CachedDist { /// The distribution exists in a registry, like `PyPI`. Registry(CachedRegistryDist), /// The distribution exists at an arbitrary URL. Url(CachedDirectUrlDist), } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct CachedRegistryDist { pub filename: WheelFilename, pub path: Box<Path>, pub hashes: HashDigests, pub cache_info: CacheInfo, pub build_info: Option<BuildInfo>, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct CachedDirectUrlDist { pub filename: WheelFilename, pub url: VerbatimParsedUrl, pub path: Box<Path>, pub hashes: HashDigests, pub cache_info: CacheInfo, pub build_info: Option<BuildInfo>, } impl CachedDist { /// Initialize a [`CachedDist`] from a [`Dist`]. pub fn from_remote( remote: Dist, filename: WheelFilename, hashes: HashDigests, cache_info: CacheInfo, build_info: Option<BuildInfo>, path: Box<Path>, ) -> Self { match remote { Dist::Built(BuiltDist::Registry(_dist)) => Self::Registry(CachedRegistryDist { filename, path, hashes, cache_info, build_info, }), Dist::Built(BuiltDist::DirectUrl(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), Dist::Built(BuiltDist::Path(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), Dist::Source(SourceDist::Registry(_dist)) => Self::Registry(CachedRegistryDist { filename, path, hashes, cache_info, build_info, }), Dist::Source(SourceDist::DirectUrl(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), Dist::Source(SourceDist::Git(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), Dist::Source(SourceDist::Path(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), Dist::Source(SourceDist::Directory(dist)) => Self::Url(CachedDirectUrlDist { filename, url: VerbatimParsedUrl { parsed_url: dist.parsed_url(), verbatim: dist.url, }, hashes, cache_info, build_info, path, }), } } /// Return the [`Path`] at which the distribution is stored on-disk. pub fn path(&self) -> &Path { match self { Self::Registry(dist) => &dist.path, Self::Url(dist) => &dist.path, } } /// Return the [`CacheInfo`] of the distribution. pub fn cache_info(&self) -> &CacheInfo { match self { Self::Registry(dist) => &dist.cache_info, Self::Url(dist) => &dist.cache_info, } } /// Return the [`BuildInfo`] of the distribution. pub fn build_info(&self) -> Option<&BuildInfo> { match self { Self::Registry(dist) => dist.build_info.as_ref(), Self::Url(dist) => dist.build_info.as_ref(), } } /// Return the [`ParsedUrl`] of the distribution, if it exists. pub fn parsed_url(&self) -> Option<&ParsedUrl> { match self { Self::Registry(_) => None, Self::Url(dist) => Some(&dist.url.parsed_url), } } /// Returns the [`WheelFilename`] of the distribution. pub fn filename(&self) -> &WheelFilename { match self { Self::Registry(dist) => &dist.filename, Self::Url(dist) => &dist.filename, } } } impl Hashed for CachedRegistryDist { fn hashes(&self) -> &[HashDigest] { self.hashes.as_slice() } } impl Name for CachedRegistryDist { fn name(&self) -> &PackageName { &self.filename.name } } impl Name for CachedDirectUrlDist { fn name(&self) -> &PackageName { &self.filename.name } } impl Name for CachedDist { fn name(&self) -> &PackageName { match self { Self::Registry(dist) => dist.name(), Self::Url(dist) => dist.name(), } } } impl DistributionMetadata for CachedRegistryDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Version(&self.filename.version) } } impl DistributionMetadata for CachedDirectUrlDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url.verbatim) } } impl DistributionMetadata for CachedDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Registry(dist) => dist.version_or_url(), Self::Url(dist) => dist.version_or_url(), } } } impl InstalledMetadata for CachedRegistryDist { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Version(&self.filename.version) } } impl InstalledMetadata for CachedDirectUrlDist { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Url(&self.url.verbatim, &self.filename.version) } } impl InstalledMetadata for CachedDist { fn installed_version(&self) -> InstalledVersion<'_> { match self { Self::Registry(dist) => dist.installed_version(), Self::Url(dist) => dist.installed_version(), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/index_name.rs
crates/uv-distribution-types/src/index_name.rs
use std::borrow::Cow; use std::ops::Deref; use std::str::FromStr; use thiserror::Error; use uv_small_str::SmallString; /// The normalized name of an index. /// /// Index names may contain letters, digits, hyphens, underscores, and periods, and must be ASCII. #[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, serde::Serialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct IndexName(SmallString); impl IndexName { /// Validates the given index name and returns [`IndexName`] if it's valid, or an error /// otherwise. pub fn new(name: &str) -> Result<Self, IndexNameError> { for c in name.chars() { match c { 'a'..='z' | 'A'..='Z' | '0'..='9' | '-' | '_' | '.' => {} c if c.is_ascii() => { return Err(IndexNameError::UnsupportedCharacter(c, name.to_string())); } c => { return Err(IndexNameError::NonAsciiName(c, name.to_string())); } } } Ok(Self(SmallString::from(name))) } /// Converts the index name to an environment variable name. /// /// For example, given `IndexName("foo-bar")`, this will return `"FOO_BAR"`. pub fn to_env_var(&self) -> String { self.0 .chars() .map(|c| { if c.is_ascii_alphanumeric() { c.to_ascii_uppercase() } else { '_' } }) .collect::<String>() } } impl FromStr for IndexName { type Err = IndexNameError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::new(s) } } impl<'de> serde::de::Deserialize<'de> for IndexName { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { let s = Cow::<'_, str>::deserialize(deserializer)?; Self::new(&s).map_err(serde::de::Error::custom) } } impl std::fmt::Display for IndexName { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl AsRef<str> for IndexName { fn as_ref(&self) -> &str { &self.0 } } impl Deref for IndexName { type Target = str; fn deref(&self) -> &Self::Target { &self.0 } } /// An error that can occur when parsing an [`IndexName`]. #[derive(Error, Debug)] pub enum IndexNameError { #[error("Index included a name, but the name was empty")] EmptyName, #[error( "Index names may only contain letters, digits, hyphens, underscores, and periods, but found unsupported character (`{0}`) in: `{1}`" )] UnsupportedCharacter(char, String), #[error("Index names must be ASCII, but found non-ASCII character (`{0}`) in: `{1}`")] NonAsciiName(char, String), }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/dist_error.rs
crates/uv-distribution-types/src/dist_error.rs
use std::collections::VecDeque; use std::fmt::{Debug, Display, Formatter}; use petgraph::Direction; use petgraph::prelude::EdgeRef; use rustc_hash::FxHashSet; use version_ranges::Ranges; use uv_normalize::{ExtraName, GroupName, PackageName}; use uv_pep440::Version; use crate::{ BuiltDist, Dist, DistRef, Edge, Name, Node, RequestedDist, Resolution, ResolvedDist, SourceDist, }; /// Inspect whether an error type is a build error. pub trait IsBuildBackendError: std::error::Error + Send + Sync + 'static { /// Returns whether the build backend failed to build the package, so it's not a uv error. fn is_build_backend_error(&self) -> bool; } /// The operation(s) that failed when reporting an error with a distribution. #[derive(Debug)] pub enum DistErrorKind { Download, DownloadAndBuild, Build, BuildBackend, Read, } impl DistErrorKind { pub fn from_requested_dist(dist: &RequestedDist, err: &impl IsBuildBackendError) -> Self { match dist { RequestedDist::Installed(_) => Self::Read, RequestedDist::Installable(dist) => Self::from_dist(dist, err), } } pub fn from_dist(dist: &Dist, err: &impl IsBuildBackendError) -> Self { if err.is_build_backend_error() { Self::BuildBackend } else { match dist { Dist::Built(BuiltDist::Path(_)) => Self::Read, Dist::Source(SourceDist::Path(_) | SourceDist::Directory(_)) => Self::Build, Dist::Built(_) => Self::Download, Dist::Source(source_dist) => { if source_dist.is_local() { Self::Build } else { Self::DownloadAndBuild } } } } } } impl Display for DistErrorKind { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Download => f.write_str("Failed to download"), Self::DownloadAndBuild => f.write_str("Failed to download and build"), Self::Build => f.write_str("Failed to build"), Self::BuildBackend => f.write_str("Failed to build"), Self::Read => f.write_str("Failed to read"), } } } /// A chain of derivation steps from the root package to the current package, to explain why a /// package is included in the resolution. #[derive(Debug, Default, Clone, PartialEq, Eq, Hash)] pub struct DerivationChain(Vec<DerivationStep>); impl FromIterator<DerivationStep> for DerivationChain { fn from_iter<T: IntoIterator<Item = DerivationStep>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } impl DerivationChain { /// Compute a [`DerivationChain`] from a resolution graph. /// /// This is used to construct a derivation chain upon install failure in the `uv pip` context, /// where we don't have a lockfile describing the resolution. pub fn from_resolution(resolution: &Resolution, target: DistRef<'_>) -> Option<Self> { // Find the target distribution in the resolution graph. let target = resolution.graph().node_indices().find(|node| { let Node::Dist { dist: ResolvedDist::Installable { dist, .. }, .. } = &resolution.graph()[*node] else { return false; }; target == dist.as_ref().into() })?; // Perform a BFS to find the shortest path to the root. let mut queue = VecDeque::new(); queue.push_back((target, None, None, Vec::new())); // TODO(charlie): Consider respecting markers here. let mut seen = FxHashSet::default(); while let Some((node, extra, group, mut path)) = queue.pop_front() { if !seen.insert(node) { continue; } match &resolution.graph()[node] { Node::Root => { path.reverse(); path.pop(); return Some(Self::from_iter(path)); } Node::Dist { dist, .. } => { for edge in resolution.graph().edges_directed(node, Direction::Incoming) { let mut path = path.clone(); path.push(DerivationStep::new( dist.name().clone(), extra.clone(), group.clone(), dist.version().cloned(), Ranges::empty(), )); let target = edge.source(); let extra = match edge.weight() { Edge::Optional(extra) => Some(extra.clone()), _ => None, }; let group = match edge.weight() { Edge::Dev(group) => Some(group.clone()), _ => None, }; queue.push_back((target, extra, group, path)); } } } } None } /// Returns the length of the derivation chain. pub fn len(&self) -> usize { self.0.len() } /// Returns `true` if the derivation chain is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Returns an iterator over the steps in the derivation chain. pub fn iter(&self) -> std::slice::Iter<'_, DerivationStep> { self.0.iter() } } impl<'chain> IntoIterator for &'chain DerivationChain { type Item = &'chain DerivationStep; type IntoIter = std::slice::Iter<'chain, DerivationStep>; fn into_iter(self) -> Self::IntoIter { self.0.iter() } } impl IntoIterator for DerivationChain { type Item = DerivationStep; type IntoIter = std::vec::IntoIter<DerivationStep>; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() } } /// A step in a derivation chain. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct DerivationStep { /// The name of the package. pub name: PackageName, /// The enabled extra of the package, if any. pub extra: Option<ExtraName>, /// The enabled dependency group of the package, if any. pub group: Option<GroupName>, /// The version of the package. pub version: Option<Version>, /// The constraints applied to the subsequent package in the chain. pub range: Ranges<Version>, } impl DerivationStep { /// Create a [`DerivationStep`] from a package name and version. pub fn new( name: PackageName, extra: Option<ExtraName>, group: Option<GroupName>, version: Option<Version>, range: Ranges<Version>, ) -> Self { Self { name, extra, group, version, range, } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/lib.rs
crates/uv-distribution-types/src/lib.rs
//! ## Type hierarchy //! //! When we receive the requirements from `pip sync`, we check which requirements already fulfilled //! in the users environment ([`InstalledDist`]), whether the matching package is in our wheel cache //! ([`CachedDist`]) or whether we need to download, (potentially build) and install it ([`Dist`]). //! These three variants make up [`BuiltDist`]. //! //! ## `Dist` //! A [`Dist`] is either a built distribution (a wheel), or a source distribution that exists at //! some location. We translate every PEP 508 requirement e.g. from `requirements.txt` or from //! `pyproject.toml`'s `[project] dependencies` into a [`Dist`] by checking each index. //! * [`BuiltDist`]: A wheel, with its three possible origins: //! * [`RegistryBuiltDist`] //! * [`DirectUrlBuiltDist`] //! * [`PathBuiltDist`] //! * [`SourceDist`]: A source distribution, with its four possible origins: //! * [`RegistrySourceDist`] //! * [`DirectUrlSourceDist`] //! * [`GitSourceDist`] //! * [`PathSourceDist`] //! //! ## `CachedDist` //! A [`CachedDist`] is a built distribution (wheel) that exists in the local cache, with the two //! possible origins we currently track: //! * [`CachedRegistryDist`] //! * [`CachedDirectUrlDist`] //! //! ## `InstalledDist` //! An [`InstalledDist`] is built distribution (wheel) that is installed in a virtual environment, //! with the two possible origins we currently track: //! * [`InstalledRegistryDist`] //! * [`InstalledDirectUrlDist`] //! //! Since we read this information from [`direct_url.json`](https://packaging.python.org/en/latest/specifications/direct-url-data-structure/), it doesn't match the information [`Dist`] exactly. use std::borrow::Cow; use std::path; use std::path::Path; use std::str::FromStr; use url::Url; use uv_distribution_filename::{ DistExtension, SourceDistExtension, SourceDistFilename, WheelFilename, }; use uv_fs::normalize_absolute_path; use uv_git_types::GitUrl; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pep508::{Pep508Url, VerbatimUrl}; use uv_pypi_types::{ ParsedArchiveUrl, ParsedDirectoryUrl, ParsedGitUrl, ParsedPathUrl, ParsedUrl, VerbatimParsedUrl, }; use uv_redacted::DisplaySafeUrl; pub use crate::annotation::*; pub use crate::any::*; pub use crate::build_info::*; pub use crate::build_requires::*; pub use crate::buildable::*; pub use crate::cached::*; pub use crate::config_settings::*; pub use crate::dependency_metadata::*; pub use crate::diagnostic::*; pub use crate::dist_error::*; pub use crate::error::*; pub use crate::file::*; pub use crate::hash::*; pub use crate::id::*; pub use crate::index::*; pub use crate::index_name::*; pub use crate::index_url::*; pub use crate::installed::*; pub use crate::known_platform::*; pub use crate::origin::*; pub use crate::pip_index::*; pub use crate::prioritized_distribution::*; pub use crate::requested::*; pub use crate::requirement::*; pub use crate::requires_python::*; pub use crate::resolution::*; pub use crate::resolved::*; pub use crate::specified_requirement::*; pub use crate::status_code_strategy::*; pub use crate::traits::*; mod annotation; mod any; mod build_info; mod build_requires; mod buildable; mod cached; mod config_settings; mod dependency_metadata; mod diagnostic; mod dist_error; mod error; mod file; mod hash; mod id; mod index; mod index_name; mod index_url; mod installed; mod known_platform; mod origin; mod pip_index; mod prioritized_distribution; mod requested; mod requirement; mod requires_python; mod resolution; mod resolved; mod specified_requirement; mod status_code_strategy; mod traits; #[derive(Debug, Clone)] pub enum VersionOrUrlRef<'a, T: Pep508Url = VerbatimUrl> { /// A PEP 440 version specifier, used to identify a distribution in a registry. Version(&'a Version), /// A URL, used to identify a distribution at an arbitrary location. Url(&'a T), } impl<'a, T: Pep508Url> VersionOrUrlRef<'a, T> { /// If it is a URL, return its value. pub fn url(&self) -> Option<&'a T> { match self { Self::Version(_) => None, Self::Url(url) => Some(url), } } } impl Verbatim for VersionOrUrlRef<'_> { fn verbatim(&self) -> Cow<'_, str> { match self { Self::Version(version) => Cow::Owned(format!("=={version}")), Self::Url(url) => Cow::Owned(format!(" @ {}", url.verbatim())), } } } impl std::fmt::Display for VersionOrUrlRef<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Version(version) => write!(f, "=={version}"), Self::Url(url) => write!(f, " @ {url}"), } } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum InstalledVersion<'a> { /// A PEP 440 version specifier, used to identify a distribution in a registry. Version(&'a Version), /// A URL, used to identify a distribution at an arbitrary location, along with the version /// specifier to which it resolved. Url(&'a DisplaySafeUrl, &'a Version), } impl<'a> InstalledVersion<'a> { /// If it is a URL, return its value. pub fn url(&self) -> Option<&'a DisplaySafeUrl> { match self { Self::Version(_) => None, Self::Url(url, _) => Some(url), } } /// If it is a version, return its value. pub fn version(&self) -> &'a Version { match self { Self::Version(version) => version, Self::Url(_, version) => version, } } } impl std::fmt::Display for InstalledVersion<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Version(version) => write!(f, "=={version}"), Self::Url(url, version) => write!(f, "=={version} (from {url})"), } } } /// Either a built distribution, a wheel, or a source distribution that exists at some location. /// /// The location can be an index, URL or path (wheel), or index, URL, path or Git repository (source distribution). #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum Dist { Built(BuiltDist), Source(SourceDist), } /// A reference to a built or source distribution. #[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] pub enum DistRef<'a> { Built(&'a BuiltDist), Source(&'a SourceDist), } /// A wheel, with its three possible origins (index, url, path) #[derive(Debug, Clone, Hash, PartialEq, Eq)] #[allow(clippy::large_enum_variant)] pub enum BuiltDist { Registry(RegistryBuiltDist), DirectUrl(DirectUrlBuiltDist), Path(PathBuiltDist), } /// A source distribution, with its possible origins (index, url, path, git) #[derive(Debug, Clone, Hash, PartialEq, Eq)] #[allow(clippy::large_enum_variant)] pub enum SourceDist { Registry(RegistrySourceDist), DirectUrl(DirectUrlSourceDist), Git(GitSourceDist), Path(PathSourceDist), Directory(DirectorySourceDist), } /// A built distribution (wheel) that exists in a registry, like `PyPI`. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RegistryBuiltWheel { pub filename: WheelFilename, pub file: Box<File>, pub index: IndexUrl, } /// A built distribution (wheel) that exists in a registry, like `PyPI`. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RegistryBuiltDist { /// All wheels associated with this distribution. It is guaranteed /// that there is at least one wheel. pub wheels: Vec<RegistryBuiltWheel>, /// The "best" wheel selected based on the current wheel tag /// environment. /// /// This is guaranteed to point into a valid entry in `wheels`. pub best_wheel_index: usize, /// A source distribution if one exists for this distribution. /// /// It is possible for this to be `None`. For example, when a distribution /// has no source distribution, or if it does have one but isn't compatible /// with the user configuration. (e.g., If `Requires-Python` isn't /// compatible with the installed/target Python versions, or if something /// like `--exclude-newer` was used.) pub sdist: Option<RegistrySourceDist>, // Ideally, this type would have an index URL on it, and the // `RegistryBuiltDist` and `RegistrySourceDist` types would *not* have an // index URL on them. Alas, the --find-links feature makes it technically // possible for the indexes to diverge across wheels/sdists in the same // distribution. // // Note though that at time of writing, when generating a universal lock // file, we require that all index URLs across wheels/sdists for a single // distribution are equivalent. } /// A built distribution (wheel) that exists at an arbitrary URL. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct DirectUrlBuiltDist { /// We require that wheel urls end in the full wheel filename, e.g. /// `https://example.org/packages/flask-3.0.0-py3-none-any.whl` pub filename: WheelFilename, /// The URL without the subdirectory fragment. pub location: Box<DisplaySafeUrl>, /// The URL as it was provided by the user. pub url: VerbatimUrl, } /// A built distribution (wheel) that exists in a local directory. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct PathBuiltDist { pub filename: WheelFilename, /// The absolute path to the wheel which we use for installing. pub install_path: Box<Path>, /// The URL as it was provided by the user. pub url: VerbatimUrl, } /// A source distribution that exists in a registry, like `PyPI`. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct RegistrySourceDist { pub name: PackageName, pub version: Version, pub file: Box<File>, /// The file extension, e.g. `tar.gz`, `zip`, etc. pub ext: SourceDistExtension, pub index: IndexUrl, /// When an sdist is selected, it may be the case that there were /// available wheels too. There are many reasons why a wheel might not /// have been chosen (maybe none available are compatible with the /// current environment), but we still want to track that they exist. In /// particular, for generating a universal lockfile, we do not want to /// skip emitting wheels to the lockfile just because the host generating /// the lockfile didn't have any compatible wheels available. pub wheels: Vec<RegistryBuiltWheel>, } /// A source distribution that exists at an arbitrary URL. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct DirectUrlSourceDist { /// Unlike [`DirectUrlBuiltDist`], we can't require a full filename with a version here, people /// like using e.g. `foo @ https://github.com/org/repo/archive/master.zip` pub name: PackageName, /// The URL without the subdirectory fragment. pub location: Box<DisplaySafeUrl>, /// The subdirectory within the archive in which the source distribution is located. pub subdirectory: Option<Box<Path>>, /// The file extension, e.g. `tar.gz`, `zip`, etc. pub ext: SourceDistExtension, /// The URL as it was provided by the user, including the subdirectory fragment. pub url: VerbatimUrl, } /// A source distribution that exists in a Git repository. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct GitSourceDist { pub name: PackageName, /// The URL without the revision and subdirectory fragment. pub git: Box<GitUrl>, /// The subdirectory within the Git repository in which the source distribution is located. pub subdirectory: Option<Box<Path>>, /// The URL as it was provided by the user, including the revision and subdirectory fragment. pub url: VerbatimUrl, } /// A source distribution that exists in a local archive (e.g., a `.tar.gz` file). #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct PathSourceDist { pub name: PackageName, pub version: Option<Version>, /// The absolute path to the distribution which we use for installing. pub install_path: Box<Path>, /// The file extension, e.g. `tar.gz`, `zip`, etc. pub ext: SourceDistExtension, /// The URL as it was provided by the user. pub url: VerbatimUrl, } /// A source distribution that exists in a local directory. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct DirectorySourceDist { pub name: PackageName, /// The absolute path to the distribution which we use for installing. pub install_path: Box<Path>, /// Whether the package should be installed in editable mode. pub editable: Option<bool>, /// Whether the package should be built and installed. pub r#virtual: Option<bool>, /// The URL as it was provided by the user. pub url: VerbatimUrl, } impl Dist { /// A remote built distribution (`.whl`) or source distribution from a `http://` or `https://` /// URL. pub fn from_http_url( name: PackageName, url: VerbatimUrl, location: DisplaySafeUrl, subdirectory: Option<Box<Path>>, ext: DistExtension, ) -> Result<Self, Error> { match ext { DistExtension::Wheel => { // Validate that the name in the wheel matches that of the requirement. let filename = WheelFilename::from_str(&url.filename()?)?; if filename.name != name { return Err(Error::PackageNameMismatch( name, filename.name, url.verbatim().to_string(), )); } Ok(Self::Built(BuiltDist::DirectUrl(DirectUrlBuiltDist { filename, location: Box::new(location), url, }))) } DistExtension::Source(ext) => { Ok(Self::Source(SourceDist::DirectUrl(DirectUrlSourceDist { name, location: Box::new(location), subdirectory, ext, url, }))) } } } /// A local built or source distribution from a `file://` URL. pub fn from_file_url( name: PackageName, url: VerbatimUrl, install_path: &Path, ext: DistExtension, ) -> Result<Self, Error> { // Convert to an absolute path. let install_path = path::absolute(install_path)?; // Normalize the path. let install_path = normalize_absolute_path(&install_path)?; // Validate that the path exists. if !install_path.exists() { return Err(Error::NotFound(url.to_url())); } // Determine whether the path represents a built or source distribution. match ext { DistExtension::Wheel => { // Validate that the name in the wheel matches that of the requirement. let filename = WheelFilename::from_str(&url.filename()?)?; if filename.name != name { return Err(Error::PackageNameMismatch( name, filename.name, url.verbatim().to_string(), )); } Ok(Self::Built(BuiltDist::Path(PathBuiltDist { filename, install_path: install_path.into_boxed_path(), url, }))) } DistExtension::Source(ext) => { // If there is a version in the filename, record it. let version = url .filename() .ok() .and_then(|filename| { SourceDistFilename::parse(filename.as_ref(), ext, &name).ok() }) .map(|filename| filename.version); Ok(Self::Source(SourceDist::Path(PathSourceDist { name, version, install_path: install_path.into_boxed_path(), ext, url, }))) } } } /// A local source tree from a `file://` URL. pub fn from_directory_url( name: PackageName, url: VerbatimUrl, install_path: &Path, editable: Option<bool>, r#virtual: Option<bool>, ) -> Result<Self, Error> { // Convert to an absolute path. let install_path = path::absolute(install_path)?; // Normalize the path. let install_path = normalize_absolute_path(&install_path)?; // Validate that the path exists. if !install_path.exists() { return Err(Error::NotFound(url.to_url())); } // Determine whether the path represents an archive or a directory. Ok(Self::Source(SourceDist::Directory(DirectorySourceDist { name, install_path: install_path.into_boxed_path(), editable, r#virtual, url, }))) } /// A remote source distribution from a `git+https://` or `git+ssh://` url. pub fn from_git_url( name: PackageName, url: VerbatimUrl, git: GitUrl, subdirectory: Option<Box<Path>>, ) -> Result<Self, Error> { Ok(Self::Source(SourceDist::Git(GitSourceDist { name, git: Box::new(git), subdirectory, url, }))) } /// Create a [`Dist`] for a URL-based distribution. pub fn from_url(name: PackageName, url: VerbatimParsedUrl) -> Result<Self, Error> { match url.parsed_url { ParsedUrl::Archive(archive) => Self::from_http_url( name, url.verbatim, archive.url, archive.subdirectory, archive.ext, ), ParsedUrl::Path(file) => { Self::from_file_url(name, url.verbatim, &file.install_path, file.ext) } ParsedUrl::Directory(directory) => Self::from_directory_url( name, url.verbatim, &directory.install_path, directory.editable, directory.r#virtual, ), ParsedUrl::Git(git) => { Self::from_git_url(name, url.verbatim, git.url, git.subdirectory) } } } /// Return true if the distribution is editable. pub fn is_editable(&self) -> bool { match self { Self::Source(dist) => dist.is_editable(), Self::Built(_) => false, } } /// Return true if the distribution refers to a local file or directory. pub fn is_local(&self) -> bool { match self { Self::Source(dist) => dist.is_local(), Self::Built(dist) => dist.is_local(), } } /// Returns the [`IndexUrl`], if the distribution is from a registry. pub fn index(&self) -> Option<&IndexUrl> { match self { Self::Built(dist) => dist.index(), Self::Source(dist) => dist.index(), } } /// Returns the [`File`] instance, if this dist is from a registry with simple json api support pub fn file(&self) -> Option<&File> { match self { Self::Built(built) => built.file(), Self::Source(source) => source.file(), } } /// Return the source tree of the distribution, if available. pub fn source_tree(&self) -> Option<&Path> { match self { Self::Built { .. } => None, Self::Source(source) => source.source_tree(), } } /// Returns the version of the distribution, if it is known. pub fn version(&self) -> Option<&Version> { match self { Self::Built(wheel) => Some(wheel.version()), Self::Source(source_dist) => source_dist.version(), } } /// Convert this distribution into a reference. pub fn as_ref(&self) -> DistRef<'_> { match self { Self::Built(dist) => DistRef::Built(dist), Self::Source(dist) => DistRef::Source(dist), } } } impl<'a> From<&'a Dist> for DistRef<'a> { fn from(dist: &'a Dist) -> Self { match dist { Dist::Built(built) => DistRef::Built(built), Dist::Source(source) => DistRef::Source(source), } } } impl<'a> From<&'a SourceDist> for DistRef<'a> { fn from(dist: &'a SourceDist) -> Self { DistRef::Source(dist) } } impl<'a> From<&'a BuiltDist> for DistRef<'a> { fn from(dist: &'a BuiltDist) -> Self { DistRef::Built(dist) } } impl BuiltDist { /// Return true if the distribution refers to a local file or directory. pub fn is_local(&self) -> bool { matches!(self, Self::Path(_)) } /// Returns the [`IndexUrl`], if the distribution is from a registry. pub fn index(&self) -> Option<&IndexUrl> { match self { Self::Registry(registry) => Some(&registry.best_wheel().index), Self::DirectUrl(_) => None, Self::Path(_) => None, } } /// Returns the [`File`] instance, if this distribution is from a registry. pub fn file(&self) -> Option<&File> { match self { Self::Registry(registry) => Some(&registry.best_wheel().file), Self::DirectUrl(_) | Self::Path(_) => None, } } pub fn version(&self) -> &Version { match self { Self::Registry(wheels) => &wheels.best_wheel().filename.version, Self::DirectUrl(wheel) => &wheel.filename.version, Self::Path(wheel) => &wheel.filename.version, } } } impl SourceDist { /// Returns the [`IndexUrl`], if the distribution is from a registry. pub fn index(&self) -> Option<&IndexUrl> { match self { Self::Registry(registry) => Some(&registry.index), Self::DirectUrl(_) | Self::Git(_) | Self::Path(_) | Self::Directory(_) => None, } } /// Returns the [`File`] instance, if this dist is from a registry with simple json api support pub fn file(&self) -> Option<&File> { match self { Self::Registry(registry) => Some(&registry.file), Self::DirectUrl(_) | Self::Git(_) | Self::Path(_) | Self::Directory(_) => None, } } /// Returns the [`Version`] of the distribution, if it is known. pub fn version(&self) -> Option<&Version> { match self { Self::Registry(source_dist) => Some(&source_dist.version), Self::DirectUrl(_) | Self::Git(_) | Self::Path(_) | Self::Directory(_) => None, } } /// Returns `true` if the distribution is editable. pub fn is_editable(&self) -> bool { match self { Self::Directory(DirectorySourceDist { editable, .. }) => editable.unwrap_or(false), _ => false, } } /// Returns `true` if the distribution is virtual. pub fn is_virtual(&self) -> bool { match self { Self::Directory(DirectorySourceDist { r#virtual, .. }) => r#virtual.unwrap_or(false), _ => false, } } /// Returns `true` if the distribution refers to a local file or directory. pub fn is_local(&self) -> bool { matches!(self, Self::Directory(_) | Self::Path(_)) } /// Returns the path to the source distribution, if it's a local distribution. pub fn as_path(&self) -> Option<&Path> { match self { Self::Path(dist) => Some(&dist.install_path), Self::Directory(dist) => Some(&dist.install_path), _ => None, } } /// Returns the source tree of the distribution, if available. pub fn source_tree(&self) -> Option<&Path> { match self { Self::Directory(dist) => Some(&dist.install_path), _ => None, } } } impl RegistryBuiltDist { /// Returns the best or "most compatible" wheel in this distribution. pub fn best_wheel(&self) -> &RegistryBuiltWheel { &self.wheels[self.best_wheel_index] } } impl DirectUrlBuiltDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Archive(ParsedArchiveUrl::from_source( (*self.location).clone(), None, DistExtension::Wheel, )) } } impl PathBuiltDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Path(ParsedPathUrl::from_source( self.install_path.clone(), DistExtension::Wheel, self.url.to_url(), )) } } impl PathSourceDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Path(ParsedPathUrl::from_source( self.install_path.clone(), DistExtension::Source(self.ext), self.url.to_url(), )) } } impl DirectUrlSourceDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Archive(ParsedArchiveUrl::from_source( (*self.location).clone(), self.subdirectory.clone(), DistExtension::Source(self.ext), )) } } impl GitSourceDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Git(ParsedGitUrl::from_source( (*self.git).clone(), self.subdirectory.clone(), )) } } impl DirectorySourceDist { /// Return the [`ParsedUrl`] for the distribution. pub fn parsed_url(&self) -> ParsedUrl { ParsedUrl::Directory(ParsedDirectoryUrl::from_source( self.install_path.clone(), self.editable, self.r#virtual, self.url.to_url(), )) } } impl Name for RegistryBuiltWheel { fn name(&self) -> &PackageName { &self.filename.name } } impl Name for RegistryBuiltDist { fn name(&self) -> &PackageName { self.best_wheel().name() } } impl Name for DirectUrlBuiltDist { fn name(&self) -> &PackageName { &self.filename.name } } impl Name for PathBuiltDist { fn name(&self) -> &PackageName { &self.filename.name } } impl Name for RegistrySourceDist { fn name(&self) -> &PackageName { &self.name } } impl Name for DirectUrlSourceDist { fn name(&self) -> &PackageName { &self.name } } impl Name for GitSourceDist { fn name(&self) -> &PackageName { &self.name } } impl Name for PathSourceDist { fn name(&self) -> &PackageName { &self.name } } impl Name for DirectorySourceDist { fn name(&self) -> &PackageName { &self.name } } impl Name for SourceDist { fn name(&self) -> &PackageName { match self { Self::Registry(dist) => dist.name(), Self::DirectUrl(dist) => dist.name(), Self::Git(dist) => dist.name(), Self::Path(dist) => dist.name(), Self::Directory(dist) => dist.name(), } } } impl Name for BuiltDist { fn name(&self) -> &PackageName { match self { Self::Registry(dist) => dist.name(), Self::DirectUrl(dist) => dist.name(), Self::Path(dist) => dist.name(), } } } impl Name for Dist { fn name(&self) -> &PackageName { match self { Self::Built(dist) => dist.name(), Self::Source(dist) => dist.name(), } } } impl Name for CompatibleDist<'_> { fn name(&self) -> &PackageName { match self { Self::InstalledDist(dist) => dist.name(), Self::SourceDist { sdist, prioritized: _, } => sdist.name(), Self::CompatibleWheel { wheel, priority: _, prioritized: _, } => wheel.name(), Self::IncompatibleWheel { sdist, wheel: _, prioritized: _, } => sdist.name(), } } } impl DistributionMetadata for RegistryBuiltWheel { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Version(&self.filename.version) } } impl DistributionMetadata for RegistryBuiltDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { self.best_wheel().version_or_url() } } impl DistributionMetadata for DirectUrlBuiltDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for PathBuiltDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for RegistrySourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Version(&self.version) } } impl DistributionMetadata for DirectUrlSourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for GitSourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for PathSourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for DirectorySourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Url(&self.url) } } impl DistributionMetadata for SourceDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Registry(dist) => dist.version_or_url(), Self::DirectUrl(dist) => dist.version_or_url(), Self::Git(dist) => dist.version_or_url(), Self::Path(dist) => dist.version_or_url(), Self::Directory(dist) => dist.version_or_url(), } } } impl DistributionMetadata for BuiltDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Registry(dist) => dist.version_or_url(), Self::DirectUrl(dist) => dist.version_or_url(), Self::Path(dist) => dist.version_or_url(), } } } impl DistributionMetadata for Dist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Built(dist) => dist.version_or_url(), Self::Source(dist) => dist.version_or_url(), } } } impl RemoteSource for File { fn filename(&self) -> Result<Cow<'_, str>, Error> { Ok(Cow::Borrowed(&self.filename)) } fn size(&self) -> Option<u64> { self.size } } impl RemoteSource for Url { fn filename(&self) -> Result<Cow<'_, str>, Error> { // Identify the last segment of the URL as the filename. let mut path_segments = self .path_segments() .ok_or_else(|| Error::MissingPathSegments(self.to_string()))?; // This is guaranteed by the contract of `Url::path_segments`. let last = path_segments .next_back() .expect("path segments is non-empty"); // Decode the filename, which may be percent-encoded. let filename = percent_encoding::percent_decode_str(last).decode_utf8()?; Ok(filename) } fn size(&self) -> Option<u64> { None } } impl RemoteSource for UrlString { fn filename(&self) -> Result<Cow<'_, str>, Error> { // Take the last segment, stripping any query or fragment. let last = self .base_str() .split('/') .next_back() .ok_or_else(|| Error::MissingPathSegments(self.to_string()))?; // Decode the filename, which may be percent-encoded. let filename = percent_encoding::percent_decode_str(last).decode_utf8()?; Ok(filename) } fn size(&self) -> Option<u64> { None } } impl RemoteSource for RegistryBuiltWheel { fn filename(&self) -> Result<Cow<'_, str>, Error> { self.file.filename() } fn size(&self) -> Option<u64> { self.file.size() } } impl RemoteSource for RegistryBuiltDist { fn filename(&self) -> Result<Cow<'_, str>, Error> { self.best_wheel().filename() } fn size(&self) -> Option<u64> { self.best_wheel().size() } } impl RemoteSource for RegistrySourceDist { fn filename(&self) -> Result<Cow<'_, str>, Error> { self.file.filename() } fn size(&self) -> Option<u64> { self.file.size() } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/index.rs
crates/uv-distribution-types/src/index.rs
use std::path::Path; use std::str::FromStr; use serde::{Deserialize, Serialize}; use thiserror::Error; use url::Url; use uv_auth::{AuthPolicy, Credentials}; use uv_redacted::DisplaySafeUrl; use uv_small_str::SmallString; use crate::index_name::{IndexName, IndexNameError}; use crate::origin::Origin; use crate::{IndexStatusCodeStrategy, IndexUrl, IndexUrlError, SerializableStatusCode}; /// Cache control configuration for an index. #[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize, Default)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub struct IndexCacheControl { /// Cache control header for Simple API requests. pub api: Option<SmallString>, /// Cache control header for file downloads. pub files: Option<SmallString>, } impl IndexCacheControl { /// Return the default Simple API cache control headers for the given index URL, if applicable. pub fn simple_api_cache_control(_url: &Url) -> Option<&'static str> { None } /// Return the default files cache control headers for the given index URL, if applicable. pub fn artifact_cache_control(url: &Url) -> Option<&'static str> { let dominated_by_pytorch_or_nvidia = url.host_str().is_some_and(|host| { host.eq_ignore_ascii_case("download.pytorch.org") || host.eq_ignore_ascii_case("pypi.nvidia.com") }); if dominated_by_pytorch_or_nvidia { // Some wheels in the PyTorch registry were accidentally uploaded with `no-cache,no-store,must-revalidate`. // The PyTorch team plans to correct this in the future, but in the meantime we override // the cache control headers to allow caching of static files. // // See: https://github.com/pytorch/pytorch/pull/149218 // // The same issue applies to files hosted on `pypi.nvidia.com`. Some("max-age=365000000, immutable, public") } else { None } } } #[derive(Debug, Clone, Serialize, Deserialize)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub struct Index { /// The name of the index. /// /// Index names can be used to reference indexes elsewhere in the configuration. For example, /// you can pin a package to a specific index by name: /// /// ```toml /// [[tool.uv.index]] /// name = "pytorch" /// url = "https://download.pytorch.org/whl/cu121" /// /// [tool.uv.sources] /// torch = { index = "pytorch" } /// ``` pub name: Option<IndexName>, /// The URL of the index. /// /// Expects to receive a URL (e.g., `https://pypi.org/simple`) or a local path. pub url: IndexUrl, /// Mark the index as explicit. /// /// Explicit indexes will _only_ be used when explicitly requested via a `[tool.uv.sources]` /// definition, as in: /// /// ```toml /// [[tool.uv.index]] /// name = "pytorch" /// url = "https://download.pytorch.org/whl/cu121" /// explicit = true /// /// [tool.uv.sources] /// torch = { index = "pytorch" } /// ``` #[serde(default)] pub explicit: bool, /// Mark the index as the default index. /// /// By default, uv uses PyPI as the default index, such that even if additional indexes are /// defined via `[[tool.uv.index]]`, PyPI will still be used as a fallback for packages that /// aren't found elsewhere. To disable the PyPI default, set `default = true` on at least one /// other index. /// /// Marking an index as default will move it to the front of the list of indexes, such that it /// is given the highest priority when resolving packages. #[serde(default)] pub default: bool, /// The origin of the index (e.g., a CLI flag, a user-level configuration file, etc.). #[serde(skip)] pub origin: Option<Origin>, /// The format used by the index. /// /// Indexes can either be PEP 503-compliant (i.e., a PyPI-style registry implementing the Simple /// API) or structured as a flat list of distributions (e.g., `--find-links`). In both cases, /// indexes can point to either local or remote resources. #[serde(default)] pub format: IndexFormat, /// The URL of the upload endpoint. /// /// When using `uv publish --index <name>`, this URL is used for publishing. /// /// A configuration for the default index PyPI would look as follows: /// /// ```toml /// [[tool.uv.index]] /// name = "pypi" /// url = "https://pypi.org/simple" /// publish-url = "https://upload.pypi.org/legacy/" /// ``` pub publish_url: Option<DisplaySafeUrl>, /// When uv should use authentication for requests to the index. /// /// ```toml /// [[tool.uv.index]] /// name = "my-index" /// url = "https://<omitted>/simple" /// authenticate = "always" /// ``` #[serde(default)] pub authenticate: AuthPolicy, /// Status codes that uv should ignore when deciding whether /// to continue searching in the next index after a failure. /// /// ```toml /// [[tool.uv.index]] /// name = "my-index" /// url = "https://<omitted>/simple" /// ignore-error-codes = [401, 403] /// ``` #[serde(default)] pub ignore_error_codes: Option<Vec<SerializableStatusCode>>, /// Cache control configuration for this index. /// /// When set, these headers will override the server's cache control headers /// for both package metadata requests and artifact downloads. /// /// ```toml /// [[tool.uv.index]] /// name = "my-index" /// url = "https://<omitted>/simple" /// cache-control = { api = "max-age=600", files = "max-age=3600" } /// ``` #[serde(default)] pub cache_control: Option<IndexCacheControl>, } impl PartialEq for Index { fn eq(&self, other: &Self) -> bool { let Self { name, url, explicit, default, origin: _, format, publish_url, authenticate, ignore_error_codes, cache_control, } = self; *url == other.url && *name == other.name && *explicit == other.explicit && *default == other.default && *format == other.format && *publish_url == other.publish_url && *authenticate == other.authenticate && *ignore_error_codes == other.ignore_error_codes && *cache_control == other.cache_control } } impl Eq for Index {} impl PartialOrd for Index { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for Index { fn cmp(&self, other: &Self) -> std::cmp::Ordering { let Self { name, url, explicit, default, origin: _, format, publish_url, authenticate, ignore_error_codes, cache_control, } = self; url.cmp(&other.url) .then_with(|| name.cmp(&other.name)) .then_with(|| explicit.cmp(&other.explicit)) .then_with(|| default.cmp(&other.default)) .then_with(|| format.cmp(&other.format)) .then_with(|| publish_url.cmp(&other.publish_url)) .then_with(|| authenticate.cmp(&other.authenticate)) .then_with(|| ignore_error_codes.cmp(&other.ignore_error_codes)) .then_with(|| cache_control.cmp(&other.cache_control)) } } impl std::hash::Hash for Index { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { name, url, explicit, default, origin: _, format, publish_url, authenticate, ignore_error_codes, cache_control, } = self; url.hash(state); name.hash(state); explicit.hash(state); default.hash(state); format.hash(state); publish_url.hash(state); authenticate.hash(state); ignore_error_codes.hash(state); cache_control.hash(state); } } #[derive( Default, Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, serde::Deserialize, )] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case")] pub enum IndexFormat { /// A PyPI-style index implementing the Simple Repository API. #[default] Simple, /// A `--find-links`-style index containing a flat list of wheels and source distributions. Flat, } impl Index { /// Initialize an [`Index`] from a pip-style `--index-url`. pub fn from_index_url(url: IndexUrl) -> Self { Self { url, name: None, explicit: false, default: true, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, } } /// Initialize an [`Index`] from a pip-style `--extra-index-url`. pub fn from_extra_index_url(url: IndexUrl) -> Self { Self { url, name: None, explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, } } /// Initialize an [`Index`] from a pip-style `--find-links`. pub fn from_find_links(url: IndexUrl) -> Self { Self { url, name: None, explicit: false, default: false, origin: None, format: IndexFormat::Flat, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, } } /// Set the [`Origin`] of the index. #[must_use] pub fn with_origin(mut self, origin: Origin) -> Self { self.origin = Some(origin); self } /// Return the [`IndexUrl`] of the index. pub fn url(&self) -> &IndexUrl { &self.url } /// Consume the [`Index`] and return the [`IndexUrl`]. pub fn into_url(self) -> IndexUrl { self.url } /// Return the raw [`Url`] of the index. pub fn raw_url(&self) -> &DisplaySafeUrl { self.url.url() } /// Return the root [`Url`] of the index, if applicable. /// /// For indexes with a `/simple` endpoint, this is simply the URL with the final segment /// removed. This is useful, e.g., for credential propagation to other endpoints on the index. pub fn root_url(&self) -> Option<DisplaySafeUrl> { self.url.root() } /// Retrieve the credentials for the index, either from the environment, or from the URL itself. pub fn credentials(&self) -> Option<Credentials> { // If the index is named, and credentials are provided via the environment, prefer those. if let Some(name) = self.name.as_ref() { if let Some(credentials) = Credentials::from_env(name.to_env_var()) { return Some(credentials); } } // Otherwise, extract the credentials from the URL. Credentials::from_url(self.url.url()) } /// Resolve the index relative to the given root directory. pub fn relative_to(mut self, root_dir: &Path) -> Result<Self, IndexUrlError> { if let IndexUrl::Path(ref url) = self.url { if let Some(given) = url.given() { self.url = IndexUrl::parse(given, Some(root_dir))?; } } Ok(self) } /// Return the [`IndexStatusCodeStrategy`] for this index. pub fn status_code_strategy(&self) -> IndexStatusCodeStrategy { if let Some(ignore_error_codes) = &self.ignore_error_codes { IndexStatusCodeStrategy::from_ignored_error_codes(ignore_error_codes) } else { IndexStatusCodeStrategy::from_index_url(self.url.url()) } } /// Return the cache control header for file requests to this index, if any. pub fn artifact_cache_control(&self) -> Option<&str> { if let Some(artifact_cache_control) = self .cache_control .as_ref() .and_then(|cache_control| cache_control.files.as_deref()) { Some(artifact_cache_control) } else { IndexCacheControl::artifact_cache_control(self.url.url()) } } /// Return the cache control header for API requests to this index, if any. pub fn simple_api_cache_control(&self) -> Option<&str> { if let Some(api_cache_control) = self .cache_control .as_ref() .and_then(|cache_control| cache_control.api.as_deref()) { Some(api_cache_control) } else { IndexCacheControl::simple_api_cache_control(self.url.url()) } } } impl From<IndexUrl> for Index { fn from(value: IndexUrl) -> Self { Self { name: None, url: value, explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, } } } impl FromStr for Index { type Err = IndexSourceError; fn from_str(s: &str) -> Result<Self, Self::Err> { // Determine whether the source is prefixed with a name, as in `name=https://pypi.org/simple`. if let Some((name, url)) = s.split_once('=') { if !name.chars().any(|c| c == ':') { let name = IndexName::from_str(name)?; let url = IndexUrl::from_str(url)?; return Ok(Self { name: Some(name), url, explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, }); } } // Otherwise, assume the source is a URL. let url = IndexUrl::from_str(s)?; Ok(Self { name: None, url, explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: AuthPolicy::default(), ignore_error_codes: None, cache_control: None, }) } } /// An [`IndexUrl`] along with the metadata necessary to query the index. #[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] pub struct IndexMetadata { /// The URL of the index. pub url: IndexUrl, /// The format used by the index. pub format: IndexFormat, } impl IndexMetadata { /// Return a reference to the [`IndexMetadata`]. pub fn as_ref(&self) -> IndexMetadataRef<'_> { let Self { url, format: kind } = self; IndexMetadataRef { url, format: *kind } } /// Consume the [`IndexMetadata`] and return the [`IndexUrl`]. pub fn into_url(self) -> IndexUrl { self.url } } /// A reference to an [`IndexMetadata`]. #[derive(Debug, Copy, Clone)] pub struct IndexMetadataRef<'a> { /// The URL of the index. pub url: &'a IndexUrl, /// The format used by the index. pub format: IndexFormat, } impl IndexMetadata { /// Return the [`IndexUrl`] of the index. pub fn url(&self) -> &IndexUrl { &self.url } } impl IndexMetadataRef<'_> { /// Return the [`IndexUrl`] of the index. pub fn url(&self) -> &IndexUrl { self.url } } impl<'a> From<&'a Index> for IndexMetadataRef<'a> { fn from(value: &'a Index) -> Self { Self { url: &value.url, format: value.format, } } } impl<'a> From<&'a IndexMetadata> for IndexMetadataRef<'a> { fn from(value: &'a IndexMetadata) -> Self { Self { url: &value.url, format: value.format, } } } impl From<IndexUrl> for IndexMetadata { fn from(value: IndexUrl) -> Self { Self { url: value, format: IndexFormat::Simple, } } } impl<'a> From<&'a IndexUrl> for IndexMetadataRef<'a> { fn from(value: &'a IndexUrl) -> Self { Self { url: value, format: IndexFormat::Simple, } } } /// An error that can occur when parsing an [`Index`]. #[derive(Error, Debug)] pub enum IndexSourceError { #[error(transparent)] Url(#[from] IndexUrlError), #[error(transparent)] IndexName(#[from] IndexNameError), #[error("Index included a name, but the name was empty")] EmptyName, } #[cfg(test)] mod tests { use super::*; #[test] fn test_index_cache_control_headers() { // Test that cache control headers are properly parsed from TOML let toml_str = r#" name = "test-index" url = "https://test.example.com/simple" cache-control = { api = "max-age=600", files = "max-age=3600" } "#; let index: Index = toml::from_str(toml_str).unwrap(); assert_eq!(index.name.as_ref().unwrap().as_ref(), "test-index"); assert!(index.cache_control.is_some()); let cache_control = index.cache_control.as_ref().unwrap(); assert_eq!(cache_control.api.as_deref(), Some("max-age=600")); assert_eq!(cache_control.files.as_deref(), Some("max-age=3600")); } #[test] fn test_index_without_cache_control() { // Test that indexes work without cache control headers let toml_str = r#" name = "test-index" url = "https://test.example.com/simple" "#; let index: Index = toml::from_str(toml_str).unwrap(); assert_eq!(index.name.as_ref().unwrap().as_ref(), "test-index"); assert_eq!(index.cache_control, None); } #[test] fn test_index_partial_cache_control() { // Test that cache control can have just one field let toml_str = r#" name = "test-index" url = "https://test.example.com/simple" cache-control = { api = "max-age=300" } "#; let index: Index = toml::from_str(toml_str).unwrap(); assert_eq!(index.name.as_ref().unwrap().as_ref(), "test-index"); assert!(index.cache_control.is_some()); let cache_control = index.cache_control.as_ref().unwrap(); assert_eq!(cache_control.api.as_deref(), Some("max-age=300")); assert_eq!(cache_control.files, None); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/id.rs
crates/uv-distribution-types/src/id.rs
use std::fmt::{Display, Formatter}; use std::path::PathBuf; use uv_cache_key::{CanonicalUrl, RepositoryUrl}; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pypi_types::HashDigest; use uv_redacted::DisplaySafeUrl; /// A unique identifier for a package. A package can either be identified by a name (e.g., `black`) /// or a URL (e.g., `git+https://github.com/psf/black`). #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum PackageId { /// The identifier consists of a package name. Name(PackageName), /// The identifier consists of a URL. Url(CanonicalUrl), } impl PackageId { /// Create a new [`PackageId`] from a package name and version. pub fn from_registry(name: PackageName) -> Self { Self::Name(name) } /// Create a new [`PackageId`] from a URL. pub fn from_url(url: &DisplaySafeUrl) -> Self { Self::Url(CanonicalUrl::new(url)) } } impl Display for PackageId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Name(name) => write!(f, "{name}"), Self::Url(url) => write!(f, "{url}"), } } } /// A unique identifier for a package at a specific version (e.g., `black==23.10.0`). #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum VersionId { /// The identifier consists of a package name and version. NameVersion(PackageName, Version), /// The identifier consists of a URL. Url(CanonicalUrl), } impl VersionId { /// Create a new [`VersionId`] from a package name and version. pub fn from_registry(name: PackageName, version: Version) -> Self { Self::NameVersion(name, version) } /// Create a new [`VersionId`] from a URL. pub fn from_url(url: &DisplaySafeUrl) -> Self { Self::Url(CanonicalUrl::new(url)) } } impl Display for VersionId { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::NameVersion(name, version) => write!(f, "{name}-{version}"), Self::Url(url) => write!(f, "{url}"), } } } /// A unique resource identifier for the distribution, like a SHA-256 hash of the distribution's /// contents. /// /// A distribution is a specific archive of a package at a specific version. For a given package /// version, there may be multiple distributions, e.g., source distribution, along with /// multiple binary distributions (wheels) for different platforms. As a concrete example, /// `black-23.10.0-py3-none-any.whl` would represent a (binary) distribution of the `black` package /// at version `23.10.0`. /// /// The distribution ID is used to uniquely identify a distribution. Ideally, the distribution /// ID should be a hash of the distribution's contents, though in practice, it's only required /// that the ID is unique within a single invocation of the resolver (and so, e.g., a hash of /// the URL would also be sufficient). #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum DistributionId { Url(CanonicalUrl), PathBuf(PathBuf), Digest(HashDigest), AbsoluteUrl(String), RelativeUrl(String, String), } /// A unique identifier for a resource, like a URL or a Git repository. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum ResourceId { Url(RepositoryUrl), PathBuf(PathBuf), Digest(HashDigest), AbsoluteUrl(String), RelativeUrl(String, String), } impl From<&Self> for VersionId { /// Required for `WaitMap::wait`. fn from(value: &Self) -> Self { value.clone() } } impl From<&Self> for DistributionId { /// Required for `WaitMap::wait`. fn from(value: &Self) -> Self { value.clone() } } impl From<&Self> for ResourceId { /// Required for `WaitMap::wait`. fn from(value: &Self) -> Self { value.clone() } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/buildable.rs
crates/uv-distribution-types/src/buildable.rs
use std::borrow::Cow; use std::path::Path; use uv_distribution_filename::SourceDistExtension; use uv_git_types::GitUrl; use uv_pep440::{Version, VersionSpecifiers}; use uv_pep508::VerbatimUrl; use uv_normalize::PackageName; use uv_redacted::DisplaySafeUrl; use crate::{DirectorySourceDist, GitSourceDist, Name, PathSourceDist, SourceDist}; /// A reference to a source that can be built into a built distribution. /// /// This can either be a distribution (e.g., a package on a registry) or a direct URL. /// /// Distributions can _also_ point to URLs in lieu of a registry; however, the primary distinction /// here is that a distribution will always include a package name, while a URL will not. #[derive(Debug, Clone)] pub enum BuildableSource<'a> { Dist(&'a SourceDist), Url(SourceUrl<'a>), } impl BuildableSource<'_> { /// Return the [`PackageName`] of the source, if available. pub fn name(&self) -> Option<&PackageName> { match self { Self::Dist(dist) => Some(dist.name()), Self::Url(_) => None, } } /// Return the source tree of the source, if available. pub fn source_tree(&self) -> Option<&Path> { match self { Self::Dist(dist) => dist.source_tree(), Self::Url(url) => url.source_tree(), } } /// Return the [`Version`] of the source, if available. pub fn version(&self) -> Option<&Version> { match self { Self::Dist(SourceDist::Registry(dist)) => Some(&dist.version), Self::Dist(SourceDist::Path(dist)) => dist.version.as_ref(), Self::Dist(_) => None, Self::Url(_) => None, } } /// Return the [`BuildableSource`] as a [`SourceDist`], if it is a distribution. pub fn as_dist(&self) -> Option<&SourceDist> { match self { Self::Dist(dist) => Some(dist), Self::Url(_) => None, } } /// Returns `true` if the source is editable. pub fn is_editable(&self) -> bool { match self { Self::Dist(dist) => dist.is_editable(), Self::Url(url) => url.is_editable(), } } /// Return true if the source refers to a local source tree (i.e., a directory). pub fn is_source_tree(&self) -> bool { match self { Self::Dist(dist) => matches!(dist, SourceDist::Directory(_)), 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<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Dist(dist) => write!(f, "{dist}"), Self::Url(url) => write!(f, "{url}"), } } } /// A reference to a source distribution defined by a URL. #[derive(Debug, Clone)] pub enum SourceUrl<'a> { Direct(DirectSourceUrl<'a>), Git(GitSourceUrl<'a>), Path(PathSourceUrl<'a>), Directory(DirectorySourceUrl<'a>), } impl SourceUrl<'_> { /// Return the [`DisplaySafeUrl`] of the source. pub fn url(&self) -> &DisplaySafeUrl { match self { Self::Direct(dist) => dist.url, Self::Git(dist) => dist.url, Self::Path(dist) => dist.url, Self::Directory(dist) => dist.url, } } /// Return the source tree of the source, if available. pub fn source_tree(&self) -> Option<&Path> { match self { Self::Directory(dist) => Some(&dist.install_path), _ => None, } } /// Returns `true` if the source is editable. pub fn is_editable(&self) -> bool { matches!( self, Self::Directory(DirectorySourceUrl { editable: Some(true), .. }) ) } /// Return true if the source refers to a local file or directory. pub fn is_local(&self) -> bool { matches!(self, Self::Path(_) | Self::Directory(_)) } } impl std::fmt::Display for SourceUrl<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Direct(url) => write!(f, "{url}"), Self::Git(url) => write!(f, "{url}"), Self::Path(url) => write!(f, "{url}"), Self::Directory(url) => write!(f, "{url}"), } } } #[derive(Debug, Clone)] pub struct DirectSourceUrl<'a> { pub url: &'a DisplaySafeUrl, pub subdirectory: Option<&'a Path>, pub ext: SourceDistExtension, } impl std::fmt::Display for DirectSourceUrl<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{url}", url = self.url) } } #[derive(Debug, Clone)] pub struct GitSourceUrl<'a> { /// The URL with the revision and subdirectory fragment. pub url: &'a VerbatimUrl, pub git: &'a GitUrl, /// The URL without the revision and subdirectory fragment. pub subdirectory: Option<&'a Path>, } impl std::fmt::Display for GitSourceUrl<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{url}", url = self.url) } } impl<'a> From<&'a GitSourceDist> for GitSourceUrl<'a> { fn from(dist: &'a GitSourceDist) -> Self { Self { url: &dist.url, git: &dist.git, subdirectory: dist.subdirectory.as_deref(), } } } #[derive(Debug, Clone)] pub struct PathSourceUrl<'a> { pub url: &'a DisplaySafeUrl, pub path: Cow<'a, Path>, pub ext: SourceDistExtension, } impl std::fmt::Display for PathSourceUrl<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{url}", url = self.url) } } impl<'a> From<&'a PathSourceDist> for PathSourceUrl<'a> { fn from(dist: &'a PathSourceDist) -> Self { Self { url: &dist.url, path: Cow::Borrowed(&dist.install_path), ext: dist.ext, } } } #[derive(Debug, Clone)] pub struct DirectorySourceUrl<'a> { pub url: &'a DisplaySafeUrl, pub install_path: Cow<'a, Path>, pub editable: Option<bool>, } impl std::fmt::Display for DirectorySourceUrl<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{url}", url = self.url) } } impl<'a> From<&'a DirectorySourceDist> for DirectorySourceUrl<'a> { fn from(dist: &'a DirectorySourceDist) -> Self { Self { url: &dist.url, install_path: Cow::Borrowed(&dist.install_path), editable: dist.editable, } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/build_info.rs
crates/uv-distribution-types/src/build_info.rs
use uv_cache_key::{CacheKey, CacheKeyHasher, cache_digest}; use crate::{BuildVariables, ConfigSettings, ExtraBuildRequirement}; /// A digest representing the build settings, such as build dependencies or other build-time /// configuration. #[derive(Default, Debug, Clone, Hash, PartialEq, Eq, serde::Deserialize, serde::Serialize)] pub struct BuildInfo { #[serde(default, skip_serializing_if = "ConfigSettings::is_empty")] config_settings: ConfigSettings, #[serde(default, skip_serializing_if = "Vec::is_empty")] extra_build_requires: Vec<ExtraBuildRequirement>, #[serde(default, skip_serializing_if = "BuildVariables::is_empty")] extra_build_variables: BuildVariables, } impl CacheKey for BuildInfo { fn cache_key(&self, state: &mut CacheKeyHasher) { self.config_settings.cache_key(state); self.extra_build_requires.cache_key(state); self.extra_build_variables.cache_key(state); } } impl BuildInfo { /// Creates a [`BuildInfo`] instance with the given configuration settings, extra build /// dependencies, and extra build variables. pub fn from_settings( config_settings: &ConfigSettings, extra_build_dependencies: &[ExtraBuildRequirement], extra_build_variables: Option<&BuildVariables>, ) -> Self { Self { config_settings: config_settings.clone(), extra_build_requires: extra_build_dependencies.to_vec(), extra_build_variables: extra_build_variables.cloned().unwrap_or_default(), } } /// Returns `true` if the [`BuildInfo`] is empty, meaning it has no configuration settings, pub fn is_empty(&self) -> bool { self.config_settings.is_empty() && self.extra_build_requires.is_empty() && self.extra_build_variables.is_empty() } /// Return the cache shard for this [`BuildInfo`]. pub fn cache_shard(&self) -> Option<String> { if self.is_empty() { None } else { Some(cache_digest(self)) } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/pip_index.rs
crates/uv-distribution-types/src/pip_index.rs
//! Compatibility structs for converting between [`IndexUrl`] and [`Index`]. These structs are //! parsed and deserialized as [`IndexUrl`], but are stored as [`Index`] with the appropriate //! flags set. use serde::{Deserialize, Deserializer, Serialize}; #[cfg(feature = "schemars")] use std::borrow::Cow; use std::path::Path; use crate::{Index, IndexUrl}; macro_rules! impl_index { ($name:ident, $from:expr) => { #[derive(Debug, Clone, Eq, PartialEq)] pub struct $name(Index); impl $name { pub fn relative_to(self, root_dir: &Path) -> Result<Self, crate::IndexUrlError> { Ok(Self(self.0.relative_to(root_dir)?)) } } impl From<$name> for Index { fn from(value: $name) -> Self { value.0 } } impl From<Index> for $name { fn from(value: Index) -> Self { Self(value) } } impl Serialize for $name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.url().serialize(serializer) } } impl<'de> Deserialize<'de> for $name { fn deserialize<D>(deserializer: D) -> Result<$name, D::Error> where D: Deserializer<'de>, { IndexUrl::deserialize(deserializer).map($from).map(Self) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for $name { fn schema_name() -> Cow<'static, str> { IndexUrl::schema_name() } fn json_schema( generator: &mut schemars::generate::SchemaGenerator, ) -> schemars::Schema { IndexUrl::json_schema(generator) } } }; } impl_index!(PipIndex, Index::from_index_url); impl_index!(PipExtraIndex, Index::from_extra_index_url); impl_index!(PipFindLinks, Index::from_find_links);
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/config_settings.rs
crates/uv-distribution-types/src/config_settings.rs
use std::{ collections::{BTreeMap, btree_map::Entry}, str::FromStr, }; use uv_cache_key::CacheKeyHasher; use uv_normalize::PackageName; #[derive(Debug, Clone)] pub struct ConfigSettingEntry { /// The key of the setting. For example, given `key=value`, this would be `key`. key: String, /// The value of the setting. For example, given `key=value`, this would be `value`. value: String, } impl FromStr for ConfigSettingEntry { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let Some((key, value)) = s.split_once('=') else { return Err(format!( "Invalid config setting: {s} (expected `KEY=VALUE`)" )); }; Ok(Self { key: key.trim().to_string(), value: value.trim().to_string(), }) } } #[derive(Debug, Clone)] pub struct ConfigSettingPackageEntry { /// The package name to apply the setting to. package: PackageName, /// The config setting entry. setting: ConfigSettingEntry, } impl FromStr for ConfigSettingPackageEntry { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let Some((package_str, config_str)) = s.split_once(':') else { return Err(format!( "Invalid config setting: {s} (expected `PACKAGE:KEY=VALUE`)" )); }; let package = PackageName::from_str(package_str.trim()) .map_err(|e| format!("Invalid package name: {e}"))?; let setting = ConfigSettingEntry::from_str(config_str)?; Ok(Self { package, setting }) } } #[derive(Debug, Clone, Hash, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema), schemars(untagged))] enum ConfigSettingValue { /// The value consists of a single string. String(String), /// The value consists of a list of strings. List(Vec<String>), } impl serde::Serialize for ConfigSettingValue { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { match self { Self::String(value) => serializer.serialize_str(value), Self::List(values) => serializer.collect_seq(values.iter()), } } } impl<'de> serde::Deserialize<'de> for ConfigSettingValue { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = ConfigSettingValue; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a string or list of strings") } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { Ok(ConfigSettingValue::String(value.to_string())) } fn visit_seq<A: serde::de::SeqAccess<'de>>( self, mut seq: A, ) -> Result<Self::Value, A::Error> { let mut values = Vec::new(); while let Some(value) = seq.next_element()? { values.push(value); } Ok(ConfigSettingValue::List(values)) } } deserializer.deserialize_any(Visitor) } } /// Settings to pass to a PEP 517 build backend, structured as a map from (string) key to string or /// list of strings. /// /// See: <https://peps.python.org/pep-0517/#config-settings> #[derive(Debug, Default, Hash, Clone, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct ConfigSettings(BTreeMap<String, ConfigSettingValue>); impl FromIterator<ConfigSettingEntry> for ConfigSettings { fn from_iter<T: IntoIterator<Item = ConfigSettingEntry>>(iter: T) -> Self { let mut config = BTreeMap::default(); for entry in iter { match config.entry(entry.key) { Entry::Vacant(vacant) => { vacant.insert(ConfigSettingValue::String(entry.value)); } Entry::Occupied(mut occupied) => match occupied.get_mut() { ConfigSettingValue::String(existing) => { let existing = existing.clone(); occupied.insert(ConfigSettingValue::List(vec![existing, entry.value])); } ConfigSettingValue::List(existing) => { existing.push(entry.value); } }, } } Self(config) } } impl ConfigSettings { /// Returns the number of settings in the configuration. pub fn len(&self) -> usize { self.0.len() } /// Returns `true` if the configuration contains no settings. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Convert the settings to a string that can be passed directly to a PEP 517 build backend. pub fn escape_for_python(&self) -> String { serde_json::to_string(self).expect("Failed to serialize config settings") } /// Merge two sets of config settings, with the values in `self` taking precedence. #[must_use] pub fn merge(self, other: Self) -> Self { let mut config = self.0; for (key, value) in other.0 { match config.entry(key) { Entry::Vacant(vacant) => { vacant.insert(value); } Entry::Occupied(mut occupied) => match occupied.get_mut() { ConfigSettingValue::String(existing) => { let existing = existing.clone(); match value { ConfigSettingValue::String(value) => { occupied.insert(ConfigSettingValue::List(vec![existing, value])); } ConfigSettingValue::List(mut values) => { values.insert(0, existing); occupied.insert(ConfigSettingValue::List(values)); } } } ConfigSettingValue::List(existing) => match value { ConfigSettingValue::String(value) => { existing.push(value); } ConfigSettingValue::List(values) => { existing.extend(values); } }, }, } } Self(config) } } impl uv_cache_key::CacheKey for ConfigSettings { fn cache_key(&self, state: &mut CacheKeyHasher) { for (key, value) in &self.0 { key.cache_key(state); match value { ConfigSettingValue::String(value) => value.cache_key(state), ConfigSettingValue::List(values) => values.cache_key(state), } } } } impl serde::Serialize for ConfigSettings { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { use serde::ser::SerializeMap; let mut map = serializer.serialize_map(Some(self.0.len()))?; for (key, value) in &self.0 { map.serialize_entry(key, value)?; } map.end() } } impl<'de> serde::Deserialize<'de> for ConfigSettings { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = ConfigSettings; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a map from string to string or list of strings") } fn visit_map<A: serde::de::MapAccess<'de>>( self, mut map: A, ) -> Result<Self::Value, A::Error> { let mut config = BTreeMap::default(); while let Some((key, value)) = map.next_entry()? { config.insert(key, value); } Ok(ConfigSettings(config)) } } deserializer.deserialize_map(Visitor) } } /// Settings to pass to PEP 517 build backends on a per-package basis. #[derive(Debug, Default, Clone, PartialEq, Eq)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub struct PackageConfigSettings(BTreeMap<PackageName, ConfigSettings>); impl FromIterator<ConfigSettingPackageEntry> for PackageConfigSettings { fn from_iter<T: IntoIterator<Item = ConfigSettingPackageEntry>>(iter: T) -> Self { let mut package_configs: BTreeMap<PackageName, Vec<ConfigSettingEntry>> = BTreeMap::new(); for entry in iter { package_configs .entry(entry.package) .or_default() .push(entry.setting); } let configs = package_configs .into_iter() .map(|(package, entries)| (package, entries.into_iter().collect())) .collect(); Self(configs) } } impl PackageConfigSettings { /// Returns the config settings for a specific package, if any. pub fn get(&self, package: &PackageName) -> Option<&ConfigSettings> { self.0.get(package) } /// Returns `true` if there are no package-specific settings. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Merge two sets of package config settings, with the values in `self` taking precedence. #[must_use] pub fn merge(mut self, other: Self) -> Self { for (package, settings) in other.0 { match self.0.entry(package) { Entry::Vacant(vacant) => { vacant.insert(settings); } Entry::Occupied(mut occupied) => { let merged = occupied.get().clone().merge(settings); occupied.insert(merged); } } } self } } impl uv_cache_key::CacheKey for PackageConfigSettings { fn cache_key(&self, state: &mut CacheKeyHasher) { for (package, settings) in &self.0 { package.to_string().cache_key(state); settings.cache_key(state); } } } impl serde::Serialize for PackageConfigSettings { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { use serde::ser::SerializeMap; let mut map = serializer.serialize_map(Some(self.0.len()))?; for (key, value) in &self.0 { map.serialize_entry(&key.to_string(), value)?; } map.end() } } impl<'de> serde::Deserialize<'de> for PackageConfigSettings { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl<'de> serde::de::Visitor<'de> for Visitor { type Value = PackageConfigSettings; fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { formatter.write_str("a map from package name to config settings") } fn visit_map<A: serde::de::MapAccess<'de>>( self, mut map: A, ) -> Result<Self::Value, A::Error> { let mut config = BTreeMap::default(); while let Some((key, value)) = map.next_entry::<String, ConfigSettings>()? { let package = PackageName::from_str(&key).map_err(|e| { serde::de::Error::custom(format!("Invalid package name: {e}")) })?; config.insert(package, value); } Ok(PackageConfigSettings(config)) } } deserializer.deserialize_map(Visitor) } } #[cfg(test)] mod tests { use super::*; #[test] fn collect_config_settings() { let settings: ConfigSettings = vec![ ConfigSettingEntry { key: "key".to_string(), value: "value".to_string(), }, ConfigSettingEntry { key: "key".to_string(), value: "value2".to_string(), }, ConfigSettingEntry { key: "list".to_string(), value: "value3".to_string(), }, ConfigSettingEntry { key: "list".to_string(), value: "value4".to_string(), }, ] .into_iter() .collect(); assert_eq!( settings.0.get("key"), Some(&ConfigSettingValue::List(vec![ "value".to_string(), "value2".to_string() ])) ); assert_eq!( settings.0.get("list"), Some(&ConfigSettingValue::List(vec![ "value3".to_string(), "value4".to_string() ])) ); } #[test] fn escape_for_python() { let mut settings = ConfigSettings::default(); settings.0.insert( "key".to_string(), ConfigSettingValue::String("value".to_string()), ); settings.0.insert( "list".to_string(), ConfigSettingValue::List(vec!["value1".to_string(), "value2".to_string()]), ); assert_eq!( settings.escape_for_python(), r#"{"key":"value","list":["value1","value2"]}"# ); let mut settings = ConfigSettings::default(); settings.0.insert( "key".to_string(), ConfigSettingValue::String("Hello, \"world!\"".to_string()), ); settings.0.insert( "list".to_string(), ConfigSettingValue::List(vec!["'value1'".to_string()]), ); assert_eq!( settings.escape_for_python(), r#"{"key":"Hello, \"world!\"","list":["'value1'"]}"# ); let mut settings = ConfigSettings::default(); settings.0.insert( "key".to_string(), ConfigSettingValue::String("val\\1 {}value".to_string()), ); assert_eq!(settings.escape_for_python(), r#"{"key":"val\\1 {}value"}"#); } #[test] fn parse_config_setting_package_entry() { // Test valid parsing let entry = ConfigSettingPackageEntry::from_str("numpy:editable_mode=compat").unwrap(); assert_eq!(entry.package.as_ref(), "numpy"); assert_eq!(entry.setting.key, "editable_mode"); assert_eq!(entry.setting.value, "compat"); // Test with package name containing hyphens let entry = ConfigSettingPackageEntry::from_str("my-package:some_key=value").unwrap(); assert_eq!(entry.package.as_ref(), "my-package"); assert_eq!(entry.setting.key, "some_key"); assert_eq!(entry.setting.value, "value"); // Test with spaces around values let entry = ConfigSettingPackageEntry::from_str(" numpy : key = value ").unwrap(); assert_eq!(entry.package.as_ref(), "numpy"); assert_eq!(entry.setting.key, "key"); assert_eq!(entry.setting.value, "value"); } #[test] fn collect_config_settings_package() { let settings: PackageConfigSettings = vec![ ConfigSettingPackageEntry::from_str("numpy:editable_mode=compat").unwrap(), ConfigSettingPackageEntry::from_str("numpy:another_key=value").unwrap(), ConfigSettingPackageEntry::from_str("scipy:build_option=fast").unwrap(), ] .into_iter() .collect(); let numpy_settings = settings .get(&PackageName::from_str("numpy").unwrap()) .unwrap(); assert_eq!( numpy_settings.0.get("editable_mode"), Some(&ConfigSettingValue::String("compat".to_string())) ); assert_eq!( numpy_settings.0.get("another_key"), Some(&ConfigSettingValue::String("value".to_string())) ); let scipy_settings = settings .get(&PackageName::from_str("scipy").unwrap()) .unwrap(); assert_eq!( scipy_settings.0.get("build_option"), Some(&ConfigSettingValue::String("fast".to_string())) ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/specified_requirement.rs
crates/uv-distribution-types/src/specified_requirement.rs
use std::borrow::Cow; use std::fmt::{Display, Formatter}; use uv_git_types::{GitLfs, GitReference}; use uv_normalize::ExtraName; use uv_pep508::{MarkerEnvironment, MarkerTree, UnnamedRequirement}; use uv_pypi_types::{Hashes, ParsedUrl}; use crate::{Requirement, RequirementSource, VerbatimParsedUrl}; /// An [`UnresolvedRequirement`] with additional metadata from `requirements.txt`, currently only /// hashes but in the future also editable and similar information. #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct NameRequirementSpecification { /// The actual requirement. pub requirement: Requirement, /// Hashes of the downloadable packages. pub hashes: Vec<String>, } /// An [`UnresolvedRequirement`] with additional metadata from `requirements.txt`, currently only /// hashes but in the future also editable and similar information. #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct UnresolvedRequirementSpecification { /// The actual requirement. pub requirement: UnresolvedRequirement, /// Hashes of the downloadable packages. pub hashes: Vec<String>, } /// A requirement read from a `requirements.txt` or `pyproject.toml` file. /// /// It is considered unresolved as we still need to query the URL for the `Unnamed` variant to /// resolve the requirement name. /// /// Analog to `RequirementsTxtRequirement` but with `distribution_types::Requirement` instead of /// `uv_pep508::Requirement`. #[derive(Hash, Debug, Clone, Eq, PartialEq)] pub enum UnresolvedRequirement { /// The uv-specific superset over PEP 508 requirements specifier incorporating /// `tool.uv.sources`. Named(Requirement), /// A PEP 508-like, direct URL dependency specifier. Unnamed(UnnamedRequirement<VerbatimParsedUrl>), } impl Display for UnresolvedRequirement { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Named(requirement) => write!(f, "{requirement}"), Self::Unnamed(requirement) => write!(f, "{requirement}"), } } } impl UnresolvedRequirement { /// Returns whether the markers apply for the given environment. /// /// When the environment is not given, this treats all marker expressions /// that reference the environment as true. In other words, it does /// environment independent expression evaluation. (Which in turn devolves /// to "only evaluate marker expressions that reference an extra name.") pub fn evaluate_markers(&self, env: Option<&MarkerEnvironment>, extras: &[ExtraName]) -> bool { match self { Self::Named(requirement) => requirement.evaluate_markers(env, extras), Self::Unnamed(requirement) => requirement.evaluate_optional_environment(env, extras), } } /// Augment a user-provided requirement by attaching any specification data that was provided /// separately from the requirement itself (e.g., `--branch main`). #[must_use] pub fn augment_requirement( self, rev: Option<&str>, tag: Option<&str>, branch: Option<&str>, lfs: Option<bool>, marker: Option<MarkerTree>, ) -> Self { #[allow(clippy::manual_map)] let git_reference = if let Some(rev) = rev { Some(GitReference::from_rev(rev.to_string())) } else if let Some(tag) = tag { Some(GitReference::Tag(tag.to_string())) } else if let Some(branch) = branch { Some(GitReference::Branch(branch.to_string())) } else { None }; match self { Self::Named(mut requirement) => Self::Named(Requirement { marker: marker .map(|marker| { requirement.marker.and(marker); requirement.marker }) .unwrap_or(requirement.marker), source: match requirement.source { RequirementSource::Git { git, subdirectory, url, } => { let git = if let Some(git_reference) = git_reference { git.with_reference(git_reference) } else { git }; let git = if let Some(lfs) = lfs { git.with_lfs(GitLfs::from(lfs)) } else { git }; RequirementSource::Git { git, subdirectory, url, } } _ => requirement.source, }, ..requirement }), Self::Unnamed(mut requirement) => Self::Unnamed(UnnamedRequirement { marker: marker .map(|marker| { requirement.marker.and(marker); requirement.marker }) .unwrap_or(requirement.marker), url: match requirement.url.parsed_url { ParsedUrl::Git(mut git) => { if let Some(git_reference) = git_reference { git.url = git.url.with_reference(git_reference); } if let Some(lfs) = lfs { git.url = git.url.with_lfs(GitLfs::from(lfs)); } VerbatimParsedUrl { parsed_url: ParsedUrl::Git(git), verbatim: requirement.url.verbatim, } } _ => requirement.url, }, ..requirement }), } } /// Returns the extras for the requirement. pub fn extras(&self) -> &[ExtraName] { match self { Self::Named(requirement) => &requirement.extras, Self::Unnamed(requirement) => &requirement.extras, } } /// Return the version specifier or URL for the requirement. pub fn source(&self) -> Cow<'_, RequirementSource> { match self { Self::Named(requirement) => Cow::Borrowed(&requirement.source), Self::Unnamed(requirement) => Cow::Owned(RequirementSource::from_parsed_url( requirement.url.parsed_url.clone(), requirement.url.verbatim.clone(), )), } } /// Returns `true` if the requirement is editable. pub fn is_editable(&self) -> bool { match self { Self::Named(requirement) => requirement.is_editable(), Self::Unnamed(requirement) => requirement.url.is_editable(), } } /// Return the hashes of the requirement, as specified in the URL fragment. pub fn hashes(&self) -> Option<Hashes> { match self { Self::Named(requirement) => requirement.hashes(), Self::Unnamed(requirement) => { let fragment = requirement.url.verbatim.fragment()?; Hashes::parse_fragment(fragment).ok() } } } } impl NameRequirementSpecification { /// Return the hashes of the requirement, as specified in the URL fragment. pub fn hashes(&self) -> Option<Hashes> { let RequirementSource::Url { ref url, .. } = self.requirement.source else { return None; }; let fragment = url.fragment()?; Hashes::parse_fragment(fragment).ok() } } impl From<Requirement> for UnresolvedRequirementSpecification { fn from(requirement: Requirement) -> Self { Self { requirement: UnresolvedRequirement::Named(requirement), hashes: Vec::new(), } } } impl From<Requirement> for NameRequirementSpecification { fn from(requirement: Requirement) -> Self { Self { requirement, hashes: Vec::new(), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/resolution.rs
crates/uv-distribution-types/src/resolution.rs
use uv_distribution_filename::DistExtension; use uv_normalize::{ExtraName, GroupName, PackageName}; use uv_pypi_types::{HashDigest, HashDigests}; use crate::{ BuiltDist, Diagnostic, Dist, IndexMetadata, Name, RequirementSource, ResolvedDist, SourceDist, }; /// A set of packages pinned at specific versions. /// /// This is similar to [`ResolverOutput`], but represents a resolution for a subset of all /// marker environments. For example, the resolution is guaranteed to contain at most one version /// for a given package. #[derive(Debug, Default, Clone)] pub struct Resolution { graph: petgraph::graph::DiGraph<Node, Edge>, diagnostics: Vec<ResolutionDiagnostic>, } impl Resolution { /// Create a [`Resolution`] from the given pinned packages. pub fn new(graph: petgraph::graph::DiGraph<Node, Edge>) -> Self { Self { graph, diagnostics: Vec::new(), } } /// Return the underlying graph of the resolution. pub fn graph(&self) -> &petgraph::graph::DiGraph<Node, Edge> { &self.graph } /// Add [`Diagnostics`] to the resolution. #[must_use] pub fn with_diagnostics(mut self, diagnostics: Vec<ResolutionDiagnostic>) -> Self { self.diagnostics.extend(diagnostics); self } /// Return the hashes for the given package name, if they exist. pub fn hashes(&self) -> impl Iterator<Item = (&ResolvedDist, &[HashDigest])> { self.graph .node_indices() .filter_map(move |node| match &self.graph[node] { Node::Dist { dist, hashes, install, .. } if *install => Some((dist, hashes.as_slice())), _ => None, }) } /// Iterate over the [`ResolvedDist`] entities in this resolution. pub fn distributions(&self) -> impl Iterator<Item = &ResolvedDist> { self.graph .raw_nodes() .iter() .filter_map(|node| match &node.weight { Node::Dist { dist, install, .. } if *install => Some(dist), _ => None, }) } /// Return the number of distributions in this resolution. pub fn len(&self) -> usize { self.distributions().count() } /// Return `true` if there are no pinned packages in this resolution. pub fn is_empty(&self) -> bool { self.distributions().next().is_none() } /// Return the [`ResolutionDiagnostic`]s that were produced during resolution. pub fn diagnostics(&self) -> &[ResolutionDiagnostic] { &self.diagnostics } /// Filter the resolution to only include packages that match the given predicate. #[must_use] pub fn filter(mut self, predicate: impl Fn(&ResolvedDist) -> bool) -> Self { for node in self.graph.node_weights_mut() { if let Node::Dist { dist, install, .. } = node { if !predicate(dist) { *install = false; } } } self } /// Map over the resolved distributions in this resolution. /// /// For efficiency, the map function should return `None` if the resolved distribution is /// unchanged. #[must_use] pub fn map(mut self, predicate: impl Fn(&ResolvedDist) -> Option<ResolvedDist>) -> Self { for node in self.graph.node_weights_mut() { if let Node::Dist { dist, .. } = node { if let Some(transformed) = predicate(dist) { *dist = transformed; } } } self } } #[derive(Debug, Clone, Hash)] pub enum ResolutionDiagnostic { MissingExtra { /// The distribution that was requested with a non-existent extra. For example, /// `black==23.10.0`. dist: ResolvedDist, /// The extra that was requested. For example, `colorama` in `black[colorama]`. extra: ExtraName, }, MissingGroup { /// The distribution that was requested with a non-existent development dependency group. dist: ResolvedDist, /// The development dependency group that was requested. group: GroupName, }, YankedVersion { /// The package that was requested with a yanked version. For example, `black==23.10.0`. dist: ResolvedDist, /// The reason that the version was yanked, if any. reason: Option<String>, }, MissingLowerBound { /// The name of the package that had no lower bound from any other package in the /// resolution. For example, `black`. package_name: PackageName, }, } impl Diagnostic for ResolutionDiagnostic { /// Convert the diagnostic into a user-facing message. fn message(&self) -> String { match self { Self::MissingExtra { dist, extra } => { format!("The package `{dist}` does not have an extra named `{extra}`") } Self::MissingGroup { dist, group } => { format!( "The package `{dist}` does not have a development dependency group named `{group}`" ) } Self::YankedVersion { dist, reason } => { if let Some(reason) = reason { format!("`{dist}` is yanked (reason: \"{reason}\")") } else { format!("`{dist}` is yanked") } } Self::MissingLowerBound { package_name: name } => { format!( "The transitive dependency `{name}` is unpinned. \ Consider setting a lower bound with a constraint when using \ `--resolution lowest` to avoid using outdated versions." ) } } } /// Returns `true` if the [`PackageName`] is involved in this diagnostic. fn includes(&self, name: &PackageName) -> bool { match self { Self::MissingExtra { dist, .. } => name == dist.name(), Self::MissingGroup { dist, .. } => name == dist.name(), Self::YankedVersion { dist, .. } => name == dist.name(), Self::MissingLowerBound { package_name } => name == package_name, } } } /// A node in the resolution, along with whether its been filtered out. /// /// We retain filtered nodes as we still need to be able to trace dependencies through the graph /// (e.g., to determine why a package was included in the resolution). #[derive(Debug, Clone)] pub enum Node { Root, Dist { dist: ResolvedDist, hashes: HashDigests, install: bool, }, } impl Node { /// Returns `true` if the node should be installed. pub fn install(&self) -> bool { match self { Self::Root => false, Self::Dist { install, .. } => *install, } } } /// An edge in the resolution graph. #[derive(Debug, Clone)] pub enum Edge { Prod, Optional(ExtraName), Dev(GroupName), } impl From<&ResolvedDist> for RequirementSource { fn from(resolved_dist: &ResolvedDist) -> Self { match resolved_dist { ResolvedDist::Installable { dist, .. } => match dist.as_ref() { Dist::Built(BuiltDist::Registry(wheels)) => { let wheel = wheels.best_wheel(); Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version( wheel.filename.version.clone(), ), ), index: Some(IndexMetadata::from(wheel.index.clone())), conflict: None, } } Dist::Built(BuiltDist::DirectUrl(wheel)) => { let mut location = wheel.url.to_url(); location.set_fragment(None); Self::Url { url: wheel.url.clone(), location, subdirectory: None, ext: DistExtension::Wheel, } } Dist::Built(BuiltDist::Path(wheel)) => Self::Path { install_path: wheel.install_path.clone(), url: wheel.url.clone(), ext: DistExtension::Wheel, }, Dist::Source(SourceDist::Registry(sdist)) => Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version(sdist.version.clone()), ), index: Some(IndexMetadata::from(sdist.index.clone())), conflict: None, }, Dist::Source(SourceDist::DirectUrl(sdist)) => { let mut location = sdist.url.to_url(); location.set_fragment(None); Self::Url { url: sdist.url.clone(), location, subdirectory: sdist.subdirectory.clone(), ext: DistExtension::Source(sdist.ext), } } Dist::Source(SourceDist::Git(sdist)) => Self::Git { git: (*sdist.git).clone(), url: sdist.url.clone(), subdirectory: sdist.subdirectory.clone(), }, Dist::Source(SourceDist::Path(sdist)) => Self::Path { install_path: sdist.install_path.clone(), url: sdist.url.clone(), ext: DistExtension::Source(sdist.ext), }, Dist::Source(SourceDist::Directory(sdist)) => Self::Directory { install_path: sdist.install_path.clone(), url: sdist.url.clone(), editable: sdist.editable, r#virtual: sdist.r#virtual, }, }, ResolvedDist::Installed { dist } => Self::Registry { specifier: uv_pep440::VersionSpecifiers::from( uv_pep440::VersionSpecifier::equals_version(dist.version().clone()), ), index: None, conflict: None, }, } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/requested.rs
crates/uv-distribution-types/src/requested.rs
use std::fmt::{Display, Formatter}; use crate::{ Dist, DistributionId, DistributionMetadata, Identifier, InstalledDist, Name, ResourceId, VersionOrUrlRef, }; use uv_normalize::PackageName; use uv_pep440::Version; /// A distribution that can be requested during resolution. /// /// Either an already-installed distribution or a distribution that can be installed. #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] pub enum RequestedDist { Installed(InstalledDist), Installable(Dist), } impl RequestedDist { /// Returns the version of the distribution, if it is known. pub fn version(&self) -> Option<&Version> { match self { Self::Installed(dist) => Some(dist.version()), Self::Installable(dist) => dist.version(), } } } impl Name for RequestedDist { fn name(&self) -> &PackageName { match self { Self::Installable(dist) => dist.name(), Self::Installed(dist) => dist.name(), } } } impl DistributionMetadata for RequestedDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Installed(dist) => dist.version_or_url(), Self::Installable(dist) => dist.version_or_url(), } } } impl Identifier for RequestedDist { fn distribution_id(&self) -> DistributionId { match self { Self::Installed(dist) => dist.distribution_id(), Self::Installable(dist) => dist.distribution_id(), } } fn resource_id(&self) -> ResourceId { match self { Self::Installed(dist) => dist.resource_id(), Self::Installable(dist) => dist.resource_id(), } } } impl Display for RequestedDist { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Installed(dist) => dist.fmt(f), Self::Installable(dist) => dist.fmt(f), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/annotation.rs
crates/uv-distribution-types/src/annotation.rs
use std::collections::{BTreeMap, BTreeSet}; use uv_fs::Simplified; use uv_normalize::PackageName; use uv_pep508::RequirementOrigin; /// Source of a dependency, e.g., a `-r requirements.txt` file. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum SourceAnnotation { /// A `-c constraints.txt` file. Constraint(RequirementOrigin), /// An `--override overrides.txt` file. Override(RequirementOrigin), /// A `-r requirements.txt` file. Requirement(RequirementOrigin), } impl std::fmt::Display for SourceAnnotation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Requirement(origin) => match origin { RequirementOrigin::File(path) => { write!(f, "-r {}", path.portable_display()) } RequirementOrigin::Project(path, project_name) => { write!(f, "{project_name} ({})", path.portable_display()) } RequirementOrigin::Group(path, project_name, group) => { if let Some(project_name) = project_name { write!(f, "{project_name} ({}:{group})", path.portable_display()) } else { write!(f, "({}:{group})", path.portable_display()) } } RequirementOrigin::Workspace => { write!(f, "(workspace)") } }, Self::Constraint(origin) => { write!(f, "-c {}", origin.path().portable_display()) } Self::Override(origin) => match origin { RequirementOrigin::File(path) => { write!(f, "--override {}", path.portable_display()) } RequirementOrigin::Project(path, project_name) => { // Project is not used for override write!(f, "--override {project_name} ({})", path.portable_display()) } RequirementOrigin::Group(path, project_name, group) => { // Group is not used for override if let Some(project_name) = project_name { write!( f, "--override {project_name} ({}:{group})", path.portable_display() ) } else { write!(f, "--override ({}:{group})", path.portable_display()) } } RequirementOrigin::Workspace => { write!(f, "--override (workspace)") } }, } } } /// A collection of source annotations. #[derive(Default, Debug, Clone)] pub struct SourceAnnotations(BTreeMap<PackageName, BTreeSet<SourceAnnotation>>); impl SourceAnnotations { /// Add a source annotation to the collection for the given package. pub fn add(&mut self, package: &PackageName, annotation: SourceAnnotation) { self.0 .entry(package.clone()) .or_default() .insert(annotation); } /// Return the source annotations for a given package. pub fn get(&self, package: &PackageName) -> Option<&BTreeSet<SourceAnnotation>> { self.0.get(package) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/error.rs
crates/uv-distribution-types/src/error.rs
use uv_normalize::PackageName; use uv_redacted::DisplaySafeUrl; #[derive(thiserror::Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), #[error(transparent)] WheelFilename(#[from] uv_distribution_filename::WheelFilenameError), #[error("Could not extract path segments from URL: {0}")] MissingPathSegments(String), #[error("Distribution not found at: {0}")] NotFound(DisplaySafeUrl), #[error("Requested package name `{0}` does not match `{1}` in the distribution filename: {2}")] PackageNameMismatch(PackageName, PackageName, String), }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/file.rs
crates/uv-distribution-types/src/file.rs
use std::borrow::Cow; use std::fmt::{self, Display, Formatter}; use std::str::FromStr; use jiff::Timestamp; use serde::{Deserialize, Serialize}; use uv_pep440::{VersionSpecifiers, VersionSpecifiersParseError}; use uv_pep508::split_scheme; use uv_pypi_types::{CoreMetadata, HashDigests, Yanked}; use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError}; use uv_small_str::SmallString; /// Error converting [`uv_pypi_types::PypiFile`] to [`distribution_type::File`]. #[derive(Debug, thiserror::Error)] pub enum FileConversionError { #[error("Failed to parse `requires-python`: `{0}`")] RequiresPython(String, #[source] VersionSpecifiersParseError), #[error("Failed to parse URL: {0}")] Url(String, #[source] url::ParseError), #[error("Failed to parse filename from URL: {0}")] MissingPathSegments(String), #[error(transparent)] Utf8(#[from] std::str::Utf8Error), } /// Internal analog to [`uv_pypi_types::PypiFile`]. #[derive(Debug, Clone, PartialEq, Eq, Hash, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)] #[rkyv(derive(Debug))] pub struct File { pub dist_info_metadata: bool, pub filename: SmallString, pub hashes: HashDigests, pub requires_python: Option<VersionSpecifiers>, pub size: Option<u64>, // N.B. We don't use a Jiff timestamp here because it's a little // annoying to do so with rkyv. Since we only use this field for doing // comparisons in testing, we just store it as a UTC timestamp in // milliseconds. pub upload_time_utc_ms: Option<i64>, pub url: FileLocation, pub yanked: Option<Box<Yanked>>, pub zstd: Option<Box<Zstd>>, } impl File { /// `TryFrom` instead of `From` to filter out files with invalid requires python version specifiers pub fn try_from_pypi( file: uv_pypi_types::PypiFile, base: &SmallString, ) -> Result<Self, FileConversionError> { Ok(Self { dist_info_metadata: file .core_metadata .as_ref() .is_some_and(CoreMetadata::is_available), filename: file.filename, hashes: HashDigests::from(file.hashes), requires_python: file .requires_python .transpose() .map_err(|err| FileConversionError::RequiresPython(err.line().clone(), err))?, size: file.size, upload_time_utc_ms: file.upload_time.map(Timestamp::as_millisecond), url: FileLocation::new(file.url, base), yanked: file.yanked, zstd: None, }) } pub fn try_from_pyx( file: uv_pypi_types::PyxFile, base: &SmallString, ) -> Result<Self, FileConversionError> { let filename = if let Some(filename) = file.filename { filename } else { // Remove any query parameters or fragments from the URL to get the filename. let base_url = file .url .as_ref() .split_once('?') .or_else(|| file.url.as_ref().split_once('#')) .map(|(path, _)| path) .unwrap_or(file.url.as_ref()); // Take the last segment, stripping any query or fragment. let last = base_url .split('/') .next_back() .ok_or_else(|| FileConversionError::MissingPathSegments(file.url.to_string()))?; // Decode the filename, which may be percent-encoded. let filename = percent_encoding::percent_decode_str(last).decode_utf8()?; SmallString::from(filename) }; Ok(Self { filename, dist_info_metadata: file .core_metadata .as_ref() .is_some_and(CoreMetadata::is_available), hashes: HashDigests::from(file.hashes), requires_python: file .requires_python .transpose() .map_err(|err| FileConversionError::RequiresPython(err.line().clone(), err))?, size: file.size, upload_time_utc_ms: file.upload_time.map(Timestamp::as_millisecond), url: FileLocation::new(file.url, base), yanked: file.yanked, zstd: file .zstd .map(|zstd| Zstd { hashes: HashDigests::from(zstd.hashes), size: zstd.size, }) .map(Box::new), }) } } /// While a registry file is generally a remote URL, it can also be a file if it comes from a directory flat indexes. #[derive(Debug, Clone, PartialEq, Eq, Hash, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)] #[rkyv(derive(Debug))] pub enum FileLocation { /// URL relative to the base URL. RelativeUrl(SmallString, SmallString), /// Absolute URL. AbsoluteUrl(UrlString), } impl FileLocation { /// Parse a relative or absolute URL on a page with a base URL. /// /// This follows the HTML semantics where a link on a page is resolved relative to the URL of /// that page. pub fn new(url: SmallString, base: &SmallString) -> Self { match split_scheme(&url) { Some(..) => Self::AbsoluteUrl(UrlString::new(url)), None => Self::RelativeUrl(base.clone(), url), } } /// Convert this location to a URL. /// /// A relative URL has its base joined to the path. An absolute URL is /// parsed as-is. And a path location is turned into a URL via the `file` /// protocol. /// /// # Errors /// /// This returns an error if any of the URL parsing fails, or if, for /// example, the location is a path and the path isn't valid UTF-8. /// (Because URLs must be valid UTF-8.) pub fn to_url(&self) -> Result<DisplaySafeUrl, ToUrlError> { match self { Self::RelativeUrl(base, path) => { let base_url = DisplaySafeUrl::parse(base).map_err(|err| ToUrlError::InvalidBase { base: base.to_string(), err, })?; let joined = base_url.join(path).map_err(|err| ToUrlError::InvalidJoin { base: base.to_string(), path: path.to_string(), err, })?; Ok(joined) } Self::AbsoluteUrl(absolute) => absolute.to_url(), } } } impl Display for FileLocation { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::RelativeUrl(_base, url) => Display::fmt(&url, f), Self::AbsoluteUrl(url) => Display::fmt(&url.0, f), } } } /// A [`Url`] represented as a `String`. /// /// This type is not guaranteed to be a valid URL, and may error on conversion. #[derive( Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize, )] #[serde(transparent)] #[rkyv(derive(Debug))] pub struct UrlString(SmallString); impl UrlString { /// Create a new [`UrlString`] from a [`String`]. pub fn new(url: SmallString) -> Self { Self(url) } /// Converts a [`UrlString`] to a [`DisplaySafeUrl`]. pub fn to_url(&self) -> Result<DisplaySafeUrl, ToUrlError> { DisplaySafeUrl::from_str(&self.0).map_err(|err| ToUrlError::InvalidAbsolute { absolute: self.0.to_string(), err, }) } /// Return the [`UrlString`] with any query parameters and fragments removed. pub fn base_str(&self) -> &str { self.as_ref() .split_once('?') .or_else(|| self.as_ref().split_once('#')) .map(|(path, _)| path) .unwrap_or(self.as_ref()) } /// Return the [`UrlString`] (as a [`Cow`]) with any fragments removed. #[must_use] pub fn without_fragment(&self) -> Cow<'_, Self> { self.as_ref() .split_once('#') .map(|(path, _)| Cow::Owned(Self(SmallString::from(path)))) .unwrap_or(Cow::Borrowed(self)) } } impl AsRef<str> for UrlString { fn as_ref(&self) -> &str { &self.0 } } impl From<DisplaySafeUrl> for UrlString { fn from(value: DisplaySafeUrl) -> Self { Self(value.as_str().into()) } } impl From<&DisplaySafeUrl> for UrlString { fn from(value: &DisplaySafeUrl) -> Self { Self(value.as_str().into()) } } impl Display for UrlString { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } /// An error that occurs when a [`FileLocation`] is not a valid URL. #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)] pub enum ToUrlError { /// An error that occurs when the base URL in [`FileLocation::Relative`] /// could not be parsed as a valid URL. #[error("Could not parse base URL `{base}` as a valid URL")] InvalidBase { /// The base URL that could not be parsed as a valid URL. base: String, /// The underlying URL parse error. #[source] err: DisplaySafeUrlError, }, /// An error that occurs when the base URL could not be joined with /// the relative path in a [`FileLocation::Relative`]. #[error("Could not join base URL `{base}` to relative path `{path}`")] InvalidJoin { /// The base URL that could not be parsed as a valid URL. base: String, /// The relative path segment. path: String, /// The underlying URL parse error. #[source] err: DisplaySafeUrlError, }, /// An error that occurs when the absolute URL in [`FileLocation::Absolute`] /// could not be parsed as a valid URL. #[error("Could not parse absolute URL `{absolute}` as a valid URL")] InvalidAbsolute { /// The absolute URL that could not be parsed as a valid URL. absolute: String, /// The underlying URL parse error. #[source] err: DisplaySafeUrlError, }, } #[derive(Debug, Clone, PartialEq, Eq, Hash, rkyv::Archive, rkyv::Deserialize, rkyv::Serialize)] pub struct Zstd { pub hashes: HashDigests, pub size: Option<u64>, } #[cfg(test)] mod tests { use super::*; #[test] fn base_str() { let url = UrlString("https://example.com/path?query#fragment".into()); assert_eq!(url.base_str(), "https://example.com/path"); let url = UrlString("https://example.com/path#fragment".into()); assert_eq!(url.base_str(), "https://example.com/path"); let url = UrlString("https://example.com/path".into()); assert_eq!(url.base_str(), "https://example.com/path"); } #[test] fn without_fragment() { // Borrows a URL without a fragment let url = UrlString("https://example.com/path".into()); assert_eq!(&*url.without_fragment(), &url); assert!(matches!(url.without_fragment(), Cow::Borrowed(_))); // Removes the fragment if present on the URL let url = UrlString("https://example.com/path?query#fragment".into()); assert_eq!( &*url.without_fragment(), &UrlString("https://example.com/path?query".into()) ); assert!(matches!(url.without_fragment(), Cow::Owned(_))); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/known_platform.rs
crates/uv-distribution-types/src/known_platform.rs
use std::fmt::{Display, Formatter}; use uv_pep508::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValueString}; /// A platform for which the resolver is solving. #[derive(Debug, Clone, Copy)] pub enum KnownPlatform { Linux, Windows, MacOS, } impl KnownPlatform { /// Return the platform's `sys.platform` value. pub fn sys_platform(self) -> &'static str { match self { Self::Linux => "linux", Self::Windows => "win32", Self::MacOS => "darwin", } } /// Return a [`MarkerTree`] for the platform. pub fn marker(self) -> MarkerTree { MarkerTree::expression(MarkerExpression::String { key: MarkerValueString::SysPlatform, operator: MarkerOperator::Equal, value: match self { Self::Linux => arcstr::literal!("linux"), Self::Windows => arcstr::literal!("win32"), Self::MacOS => arcstr::literal!("darwin"), }, }) } /// Determine the [`KnownPlatform`] from a marker tree. pub fn from_marker(marker: MarkerTree) -> Option<Self> { if marker == Self::Linux.marker() { Some(Self::Linux) } else if marker == Self::Windows.marker() { Some(Self::Windows) } else if marker == Self::MacOS.marker() { Some(Self::MacOS) } else { None } } } impl Display for KnownPlatform { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Linux => write!(f, "Linux"), Self::Windows => write!(f, "Windows"), Self::MacOS => write!(f, "macOS"), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/index_url.rs
crates/uv-distribution-types/src/index_url.rs
use std::borrow::Cow; use std::fmt::{Display, Formatter}; use std::ops::Deref; use std::path::Path; use std::str::FromStr; use std::sync::{Arc, LazyLock, RwLock}; use itertools::Either; use rustc_hash::{FxHashMap, FxHashSet}; use thiserror::Error; use url::{ParseError, Url}; use uv_auth::RealmRef; use uv_cache_key::CanonicalUrl; use uv_pep508::{Scheme, VerbatimUrl, VerbatimUrlError, split_scheme}; use uv_redacted::DisplaySafeUrl; use uv_warnings::warn_user; use crate::{Index, IndexStatusCodeStrategy, Verbatim}; static PYPI_URL: LazyLock<DisplaySafeUrl> = LazyLock::new(|| DisplaySafeUrl::parse("https://pypi.org/simple").unwrap()); static DEFAULT_INDEX: LazyLock<Index> = LazyLock::new(|| { Index::from_index_url(IndexUrl::Pypi(Arc::new(VerbatimUrl::from_url( PYPI_URL.clone(), )))) }); /// The URL of an index to use for fetching packages (e.g., PyPI). #[derive(Debug, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] pub enum IndexUrl { Pypi(Arc<VerbatimUrl>), Url(Arc<VerbatimUrl>), Path(Arc<VerbatimUrl>), } impl IndexUrl { /// Parse an [`IndexUrl`] from a string, relative to an optional root directory. /// /// If no root directory is provided, relative paths are resolved against the current working /// directory. pub fn parse(path: &str, root_dir: Option<&Path>) -> Result<Self, IndexUrlError> { let url = VerbatimUrl::from_url_or_path(path, root_dir)?; Ok(Self::from(url)) } /// Return the root [`Url`] of the index, if applicable. /// /// For indexes with a `/simple` endpoint, this is simply the URL with the final segment /// removed. This is useful, e.g., for credential propagation to other endpoints on the index. pub fn root(&self) -> Option<DisplaySafeUrl> { let mut segments = self.url().path_segments()?; let last = match segments.next_back()? { // If the last segment is empty due to a trailing `/`, skip it (as in `pop_if_empty`) "" => segments.next_back()?, segment => segment, }; // We also handle `/+simple` as it's used in devpi if !(last.eq_ignore_ascii_case("simple") || last.eq_ignore_ascii_case("+simple")) { return None; } let mut url = self.url().clone(); url.path_segments_mut().ok()?.pop_if_empty().pop(); Some(url) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for IndexUrl { fn schema_name() -> Cow<'static, str> { Cow::Borrowed("IndexUrl") } fn json_schema(_generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({ "type": "string", "description": "The URL of an index to use for fetching packages (e.g., `https://pypi.org/simple`), or a local path." }) } } impl IndexUrl { #[inline] fn inner(&self) -> &VerbatimUrl { match self { Self::Pypi(url) | Self::Url(url) | Self::Path(url) => url, } } /// Return the raw URL for the index. pub fn url(&self) -> &DisplaySafeUrl { self.inner().raw() } /// Convert the index URL into a [`DisplaySafeUrl`]. pub fn into_url(self) -> DisplaySafeUrl { self.inner().to_url() } /// Return the redacted URL for the index, omitting any sensitive credentials. pub fn without_credentials(&self) -> Cow<'_, DisplaySafeUrl> { let url = self.url(); if url.username().is_empty() && url.password().is_none() { Cow::Borrowed(url) } else { let mut url = url.clone(); let _ = url.set_username(""); let _ = url.set_password(None); Cow::Owned(url) } } /// Warn user if the given URL was provided as an ambiguous relative path. /// /// This is a temporary warning. Ambiguous values will not be /// accepted in the future. pub fn warn_on_disambiguated_relative_path(&self) { let Self::Path(verbatim_url) = &self else { return; }; if let Some(path) = verbatim_url.given() { if !is_disambiguated_path(path) { if cfg!(windows) { warn_user!( "Relative paths passed to `--index` or `--default-index` should be disambiguated from index names (use `.\\{path}` or `./{path}`). Support for ambiguous values will be removed in the future" ); } else { warn_user!( "Relative paths passed to `--index` or `--default-index` should be disambiguated from index names (use `./{path}`). Support for ambiguous values will be removed in the future" ); } } } } } impl Display for IndexUrl { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(self.inner(), f) } } impl Verbatim for IndexUrl { fn verbatim(&self) -> Cow<'_, str> { self.inner().verbatim() } } /// Checks if a path is disambiguated. /// /// Disambiguated paths are absolute paths, paths with valid schemes, /// and paths starting with "./" or "../" on Unix or ".\\", "..\\", /// "./", or "../" on Windows. fn is_disambiguated_path(path: &str) -> bool { if cfg!(windows) { if path.starts_with(".\\") || path.starts_with("..\\") || path.starts_with('/') { return true; } } if path.starts_with("./") || path.starts_with("../") || Path::new(path).is_absolute() { return true; } // Check if the path has a scheme (like `file://`) if let Some((scheme, _)) = split_scheme(path) { return Scheme::parse(scheme).is_some(); } // This is an ambiguous relative path false } /// An error that can occur when parsing an [`IndexUrl`]. #[derive(Error, Debug)] pub enum IndexUrlError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Url(#[from] ParseError), #[error(transparent)] VerbatimUrl(#[from] VerbatimUrlError), } impl FromStr for IndexUrl { type Err = IndexUrlError; fn from_str(s: &str) -> Result<Self, Self::Err> { Self::parse(s, None) } } impl serde::ser::Serialize for IndexUrl { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { self.inner().without_credentials().serialize(serializer) } } impl<'de> serde::de::Deserialize<'de> for IndexUrl { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::de::Deserializer<'de>, { struct Visitor; impl serde::de::Visitor<'_> for Visitor { type Value = IndexUrl; fn expecting(&self, f: &mut Formatter) -> std::fmt::Result { f.write_str("a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { IndexUrl::from_str(v).map_err(serde::de::Error::custom) } } deserializer.deserialize_str(Visitor) } } impl From<VerbatimUrl> for IndexUrl { fn from(url: VerbatimUrl) -> Self { if url.scheme() == "file" { Self::Path(Arc::new(url)) } else if *url.raw() == *PYPI_URL { Self::Pypi(Arc::new(url)) } else { Self::Url(Arc::new(url)) } } } impl From<IndexUrl> for DisplaySafeUrl { fn from(index: IndexUrl) -> Self { index.inner().to_url() } } impl Deref for IndexUrl { type Target = Url; fn deref(&self) -> &Self::Target { self.inner() } } /// The index locations to use for fetching packages. By default, uses the PyPI index. /// /// This type merges the legacy `--index-url`, `--extra-index-url`, and `--find-links` options, /// along with the uv-specific `--index` and `--default-index`. #[derive(Default, Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub struct IndexLocations { indexes: Vec<Index>, flat_index: Vec<Index>, no_index: bool, } impl IndexLocations { /// Determine the index URLs to use for fetching packages. pub fn new(indexes: Vec<Index>, flat_index: Vec<Index>, no_index: bool) -> Self { Self { indexes, flat_index, no_index, } } /// Combine a set of index locations. /// /// If either the current or the other index locations have `no_index` set, the result will /// have `no_index` set. /// /// If the current index location has an `index` set, it will be preserved. #[must_use] pub fn combine(self, indexes: Vec<Index>, flat_index: Vec<Index>, no_index: bool) -> Self { Self { indexes: self.indexes.into_iter().chain(indexes).collect(), flat_index: self.flat_index.into_iter().chain(flat_index).collect(), no_index: self.no_index || no_index, } } /// Returns `true` if no index configuration is set, i.e., the [`IndexLocations`] matches the /// default configuration. pub fn is_none(&self) -> bool { *self == Self::default() } } /// Returns `true` if two [`IndexUrl`]s refer to the same index. fn is_same_index(a: &IndexUrl, b: &IndexUrl) -> bool { RealmRef::from(&**b.url()) == RealmRef::from(&**a.url()) && CanonicalUrl::new(a.url()) == CanonicalUrl::new(b.url()) } impl<'a> IndexLocations { /// Return the default [`Index`] entry. /// /// If `--no-index` is set, return `None`. /// /// If no index is provided, use the `PyPI` index. pub fn default_index(&'a self) -> Option<&'a Index> { if self.no_index { None } else { let mut seen = FxHashSet::default(); self.indexes .iter() .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))) .find(|index| index.default) .or_else(|| Some(&DEFAULT_INDEX)) } } /// Return an iterator over the implicit [`Index`] entries. /// /// Default and explicit indexes are excluded. pub fn implicit_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { if self.no_index { Either::Left(std::iter::empty()) } else { let mut seen = FxHashSet::default(); Either::Right( self.indexes .iter() .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))) .filter(|index| !index.default && !index.explicit), ) } } /// Return an iterator over all [`Index`] entries in order. /// /// Explicit indexes are excluded. /// /// Prioritizes the extra indexes over the default index. /// /// If `no_index` was enabled, then this always returns an empty /// iterator. pub fn indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { self.implicit_indexes() .chain(self.default_index()) .filter(|index| !index.explicit) } /// Return an iterator over all simple [`Index`] entries in order. /// /// If `no_index` was enabled, then this always returns an empty iterator. pub fn simple_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { if self.no_index { Either::Left(std::iter::empty()) } else { let mut seen = FxHashSet::default(); Either::Right( self.indexes .iter() .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))), ) } } /// Return an iterator over the [`FlatIndexLocation`] entries. pub fn flat_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { self.flat_index.iter() } /// Return the `--no-index` flag. pub fn no_index(&self) -> bool { self.no_index } /// Clone the index locations into a [`IndexUrls`] instance. pub fn index_urls(&'a self) -> IndexUrls { IndexUrls { indexes: self.indexes.clone(), no_index: self.no_index, } } /// Return a vector containing all allowed [`Index`] entries. /// /// This includes explicit indexes, implicit indexes, flat indexes, and the default index. /// /// The indexes will be returned in the reverse of the order in which they were defined, such /// that the last-defined index is the first item in the vector. pub fn allowed_indexes(&'a self) -> Vec<&'a Index> { if self.no_index { self.flat_index.iter().rev().collect() } else { let mut indexes = vec![]; let mut seen = FxHashSet::default(); let mut default = false; for index in { self.indexes .iter() .chain(self.flat_index.iter()) .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))) } { if index.default { if default { continue; } default = true; } indexes.push(index); } if !default { indexes.push(&*DEFAULT_INDEX); } indexes.reverse(); indexes } } /// Return a vector containing all known [`Index`] entries. /// /// This includes explicit indexes, implicit indexes, flat indexes, and default indexes; /// in short, it includes all defined indexes, even if they're overridden by some other index /// definition. /// /// The indexes will be returned in the reverse of the order in which they were defined, such /// that the last-defined index is the first item in the vector. pub fn known_indexes(&'a self) -> impl Iterator<Item = &'a Index> { if self.no_index { Either::Left(self.flat_index.iter().rev()) } else { Either::Right( std::iter::once(&*DEFAULT_INDEX) .chain(self.flat_index.iter().rev()) .chain(self.indexes.iter().rev()), ) } } /// Return the Simple API cache control header for an [`IndexUrl`], if configured. pub fn simple_api_cache_control_for(&self, url: &IndexUrl) -> Option<&str> { for index in &self.indexes { if is_same_index(index.url(), url) { return index.simple_api_cache_control(); } } None } /// Return the artifact cache control header for an [`IndexUrl`], if configured. pub fn artifact_cache_control_for(&self, url: &IndexUrl) -> Option<&str> { for index in &self.indexes { if is_same_index(index.url(), url) { return index.artifact_cache_control(); } } None } } impl From<&IndexLocations> for uv_auth::Indexes { fn from(index_locations: &IndexLocations) -> Self { Self::from_indexes(index_locations.allowed_indexes().into_iter().map(|index| { let mut url = index.url().url().clone(); url.set_username("").ok(); url.set_password(None).ok(); let mut root_url = index.url().root().unwrap_or_else(|| url.clone()); root_url.set_username("").ok(); root_url.set_password(None).ok(); uv_auth::Index { url, root_url, auth_policy: index.authenticate, } })) } } /// The index URLs to use for fetching packages. /// /// This type merges the legacy `--index-url` and `--extra-index-url` options, along with the /// uv-specific `--index` and `--default-index`. #[derive(Default, Debug, Clone, PartialEq, Eq)] pub struct IndexUrls { indexes: Vec<Index>, no_index: bool, } impl<'a> IndexUrls { pub fn from_indexes(indexes: Vec<Index>) -> Self { Self { indexes, no_index: false, } } /// Return the default [`Index`] entry. /// /// If `--no-index` is set, return `None`. /// /// If no index is provided, use the `PyPI` index. fn default_index(&'a self) -> Option<&'a Index> { if self.no_index { None } else { let mut seen = FxHashSet::default(); self.indexes .iter() .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))) .find(|index| index.default) .or_else(|| Some(&DEFAULT_INDEX)) } } /// Return an iterator over the implicit [`Index`] entries. /// /// Default and explicit indexes are excluded. fn implicit_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { if self.no_index { Either::Left(std::iter::empty()) } else { let mut seen = FxHashSet::default(); Either::Right( self.indexes .iter() .filter(move |index| index.name.as_ref().is_none_or(|name| seen.insert(name))) .filter(|index| !index.default && !index.explicit), ) } } /// Return an iterator over all [`IndexUrl`] entries in order. /// /// Prioritizes the `[tool.uv.index]` definitions over the `--extra-index-url` definitions /// over the `--index-url` definition. /// /// If `no_index` was enabled, then this always returns an empty /// iterator. pub fn indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { let mut seen = FxHashSet::default(); self.implicit_indexes() .chain(self.default_index()) .filter(|index| !index.explicit) .filter(move |index| seen.insert(index.raw_url())) // Filter out redundant raw URLs } /// Return an iterator over all user-defined [`Index`] entries in order. /// /// Prioritizes the `[tool.uv.index]` definitions over the `--extra-index-url` definitions /// over the `--index-url` definition. /// /// Unlike [`IndexUrl::indexes`], this includes explicit indexes and does _not_ insert PyPI /// as a fallback default. /// /// If `no_index` was enabled, then this always returns an empty /// iterator. pub fn defined_indexes(&'a self) -> impl Iterator<Item = &'a Index> + 'a { if self.no_index { return Either::Left(std::iter::empty()); } let mut seen = FxHashSet::default(); let (non_default, default) = self .indexes .iter() .filter(move |index| { if let Some(name) = &index.name { seen.insert(name) } else { true } }) .partition::<Vec<_>, _>(|index| !index.default); Either::Right(non_default.into_iter().chain(default)) } /// Return the `--no-index` flag. pub fn no_index(&self) -> bool { self.no_index } /// Return the [`IndexStatusCodeStrategy`] for an [`IndexUrl`]. pub fn status_code_strategy_for(&self, url: &IndexUrl) -> IndexStatusCodeStrategy { for index in &self.indexes { if is_same_index(index.url(), url) { return index.status_code_strategy(); } } IndexStatusCodeStrategy::Default } /// Return the Simple API cache control header for an [`IndexUrl`], if configured. pub fn simple_api_cache_control_for(&self, url: &IndexUrl) -> Option<&str> { for index in &self.indexes { if is_same_index(index.url(), url) { return index.simple_api_cache_control(); } } None } /// Return the artifact cache control header for an [`IndexUrl`], if configured. pub fn artifact_cache_control_for(&self, url: &IndexUrl) -> Option<&str> { for index in &self.indexes { if is_same_index(index.url(), url) { return index.artifact_cache_control(); } } None } } bitflags::bitflags! { #[derive(Debug, Copy, Clone)] struct Flags: u8 { /// Whether the index supports range requests. const NO_RANGE_REQUESTS = 1; /// Whether the index returned a `401 Unauthorized` status code. const UNAUTHORIZED = 1 << 2; /// Whether the index returned a `403 Forbidden` status code. const FORBIDDEN = 1 << 1; } } /// A map of [`IndexUrl`]s to their capabilities. /// /// We only store indexes that lack capabilities (i.e., don't support range requests, aren't /// authorized). The benefit is that the map is almost always empty, so validating capabilities is /// extremely cheap. #[derive(Debug, Default, Clone)] pub struct IndexCapabilities(Arc<RwLock<FxHashMap<IndexUrl, Flags>>>); impl IndexCapabilities { /// Returns `true` if the given [`IndexUrl`] supports range requests. pub fn supports_range_requests(&self, index_url: &IndexUrl) -> bool { !self .0 .read() .unwrap() .get(index_url) .is_some_and(|flags| flags.intersects(Flags::NO_RANGE_REQUESTS)) } /// Mark an [`IndexUrl`] as not supporting range requests. pub fn set_no_range_requests(&self, index_url: IndexUrl) { self.0 .write() .unwrap() .entry(index_url) .or_insert(Flags::empty()) .insert(Flags::NO_RANGE_REQUESTS); } /// Returns `true` if the given [`IndexUrl`] returns a `401 Unauthorized` status code. pub fn unauthorized(&self, index_url: &IndexUrl) -> bool { self.0 .read() .unwrap() .get(index_url) .is_some_and(|flags| flags.intersects(Flags::UNAUTHORIZED)) } /// Mark an [`IndexUrl`] as returning a `401 Unauthorized` status code. pub fn set_unauthorized(&self, index_url: IndexUrl) { self.0 .write() .unwrap() .entry(index_url) .or_insert(Flags::empty()) .insert(Flags::UNAUTHORIZED); } /// Returns `true` if the given [`IndexUrl`] returns a `403 Forbidden` status code. pub fn forbidden(&self, index_url: &IndexUrl) -> bool { self.0 .read() .unwrap() .get(index_url) .is_some_and(|flags| flags.intersects(Flags::FORBIDDEN)) } /// Mark an [`IndexUrl`] as returning a `403 Forbidden` status code. pub fn set_forbidden(&self, index_url: IndexUrl) { self.0 .write() .unwrap() .entry(index_url) .or_insert(Flags::empty()) .insert(Flags::FORBIDDEN); } } #[cfg(test)] mod tests { use super::*; use crate::{IndexCacheControl, IndexFormat, IndexName}; use uv_small_str::SmallString; #[test] fn test_index_url_parse_valid_paths() { // Absolute path assert!(is_disambiguated_path("/absolute/path")); // Relative path assert!(is_disambiguated_path("./relative/path")); assert!(is_disambiguated_path("../../relative/path")); if cfg!(windows) { // Windows absolute path assert!(is_disambiguated_path("C:/absolute/path")); // Windows relative path assert!(is_disambiguated_path(".\\relative\\path")); assert!(is_disambiguated_path("..\\..\\relative\\path")); } } #[test] fn test_index_url_parse_ambiguous_paths() { // Test single-segment ambiguous path assert!(!is_disambiguated_path("index")); // Test multi-segment ambiguous path assert!(!is_disambiguated_path("relative/path")); } #[test] fn test_index_url_parse_with_schemes() { assert!(is_disambiguated_path("file:///absolute/path")); assert!(is_disambiguated_path("https://registry.com/simple/")); assert!(is_disambiguated_path( "git+https://github.com/example/repo.git" )); } #[test] fn test_cache_control_lookup() { use std::str::FromStr; use uv_small_str::SmallString; use crate::IndexFormat; use crate::index_name::IndexName; let indexes = vec![ Index { name: Some(IndexName::from_str("index1").unwrap()), url: IndexUrl::from_str("https://index1.example.com/simple").unwrap(), cache_control: Some(crate::IndexCacheControl { api: Some(SmallString::from("max-age=300")), files: Some(SmallString::from("max-age=1800")), }), explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: uv_auth::AuthPolicy::default(), ignore_error_codes: None, }, Index { name: Some(IndexName::from_str("index2").unwrap()), url: IndexUrl::from_str("https://index2.example.com/simple").unwrap(), cache_control: None, explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: uv_auth::AuthPolicy::default(), ignore_error_codes: None, }, ]; let index_urls = IndexUrls::from_indexes(indexes); let url1 = IndexUrl::from_str("https://index1.example.com/simple").unwrap(); assert_eq!( index_urls.simple_api_cache_control_for(&url1), Some("max-age=300") ); assert_eq!( index_urls.artifact_cache_control_for(&url1), Some("max-age=1800") ); let url2 = IndexUrl::from_str("https://index2.example.com/simple").unwrap(); assert_eq!(index_urls.simple_api_cache_control_for(&url2), None); assert_eq!(index_urls.artifact_cache_control_for(&url2), None); let url3 = IndexUrl::from_str("https://index3.example.com/simple").unwrap(); assert_eq!(index_urls.simple_api_cache_control_for(&url3), None); assert_eq!(index_urls.artifact_cache_control_for(&url3), None); } #[test] fn test_pytorch_default_cache_control() { // Test that PyTorch indexes get default cache control from the getter methods let indexes = vec![Index { name: Some(IndexName::from_str("pytorch").unwrap()), url: IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(), cache_control: None, // No explicit cache control explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: uv_auth::AuthPolicy::default(), ignore_error_codes: None, }]; let index_urls = IndexUrls::from_indexes(indexes.clone()); let index_locations = IndexLocations::new(indexes, Vec::new(), false); let pytorch_url = IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(); // IndexUrls should return the default for PyTorch assert_eq!(index_urls.simple_api_cache_control_for(&pytorch_url), None); assert_eq!( index_urls.artifact_cache_control_for(&pytorch_url), Some("max-age=365000000, immutable, public") ); // IndexLocations should also return the default for PyTorch assert_eq!( index_locations.simple_api_cache_control_for(&pytorch_url), None ); assert_eq!( index_locations.artifact_cache_control_for(&pytorch_url), Some("max-age=365000000, immutable, public") ); } #[test] fn test_pytorch_user_override_cache_control() { // Test that user-specified cache control overrides PyTorch defaults let indexes = vec![Index { name: Some(IndexName::from_str("pytorch").unwrap()), url: IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(), cache_control: Some(IndexCacheControl { api: Some(SmallString::from("no-cache")), files: Some(SmallString::from("max-age=3600")), }), explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: uv_auth::AuthPolicy::default(), ignore_error_codes: None, }]; let index_urls = IndexUrls::from_indexes(indexes.clone()); let index_locations = IndexLocations::new(indexes, Vec::new(), false); let pytorch_url = IndexUrl::from_str("https://download.pytorch.org/whl/cu118").unwrap(); // User settings should override defaults assert_eq!( index_urls.simple_api_cache_control_for(&pytorch_url), Some("no-cache") ); assert_eq!( index_urls.artifact_cache_control_for(&pytorch_url), Some("max-age=3600") ); // Same for IndexLocations assert_eq!( index_locations.simple_api_cache_control_for(&pytorch_url), Some("no-cache") ); assert_eq!( index_locations.artifact_cache_control_for(&pytorch_url), Some("max-age=3600") ); } #[test] fn test_nvidia_default_cache_control() { // Test that NVIDIA indexes get default cache control from the getter methods let indexes = vec![Index { name: Some(IndexName::from_str("nvidia").unwrap()), url: IndexUrl::from_str("https://pypi.nvidia.com").unwrap(), cache_control: None, // No explicit cache control explicit: false, default: false, origin: None, format: IndexFormat::Simple, publish_url: None, authenticate: uv_auth::AuthPolicy::default(), ignore_error_codes: None, }]; let index_urls = IndexUrls::from_indexes(indexes.clone()); let index_locations = IndexLocations::new(indexes, Vec::new(), false); let nvidia_url = IndexUrl::from_str("https://pypi.nvidia.com").unwrap(); // IndexUrls should return the default for NVIDIA assert_eq!(index_urls.simple_api_cache_control_for(&nvidia_url), None); assert_eq!( index_urls.artifact_cache_control_for(&nvidia_url), Some("max-age=365000000, immutable, public") ); // IndexLocations should also return the default for NVIDIA assert_eq!( index_locations.simple_api_cache_control_for(&nvidia_url), None ); assert_eq!( index_locations.artifact_cache_control_for(&nvidia_url), Some("max-age=365000000, immutable, public") ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/any.rs
crates/uv-distribution-types/src/any.rs
use std::hash::Hash; use uv_cache_key::CanonicalUrl; use uv_normalize::PackageName; use uv_pep440::Version; use crate::cached::CachedDist; use crate::installed::InstalledDist; use crate::{InstalledMetadata, InstalledVersion, Name}; /// A distribution which is either installable, is a wheel in our cache or is already installed. /// /// Note equality and hash operations are only based on the name and canonical version, not the /// kind. #[derive(Debug, Clone, Eq)] #[allow(clippy::large_enum_variant)] pub enum LocalDist { Cached(CachedDist, CanonicalVersion), Installed(InstalledDist, CanonicalVersion), } impl LocalDist { fn canonical_version(&self) -> &CanonicalVersion { match self { Self::Cached(_, version) => version, Self::Installed(_, version) => version, } } } impl Name for LocalDist { fn name(&self) -> &PackageName { match self { Self::Cached(dist, _) => dist.name(), Self::Installed(dist, _) => dist.name(), } } } impl InstalledMetadata for LocalDist { fn installed_version(&self) -> InstalledVersion<'_> { match self { Self::Cached(dist, _) => dist.installed_version(), Self::Installed(dist, _) => dist.installed_version(), } } } impl From<CachedDist> for LocalDist { fn from(dist: CachedDist) -> Self { let version = CanonicalVersion::from(dist.installed_version()); Self::Cached(dist, version) } } impl From<InstalledDist> for LocalDist { fn from(dist: InstalledDist) -> Self { let version = CanonicalVersion::from(dist.installed_version()); Self::Installed(dist, version) } } impl Hash for LocalDist { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.name().hash(state); self.canonical_version().hash(state); } } impl PartialEq for LocalDist { fn eq(&self, other: &Self) -> bool { self.name() == other.name() && self.canonical_version() == other.canonical_version() } } /// Like [`InstalledVersion`], but with [`CanonicalUrl`] to ensure robust URL comparisons. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum CanonicalVersion { Version(Version), Url(CanonicalUrl, Version), } impl From<InstalledVersion<'_>> for CanonicalVersion { fn from(installed_version: InstalledVersion<'_>) -> Self { match installed_version { InstalledVersion::Version(version) => Self::Version(version.clone()), InstalledVersion::Url(url, version) => { Self::Url(CanonicalUrl::new(url), version.clone()) } } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/prioritized_distribution.rs
crates/uv-distribution-types/src/prioritized_distribution.rs
use std::fmt::{Display, Formatter}; use arcstr::ArcStr; use owo_colors::OwoColorize; use tracing::debug; use uv_distribution_filename::{BuildTag, WheelFilename}; use uv_pep440::{Version, VersionSpecifier, VersionSpecifiers}; use uv_pep508::{MarkerExpression, MarkerOperator, MarkerTree, MarkerValueString}; use uv_platform_tags::{AbiTag, IncompatibleTag, LanguageTag, PlatformTag, TagPriority, Tags}; use uv_pypi_types::{HashDigest, Yanked}; use crate::{ File, InstalledDist, KnownPlatform, RegistryBuiltDist, RegistryBuiltWheel, RegistrySourceDist, ResolvedDistRef, }; /// A collection of distributions that have been filtered by relevance. #[derive(Debug, Default, Clone)] pub struct PrioritizedDist(Box<PrioritizedDistInner>); /// [`PrioritizedDist`] is boxed because [`Dist`] is large. #[derive(Debug, Clone)] struct PrioritizedDistInner { /// The highest-priority source distribution. Between compatible source distributions this priority is arbitrary. source: Option<(RegistrySourceDist, SourceDistCompatibility)>, /// The highest-priority wheel index. When present, it is /// guaranteed to be a valid index into `wheels`. best_wheel_index: Option<usize>, /// The set of all wheels associated with this distribution. wheels: Vec<(RegistryBuiltWheel, WheelCompatibility)>, /// The hashes for each distribution. hashes: Vec<HashDigest>, /// The set of supported platforms for the distribution, described in terms of their markers. markers: MarkerTree, } impl Default for PrioritizedDistInner { fn default() -> Self { Self { source: None, best_wheel_index: None, wheels: Vec::new(), hashes: Vec::new(), markers: MarkerTree::FALSE, } } } /// A distribution that can be used for both resolution and installation. #[derive(Debug, Copy, Clone)] pub enum CompatibleDist<'a> { /// The distribution is already installed and can be used. InstalledDist(&'a InstalledDist), /// The distribution should be resolved and installed using a source distribution. SourceDist { /// The source distribution that should be used. sdist: &'a RegistrySourceDist, /// The prioritized distribution that the sdist came from. prioritized: &'a PrioritizedDist, }, /// The distribution should be resolved and installed using a wheel distribution. CompatibleWheel { /// The wheel that should be used. wheel: &'a RegistryBuiltWheel, /// The platform priority associated with the wheel. priority: Option<TagPriority>, /// The prioritized distribution that the wheel came from. prioritized: &'a PrioritizedDist, }, /// The distribution should be resolved using an incompatible wheel distribution, but /// installed using a source distribution. IncompatibleWheel { /// The sdist to be used during installation. sdist: &'a RegistrySourceDist, /// The wheel to be used during resolution. wheel: &'a RegistryBuiltWheel, /// The prioritized distribution that the wheel and sdist came from. prioritized: &'a PrioritizedDist, }, } impl CompatibleDist<'_> { /// Return the `requires-python` specifier for the distribution, if any. pub fn requires_python(&self) -> Option<&VersionSpecifiers> { match self { Self::InstalledDist(_) => None, Self::SourceDist { sdist, .. } => sdist.file.requires_python.as_ref(), Self::CompatibleWheel { wheel, .. } => wheel.file.requires_python.as_ref(), Self::IncompatibleWheel { sdist, .. } => sdist.file.requires_python.as_ref(), } } // For installable distributions, return the prioritized distribution it was derived from. pub fn prioritized(&self) -> Option<&PrioritizedDist> { match self { Self::InstalledDist(_) => None, Self::SourceDist { prioritized, .. } | Self::CompatibleWheel { prioritized, .. } | Self::IncompatibleWheel { prioritized, .. } => Some(prioritized), } } /// Return the set of supported platform the distribution, in terms of their markers. pub fn implied_markers(&self) -> MarkerTree { match self.prioritized() { Some(prioritized) => prioritized.0.markers, None => MarkerTree::TRUE, } } } #[derive(Debug, PartialEq, Eq, Clone)] pub enum IncompatibleDist { /// An incompatible wheel is available. Wheel(IncompatibleWheel), /// An incompatible source distribution is available. Source(IncompatibleSource), /// No distributions are available Unavailable, } impl IncompatibleDist { pub fn singular_message(&self) -> String { match self { Self::Wheel(incompatibility) => match incompatibility { IncompatibleWheel::NoBinary => format!("has {self}"), IncompatibleWheel::Tag(_) => format!("has {self}"), IncompatibleWheel::Yanked(_) => format!("was {self}"), IncompatibleWheel::ExcludeNewer(ts) => match ts { Some(_) => format!("was {self}"), None => format!("has {self}"), }, IncompatibleWheel::RequiresPython(..) => format!("requires {self}"), IncompatibleWheel::MissingPlatform(_) => format!("has {self}"), }, Self::Source(incompatibility) => match incompatibility { IncompatibleSource::NoBuild => format!("has {self}"), IncompatibleSource::Yanked(_) => format!("was {self}"), IncompatibleSource::ExcludeNewer(ts) => match ts { Some(_) => format!("was {self}"), None => format!("has {self}"), }, IncompatibleSource::RequiresPython(..) => { format!("requires {self}") } }, Self::Unavailable => format!("has {self}"), } } pub fn plural_message(&self) -> String { match self { Self::Wheel(incompatibility) => match incompatibility { IncompatibleWheel::NoBinary => format!("have {self}"), IncompatibleWheel::Tag(_) => format!("have {self}"), IncompatibleWheel::Yanked(_) => format!("were {self}"), IncompatibleWheel::ExcludeNewer(ts) => match ts { Some(_) => format!("were {self}"), None => format!("have {self}"), }, IncompatibleWheel::RequiresPython(..) => format!("require {self}"), IncompatibleWheel::MissingPlatform(_) => format!("have {self}"), }, Self::Source(incompatibility) => match incompatibility { IncompatibleSource::NoBuild => format!("have {self}"), IncompatibleSource::Yanked(_) => format!("were {self}"), IncompatibleSource::ExcludeNewer(ts) => match ts { Some(_) => format!("were {self}"), None => format!("have {self}"), }, IncompatibleSource::RequiresPython(..) => { format!("require {self}") } }, Self::Unavailable => format!("have {self}"), } } pub fn context_message( &self, tags: Option<&Tags>, requires_python: Option<AbiTag>, ) -> Option<String> { match self { Self::Wheel(incompatibility) => match incompatibility { IncompatibleWheel::Tag(IncompatibleTag::Python) => { let tag = tags?.python_tag().as_ref().map(ToString::to_string)?; Some(format!("(e.g., `{tag}`)", tag = tag.cyan())) } IncompatibleWheel::Tag(IncompatibleTag::Abi) => { let tag = tags?.abi_tag().as_ref().map(ToString::to_string)?; Some(format!("(e.g., `{tag}`)", tag = tag.cyan())) } IncompatibleWheel::Tag(IncompatibleTag::AbiPythonVersion) => { let tag = requires_python?; Some(format!("(e.g., `{tag}`)", tag = tag.cyan())) } IncompatibleWheel::Tag(IncompatibleTag::Platform) => { let tag = tags?.platform_tag().map(ToString::to_string)?; Some(format!("(e.g., `{tag}`)", tag = tag.cyan())) } IncompatibleWheel::Tag(IncompatibleTag::Invalid) => None, IncompatibleWheel::NoBinary => None, IncompatibleWheel::Yanked(..) => None, IncompatibleWheel::ExcludeNewer(..) => None, IncompatibleWheel::RequiresPython(..) => None, IncompatibleWheel::MissingPlatform(..) => None, }, Self::Source(..) => None, Self::Unavailable => None, } } } impl Display for IncompatibleDist { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Wheel(incompatibility) => match incompatibility { IncompatibleWheel::NoBinary => f.write_str("no source distribution"), IncompatibleWheel::Tag(tag) => match tag { IncompatibleTag::Invalid => f.write_str("no wheels with valid tags"), IncompatibleTag::Python => { f.write_str("no wheels with a matching Python implementation tag") } IncompatibleTag::Abi => f.write_str("no wheels with a matching Python ABI tag"), IncompatibleTag::AbiPythonVersion => { f.write_str("no wheels with a matching Python version tag") } IncompatibleTag::Platform => { f.write_str("no wheels with a matching platform tag") } }, IncompatibleWheel::Yanked(yanked) => match yanked { Yanked::Bool(_) => f.write_str("yanked"), Yanked::Reason(reason) => write!( f, "yanked (reason: {})", reason.trim().trim_end_matches('.') ), }, IncompatibleWheel::ExcludeNewer(ts) => match ts { Some(_) => f.write_str("published after the exclude newer time"), None => f.write_str("no publish time"), }, IncompatibleWheel::RequiresPython(python, _) => { write!(f, "Python {python}") } IncompatibleWheel::MissingPlatform(marker) => { if let Some(platform) = KnownPlatform::from_marker(*marker) { write!(f, "no {platform}-compatible wheels") } else if let Some(marker) = marker.try_to_string() { write!(f, "no `{marker}`-compatible wheels") } else { write!(f, "no compatible wheels") } } }, Self::Source(incompatibility) => match incompatibility { IncompatibleSource::NoBuild => f.write_str("no usable wheels"), IncompatibleSource::Yanked(yanked) => match yanked { Yanked::Bool(_) => f.write_str("yanked"), Yanked::Reason(reason) => write!( f, "yanked (reason: {})", reason.trim().trim_end_matches('.') ), }, IncompatibleSource::ExcludeNewer(ts) => match ts { Some(_) => f.write_str("published after the exclude newer time"), None => f.write_str("no publish time"), }, IncompatibleSource::RequiresPython(python, _) => { write!(f, "Python {python}") } }, Self::Unavailable => f.write_str("no available distributions"), } } } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum PythonRequirementKind { /// The installed version of Python. Installed, /// The target version of Python; that is, the version of Python for which we are resolving /// dependencies. This is typically the same as the installed version, but may be different /// when specifying an alternate Python version for the resolution. Target, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum WheelCompatibility { Incompatible(IncompatibleWheel), Compatible(HashComparison, Option<TagPriority>, Option<BuildTag>), } #[derive(Debug, PartialEq, Eq, Clone)] pub enum IncompatibleWheel { /// The wheel was published after the exclude newer time. ExcludeNewer(Option<i64>), /// The wheel tags do not match those of the target Python platform. Tag(IncompatibleTag), /// The required Python version is not a superset of the target Python version range. RequiresPython(VersionSpecifiers, PythonRequirementKind), /// The wheel was yanked. Yanked(Yanked), /// The use of binary wheels is disabled. NoBinary, /// Wheels are not available for the current platform. MissingPlatform(MarkerTree), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum SourceDistCompatibility { Incompatible(IncompatibleSource), Compatible(HashComparison), } #[derive(Debug, PartialEq, Eq, Clone)] pub enum IncompatibleSource { ExcludeNewer(Option<i64>), RequiresPython(VersionSpecifiers, PythonRequirementKind), Yanked(Yanked), NoBuild, } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum HashComparison { /// The hash is present, but does not match the expected value. Mismatched, /// The hash is missing. Missing, /// The hash matches the expected value. Matched, } impl PrioritizedDist { /// Create a new [`PrioritizedDist`] from the given wheel distribution. pub fn from_built( dist: RegistryBuiltWheel, hashes: Vec<HashDigest>, compatibility: WheelCompatibility, ) -> Self { Self(Box::new(PrioritizedDistInner { markers: implied_markers(&dist.filename), best_wheel_index: Some(0), wheels: vec![(dist, compatibility)], source: None, hashes, })) } /// Create a new [`PrioritizedDist`] from the given source distribution. pub fn from_source( dist: RegistrySourceDist, hashes: Vec<HashDigest>, compatibility: SourceDistCompatibility, ) -> Self { Self(Box::new(PrioritizedDistInner { markers: MarkerTree::TRUE, best_wheel_index: None, wheels: vec![], source: Some((dist, compatibility)), hashes, })) } /// Insert the given built distribution into the [`PrioritizedDist`]. pub fn insert_built( &mut self, dist: RegistryBuiltWheel, hashes: impl IntoIterator<Item = HashDigest>, compatibility: WheelCompatibility, ) { // Track the implied markers. if compatibility.is_compatible() { if !self.0.markers.is_true() { self.0.markers.or(implied_markers(&dist.filename)); } } // Track the hashes. if !compatibility.is_excluded() { self.0.hashes.extend(hashes); } // Track the highest-priority wheel. if let Some((.., existing_compatibility)) = self.best_wheel() { if compatibility.is_more_compatible(existing_compatibility) { self.0.best_wheel_index = Some(self.0.wheels.len()); } } else { self.0.best_wheel_index = Some(self.0.wheels.len()); } self.0.wheels.push((dist, compatibility)); } /// Insert the given source distribution into the [`PrioritizedDist`]. pub fn insert_source( &mut self, dist: RegistrySourceDist, hashes: impl IntoIterator<Item = HashDigest>, compatibility: SourceDistCompatibility, ) { // Track the implied markers. if compatibility.is_compatible() { self.0.markers = MarkerTree::TRUE; } // Track the hashes. if !compatibility.is_excluded() { self.0.hashes.extend(hashes); } // Track the highest-priority source. if let Some((.., existing_compatibility)) = &self.0.source { if compatibility.is_more_compatible(existing_compatibility) { self.0.source = Some((dist, compatibility)); } } else { self.0.source = Some((dist, compatibility)); } } /// Return the highest-priority distribution for the package version, if any. pub fn get(&self) -> Option<CompatibleDist<'_>> { let best_wheel = self.0.best_wheel_index.map(|i| &self.0.wheels[i]); match (&best_wheel, &self.0.source) { // If both are compatible, break ties based on the hash outcome. For example, prefer a // source distribution with a matching hash over a wheel with a mismatched hash. When // the outcomes are equivalent (e.g., both have a matching hash), prefer the wheel. ( Some((wheel, WheelCompatibility::Compatible(wheel_hash, tag_priority, ..))), Some((sdist, SourceDistCompatibility::Compatible(sdist_hash))), ) => { if sdist_hash > wheel_hash { Some(CompatibleDist::SourceDist { sdist, prioritized: self, }) } else { Some(CompatibleDist::CompatibleWheel { wheel, priority: *tag_priority, prioritized: self, }) } } // Prefer the highest-priority, platform-compatible wheel. (Some((wheel, WheelCompatibility::Compatible(_, tag_priority, ..))), _) => { Some(CompatibleDist::CompatibleWheel { wheel, priority: *tag_priority, prioritized: self, }) } // If we have a compatible source distribution and an incompatible wheel, return the // wheel. We assume that all distributions have the same metadata for a given package // version. If a compatible source distribution exists, we assume we can build it, but // using the wheel is faster. // // (If the incompatible wheel should actually be ignored entirely, fall through to // using the source distribution.) ( Some((wheel, compatibility @ WheelCompatibility::Incompatible(_))), Some((sdist, SourceDistCompatibility::Compatible(_))), ) if !compatibility.is_excluded() => Some(CompatibleDist::IncompatibleWheel { sdist, wheel, prioritized: self, }), // Otherwise, if we have a source distribution, return it. (.., Some((sdist, SourceDistCompatibility::Compatible(_)))) => { Some(CompatibleDist::SourceDist { sdist, prioritized: self, }) } _ => None, } } /// Return the incompatibility for the best source distribution, if any. pub fn incompatible_source(&self) -> Option<&IncompatibleSource> { self.0 .source .as_ref() .and_then(|(_, compatibility)| match compatibility { SourceDistCompatibility::Compatible(_) => None, SourceDistCompatibility::Incompatible(incompatibility) => Some(incompatibility), }) } /// Return the incompatibility for the best wheel, if any. pub fn incompatible_wheel(&self) -> Option<&IncompatibleWheel> { self.0 .best_wheel_index .map(|i| &self.0.wheels[i]) .and_then(|(_, compatibility)| match compatibility { WheelCompatibility::Compatible(_, _, _) => None, WheelCompatibility::Incompatible(incompatibility) => Some(incompatibility), }) } /// Return the hashes for each distribution. pub fn hashes(&self) -> &[HashDigest] { &self.0.hashes } /// Returns true if and only if this distribution does not contain any /// source distributions or wheels. pub fn is_empty(&self) -> bool { self.0.source.is_none() && self.0.wheels.is_empty() } /// If this prioritized dist has at least one wheel, then this creates /// a built distribution with the best wheel in this prioritized dist. pub fn built_dist(&self) -> Option<RegistryBuiltDist> { let best_wheel_index = self.0.best_wheel_index?; // Remove any excluded wheels from the list of wheels, and adjust the wheel index to be // relative to the filtered list. let mut adjusted_wheels = Vec::with_capacity(self.0.wheels.len()); let mut adjusted_best_index = 0; for (i, (wheel, compatibility)) in self.0.wheels.iter().enumerate() { if compatibility.is_excluded() { continue; } if i == best_wheel_index { adjusted_best_index = adjusted_wheels.len(); } adjusted_wheels.push(wheel.clone()); } let sdist = self.0.source.as_ref().map(|(sdist, _)| sdist.clone()); Some(RegistryBuiltDist { wheels: adjusted_wheels, best_wheel_index: adjusted_best_index, sdist, }) } /// If this prioritized dist has an sdist, then this creates a source /// distribution. pub fn source_dist(&self) -> Option<RegistrySourceDist> { let mut sdist = self .0 .source .as_ref() .filter(|(_, compatibility)| !compatibility.is_excluded()) .map(|(sdist, _)| sdist.clone())?; assert!( sdist.wheels.is_empty(), "source distribution should not have any wheels yet" ); sdist.wheels = self .0 .wheels .iter() .map(|(wheel, _)| wheel.clone()) .collect(); Some(sdist) } /// Returns the "best" wheel in this prioritized distribution, if one /// exists. pub fn best_wheel(&self) -> Option<&(RegistryBuiltWheel, WheelCompatibility)> { self.0.best_wheel_index.map(|i| &self.0.wheels[i]) } /// Returns an iterator of all wheels and the source distribution, if any. pub fn files(&self) -> impl Iterator<Item = &File> { self.0 .wheels .iter() .map(|(wheel, _)| wheel.file.as_ref()) .chain( self.0 .source .as_ref() .map(|(source_dist, _)| source_dist.file.as_ref()), ) } /// Returns an iterator over all Python tags for the distribution. pub fn python_tags(&self) -> impl Iterator<Item = LanguageTag> + '_ { self.0 .wheels .iter() .flat_map(|(wheel, _)| wheel.filename.python_tags().iter().copied()) } /// Returns an iterator over all ABI tags for the distribution. pub fn abi_tags(&self) -> impl Iterator<Item = AbiTag> + '_ { self.0 .wheels .iter() .flat_map(|(wheel, _)| wheel.filename.abi_tags().iter().copied()) } /// Returns the set of platform tags for the distribution that are ABI-compatible with the given /// tags. pub fn platform_tags<'a>( &'a self, tags: &'a Tags, ) -> impl Iterator<Item = &'a PlatformTag> + 'a { self.0.wheels.iter().flat_map(move |(wheel, _)| { if wheel.filename.python_tags().iter().any(|wheel_py| { wheel .filename .abi_tags() .iter() .any(|wheel_abi| tags.is_compatible_abi(*wheel_py, *wheel_abi)) }) { wheel.filename.platform_tags().iter() } else { [].iter() } }) } } impl<'a> CompatibleDist<'a> { /// Return the [`ResolvedDistRef`] to use during resolution. pub fn for_resolution(&self) -> ResolvedDistRef<'a> { match self { Self::InstalledDist(dist) => ResolvedDistRef::Installed { dist }, Self::SourceDist { sdist, prioritized } => { ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized } } Self::CompatibleWheel { wheel, prioritized, .. } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized }, Self::IncompatibleWheel { wheel, prioritized, .. } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized }, } } /// Return the [`ResolvedDistRef`] to use during installation. pub fn for_installation(&self) -> ResolvedDistRef<'a> { match self { Self::InstalledDist(dist) => ResolvedDistRef::Installed { dist }, Self::SourceDist { sdist, prioritized } => { ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized } } Self::CompatibleWheel { wheel, prioritized, .. } => ResolvedDistRef::InstallableRegistryBuiltDist { wheel, prioritized }, Self::IncompatibleWheel { sdist, prioritized, .. } => ResolvedDistRef::InstallableRegistrySourceDist { sdist, prioritized }, } } /// Returns a [`RegistryBuiltWheel`] if the distribution includes a compatible or incompatible /// wheel. pub fn wheel(&self) -> Option<&RegistryBuiltWheel> { match self { Self::InstalledDist(_) => None, Self::SourceDist { .. } => None, Self::CompatibleWheel { wheel, .. } => Some(wheel), Self::IncompatibleWheel { wheel, .. } => Some(wheel), } } } impl WheelCompatibility { /// Return `true` if the distribution is compatible. pub fn is_compatible(&self) -> bool { matches!(self, Self::Compatible(_, _, _)) } /// Return `true` if the distribution is excluded. pub fn is_excluded(&self) -> bool { matches!(self, Self::Incompatible(IncompatibleWheel::ExcludeNewer(_))) } /// Return `true` if the current compatibility is more compatible than another. /// /// Compatible wheels are always higher more compatible than incompatible wheels. /// Compatible wheel ordering is determined by tag priority. pub fn is_more_compatible(&self, other: &Self) -> bool { match (self, other) { (Self::Compatible(_, _, _), Self::Incompatible(_)) => true, ( Self::Compatible(hash, tag_priority, build_tag), Self::Compatible(other_hash, other_tag_priority, other_build_tag), ) => { (hash, tag_priority, build_tag) > (other_hash, other_tag_priority, other_build_tag) } (Self::Incompatible(_), Self::Compatible(_, _, _)) => false, (Self::Incompatible(incompatibility), Self::Incompatible(other_incompatibility)) => { incompatibility.is_more_compatible(other_incompatibility) } } } } impl SourceDistCompatibility { /// Return `true` if the distribution is compatible. pub fn is_compatible(&self) -> bool { matches!(self, Self::Compatible(_)) } /// Return `true` if the distribution is excluded. pub fn is_excluded(&self) -> bool { matches!( self, Self::Incompatible(IncompatibleSource::ExcludeNewer(_)) ) } /// Return the higher priority compatibility. /// /// Compatible source distributions are always higher priority than incompatible source distributions. /// Compatible source distribution priority is arbitrary. /// Incompatible source distribution priority selects a source distribution that was "closest" to being usable. pub fn is_more_compatible(&self, other: &Self) -> bool { match (self, other) { (Self::Compatible(_), Self::Incompatible(_)) => true, (Self::Compatible(compatibility), Self::Compatible(other_compatibility)) => { compatibility > other_compatibility } (Self::Incompatible(_), Self::Compatible(_)) => false, (Self::Incompatible(incompatibility), Self::Incompatible(other_incompatibility)) => { incompatibility.is_more_compatible(other_incompatibility) } } } } impl IncompatibleSource { fn is_more_compatible(&self, other: &Self) -> bool { match self { Self::ExcludeNewer(timestamp_self) => match other { // Smaller timestamps are closer to the cut-off time Self::ExcludeNewer(timestamp_other) => timestamp_other < timestamp_self, Self::NoBuild | Self::RequiresPython(_, _) | Self::Yanked(_) => true, }, Self::RequiresPython(_, _) => match other { Self::ExcludeNewer(_) => false, // Version specifiers cannot be reasonably compared Self::RequiresPython(_, _) => false, Self::NoBuild | Self::Yanked(_) => true, }, Self::Yanked(_) => match other { Self::ExcludeNewer(_) | Self::RequiresPython(_, _) => false, // Yanks with a reason are more helpful for errors Self::Yanked(yanked_other) => matches!(yanked_other, Yanked::Reason(_)), Self::NoBuild => true, }, Self::NoBuild => false, } } } impl IncompatibleWheel { #[allow(clippy::match_like_matches_macro)] fn is_more_compatible(&self, other: &Self) -> bool { match self { Self::ExcludeNewer(timestamp_self) => match other { // Smaller timestamps are closer to the cut-off time Self::ExcludeNewer(timestamp_other) => match (timestamp_self, timestamp_other) { (None, _) => true, (_, None) => false, (Some(timestamp_self), Some(timestamp_other)) => { timestamp_other < timestamp_self } }, Self::MissingPlatform(_) | Self::NoBinary | Self::RequiresPython(_, _) | Self::Tag(_) | Self::Yanked(_) => true, }, Self::Tag(tag_self) => match other { Self::ExcludeNewer(_) => false, Self::Tag(tag_other) => tag_self > tag_other, Self::MissingPlatform(_) | Self::NoBinary | Self::RequiresPython(_, _) | Self::Yanked(_) => true, }, Self::RequiresPython(_, _) => match other { Self::ExcludeNewer(_) | Self::Tag(_) => false, // Version specifiers cannot be reasonably compared Self::RequiresPython(_, _) => false, Self::MissingPlatform(_) | Self::NoBinary | Self::Yanked(_) => true, }, Self::Yanked(_) => match other { Self::ExcludeNewer(_) | Self::Tag(_) | Self::RequiresPython(_, _) => false, // Yanks with a reason are more helpful for errors Self::Yanked(yanked_other) => matches!(yanked_other, Yanked::Reason(_)), Self::MissingPlatform(_) | Self::NoBinary => true, }, Self::NoBinary => match other { Self::ExcludeNewer(_) | Self::Tag(_) | Self::RequiresPython(_, _) | Self::Yanked(_) => false, Self::NoBinary => false, Self::MissingPlatform(_) => true, }, Self::MissingPlatform(_) => false, } } } /// Given a wheel filename, determine the set of supported markers.
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/origin.rs
crates/uv-distribution-types/src/origin.rs
/// The origin of a piece of configuration. #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)] pub enum Origin { /// The setting was provided via the CLI. Cli, /// The setting was provided via a user-level configuration file. User, /// The setting was provided via a project-level configuration file. Project, /// The setting was provided via a `requirements.txt` file. RequirementsTxt, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/hash.rs
crates/uv-distribution-types/src/hash.rs
use uv_pypi_types::{HashAlgorithm, HashDigest}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HashPolicy<'a> { /// No hash policy is specified. None, /// Hashes should be generated (specifically, a SHA-256 hash), but not validated. Generate(HashGeneration), /// Hashes should be validated against a pre-defined list of hashes. If necessary, hashes should /// be generated so as to ensure that the archive is valid. Validate(&'a [HashDigest]), } impl HashPolicy<'_> { /// Returns `true` if the hash policy is `None`. pub fn is_none(&self) -> bool { matches!(self, Self::None) } /// Returns `true` if the hash policy is `Validate`. pub fn is_validate(&self) -> bool { matches!(self, Self::Validate(_)) } /// Returns `true` if the hash policy indicates that hashes should be generated. pub fn is_generate(&self, dist: &crate::BuiltDist) -> bool { match self { Self::Generate(HashGeneration::Url) => dist.file().is_none(), Self::Generate(HashGeneration::All) => { dist.file().is_none_or(|file| file.hashes.is_empty()) } Self::Validate(_) => false, Self::None => false, } } /// Return the algorithms used in the hash policy. pub fn algorithms(&self) -> Vec<HashAlgorithm> { match self { Self::None => vec![], Self::Generate(_) => vec![HashAlgorithm::Sha256], Self::Validate(hashes) => { let mut algorithms = hashes.iter().map(HashDigest::algorithm).collect::<Vec<_>>(); algorithms.sort(); algorithms.dedup(); algorithms } } } /// Return the digests used in the hash policy. pub fn digests(&self) -> &[HashDigest] { match self { Self::None => &[], Self::Generate(_) => &[], Self::Validate(hashes) => hashes, } } } /// The context in which hashes should be generated. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum HashGeneration { /// Generate hashes for direct URL distributions. Url, /// Generate hashes for direct URL distributions, along with any distributions that are hosted /// on a registry that does _not_ provide hashes. All, } pub trait Hashed { /// Return the [`HashDigest`]s for the archive. fn hashes(&self) -> &[HashDigest]; /// Returns `true` if the archive satisfies the given hash policy. fn satisfies(&self, hashes: HashPolicy) -> bool { match hashes { HashPolicy::None => true, HashPolicy::Generate(_) => self .hashes() .iter() .any(|hash| hash.algorithm == HashAlgorithm::Sha256), HashPolicy::Validate(hashes) => self.hashes().iter().any(|hash| hashes.contains(hash)), } } /// Returns `true` if the archive includes a hash for at least one of the given algorithms. fn has_digests(&self, hashes: HashPolicy) -> bool { match hashes { HashPolicy::None => true, HashPolicy::Generate(_) => self .hashes() .iter() .any(|hash| hash.algorithm == HashAlgorithm::Sha256), HashPolicy::Validate(hashes) => hashes .iter() .map(HashDigest::algorithm) .any(|algorithm| self.hashes().iter().any(|hash| hash.algorithm == algorithm)), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/status_code_strategy.rs
crates/uv-distribution-types/src/status_code_strategy.rs
#[cfg(feature = "schemars")] use std::borrow::Cow; use std::ops::Deref; use http::StatusCode; use rustc_hash::FxHashSet; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use url::Url; use crate::{IndexCapabilities, IndexUrl}; #[derive(Debug, Clone, Default, Eq, PartialEq)] pub enum IndexStatusCodeStrategy { #[default] Default, IgnoreErrorCodes { status_codes: FxHashSet<StatusCode>, }, } impl IndexStatusCodeStrategy { /// Derive a strategy from an index URL. We special-case PyTorch. Otherwise, /// we follow the default strategy. pub fn from_index_url(url: &Url) -> Self { if url .host_str() .is_some_and(|host| host.eq_ignore_ascii_case("download.pytorch.org")) { // The PyTorch registry returns a 403 when a package is not found, so // we ignore them when deciding whether to search other indexes. Self::IgnoreErrorCodes { status_codes: FxHashSet::from_iter([StatusCode::FORBIDDEN]), } } else { Self::Default } } /// Derive a strategy from a list of status codes to ignore. pub fn from_ignored_error_codes(status_codes: &[SerializableStatusCode]) -> Self { Self::IgnoreErrorCodes { status_codes: status_codes .iter() .map(SerializableStatusCode::deref) .copied() .collect::<FxHashSet<_>>(), } } /// Derive a strategy for ignoring authentication error codes. pub fn ignore_authentication_error_codes() -> Self { Self::IgnoreErrorCodes { status_codes: FxHashSet::from_iter([ StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN, StatusCode::NETWORK_AUTHENTICATION_REQUIRED, StatusCode::PROXY_AUTHENTICATION_REQUIRED, ]), } } /// Based on the strategy, decide whether to continue searching the next index /// based on the status code returned by this one. pub fn handle_status_code( &self, status_code: StatusCode, index_url: &IndexUrl, capabilities: &IndexCapabilities, ) -> IndexStatusCodeDecision { match self { Self::Default => match status_code { StatusCode::NOT_FOUND => IndexStatusCodeDecision::Ignore, StatusCode::UNAUTHORIZED => { capabilities.set_unauthorized(index_url.clone()); IndexStatusCodeDecision::Fail(status_code) } StatusCode::FORBIDDEN => { capabilities.set_forbidden(index_url.clone()); IndexStatusCodeDecision::Fail(status_code) } _ => IndexStatusCodeDecision::Fail(status_code), }, Self::IgnoreErrorCodes { status_codes } => { if status_codes.contains(&status_code) { IndexStatusCodeDecision::Ignore } else { Self::Default.handle_status_code(status_code, index_url, capabilities) } } } } } /// Decision on whether to continue searching the next index. #[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)] pub enum IndexStatusCodeDecision { Ignore, Fail(StatusCode), } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SerializableStatusCode(StatusCode); impl Deref for SerializableStatusCode { type Target = StatusCode; fn deref(&self) -> &Self::Target { &self.0 } } impl Serialize for SerializableStatusCode { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_u16(self.0.as_u16()) } } impl<'de> Deserialize<'de> for SerializableStatusCode { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let code = u16::deserialize(deserializer)?; StatusCode::from_u16(code) .map(SerializableStatusCode) .map_err(|_| { serde::de::Error::custom(format!("{code} is not a valid HTTP status code")) }) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for SerializableStatusCode { fn schema_name() -> Cow<'static, str> { Cow::Borrowed("StatusCode") } fn json_schema(_generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({ "type": "number", "minimum": 100, "maximum": 599, "description": "HTTP status code (100-599)" }) } } #[cfg(test)] mod tests { use std::str::FromStr; use url::Url; use super::*; #[test] fn test_strategy_normal_registry() { let url = Url::from_str("https://internal-registry.com/simple").unwrap(); assert_eq!( IndexStatusCodeStrategy::from_index_url(&url), IndexStatusCodeStrategy::Default ); } #[test] fn test_strategy_pytorch_registry() { let status_codes = std::iter::once(StatusCode::FORBIDDEN).collect::<FxHashSet<_>>(); let url = Url::from_str("https://download.pytorch.org/whl/cu118").unwrap(); assert_eq!( IndexStatusCodeStrategy::from_index_url(&url), IndexStatusCodeStrategy::IgnoreErrorCodes { status_codes } ); } #[test] fn test_strategy_custom_error_codes() { let status_codes = FxHashSet::from_iter([StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN]); let serializable_status_codes = status_codes .iter() .map(|code| SerializableStatusCode(*code)) .collect::<Vec<_>>(); assert_eq!( IndexStatusCodeStrategy::from_ignored_error_codes(&serializable_status_codes), IndexStatusCodeStrategy::IgnoreErrorCodes { status_codes } ); } #[test] fn test_decision_default_400() { let strategy = IndexStatusCodeStrategy::Default; let status_code = StatusCode::BAD_REQUEST; let index_url = IndexUrl::parse("https://internal-registry.com/simple", None).unwrap(); let capabilities = IndexCapabilities::default(); let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!( decision, IndexStatusCodeDecision::Fail(StatusCode::BAD_REQUEST) ); } #[test] fn test_decision_default_401() { let strategy = IndexStatusCodeStrategy::Default; let status_code = StatusCode::UNAUTHORIZED; let index_url = IndexUrl::parse("https://internal-registry.com/simple", None).unwrap(); let capabilities = IndexCapabilities::default(); let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!( decision, IndexStatusCodeDecision::Fail(StatusCode::UNAUTHORIZED) ); assert!(capabilities.unauthorized(&index_url)); assert!(!capabilities.forbidden(&index_url)); } #[test] fn test_decision_default_403() { let strategy = IndexStatusCodeStrategy::Default; let status_code = StatusCode::FORBIDDEN; let index_url = IndexUrl::parse("https://internal-registry.com/simple", None).unwrap(); let capabilities = IndexCapabilities::default(); let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!( decision, IndexStatusCodeDecision::Fail(StatusCode::FORBIDDEN) ); assert!(capabilities.forbidden(&index_url)); assert!(!capabilities.unauthorized(&index_url)); } #[test] fn test_decision_default_404() { let strategy = IndexStatusCodeStrategy::Default; let status_code = StatusCode::NOT_FOUND; let index_url = IndexUrl::parse("https://internal-registry.com/simple", None).unwrap(); let capabilities = IndexCapabilities::default(); let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!(decision, IndexStatusCodeDecision::Ignore); assert!(!capabilities.forbidden(&index_url)); assert!(!capabilities.unauthorized(&index_url)); } #[test] fn test_decision_pytorch() { let index_url = IndexUrl::parse("https://download.pytorch.org/whl/cu118", None).unwrap(); let strategy = IndexStatusCodeStrategy::from_index_url(&index_url); let capabilities = IndexCapabilities::default(); // Test we continue on 403 for PyTorch registry. let status_code = StatusCode::FORBIDDEN; let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!(decision, IndexStatusCodeDecision::Ignore); // Test we stop on 401 for PyTorch registry. let status_code = StatusCode::UNAUTHORIZED; let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!( decision, IndexStatusCodeDecision::Fail(StatusCode::UNAUTHORIZED) ); } #[test] fn test_decision_multiple_ignored_status_codes() { let status_codes = vec![ StatusCode::UNAUTHORIZED, StatusCode::BAD_GATEWAY, StatusCode::SERVICE_UNAVAILABLE, ]; let strategy = IndexStatusCodeStrategy::IgnoreErrorCodes { status_codes: status_codes.iter().copied().collect::<FxHashSet<_>>(), }; let index_url = IndexUrl::parse("https://internal-registry.com/simple", None).unwrap(); let capabilities = IndexCapabilities::default(); // Test each ignored status code for status_code in status_codes { let decision = strategy.handle_status_code(status_code, &index_url, &capabilities); assert_eq!(decision, IndexStatusCodeDecision::Ignore); } // Test a status code that's not ignored let other_status_code = StatusCode::FORBIDDEN; let decision = strategy.handle_status_code(other_status_code, &index_url, &capabilities); assert_eq!( decision, IndexStatusCodeDecision::Fail(StatusCode::FORBIDDEN) ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/requires_python.rs
crates/uv-distribution-types/src/requires_python.rs
use std::collections::Bound; use version_ranges::Ranges; use uv_distribution_filename::WheelFilename; use uv_pep440::{ LowerBound, UpperBound, Version, VersionSpecifier, VersionSpecifiers, release_specifiers_to_ranges, }; use uv_pep508::{MarkerExpression, MarkerTree, MarkerValueVersion}; use uv_platform_tags::{AbiTag, LanguageTag}; /// The `Requires-Python` requirement specifier. /// /// See: <https://packaging.python.org/en/latest/guides/dropping-older-python-versions/> #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct RequiresPython { /// The supported Python versions as provides by the user, usually through the `requires-python` /// field in `pyproject.toml`. /// /// For a workspace, it's the intersection of all `requires-python` values in the workspace. If /// no bound was provided by the user, it's greater equal the current Python version. /// /// The specifiers remain static over the lifetime of the workspace, such that they /// represent the initial Python version constraints. specifiers: VersionSpecifiers, /// The lower and upper bounds of the given specifiers. /// /// The range may be narrowed over the course of dependency resolution as the resolver /// investigates environments with stricter Python version constraints. range: RequiresPythonRange, } impl RequiresPython { /// Returns a [`RequiresPython`] to express `>=` equality with the given version. pub fn greater_than_equal_version(version: &Version) -> Self { let version = version.only_release(); Self { specifiers: VersionSpecifiers::from(VersionSpecifier::greater_than_equal_version( version.clone(), )), range: RequiresPythonRange( LowerBound::new(Bound::Included(version.clone())), UpperBound::new(Bound::Unbounded), ), } } /// Returns a [`RequiresPython`] from a version specifier. pub fn from_specifiers(specifiers: &VersionSpecifiers) -> Self { let (lower_bound, upper_bound) = release_specifiers_to_ranges(specifiers.clone()) .bounding_range() .map(|(lower_bound, upper_bound)| (lower_bound.cloned(), upper_bound.cloned())) .unwrap_or((Bound::Unbounded, Bound::Unbounded)); Self { specifiers: specifiers.clone(), range: RequiresPythonRange(LowerBound::new(lower_bound), UpperBound::new(upper_bound)), } } /// Returns a [`RequiresPython`] to express the intersection of the given version specifiers. /// /// For example, given `>=3.8` and `>=3.9`, this would return `>=3.9`. pub fn intersection<'a>( specifiers: impl Iterator<Item = &'a VersionSpecifiers>, ) -> Option<Self> { // Convert to PubGrub range and perform an intersection. let range = specifiers .map(|specs| release_specifiers_to_ranges(specs.clone())) .reduce(|acc, r| acc.intersection(&r))?; // If the intersection is empty, return `None`. if range.is_empty() { return None; } // Convert back to PEP 440 specifiers. let specifiers = VersionSpecifiers::from_release_only_bounds(range.iter()); // Extract the bounds. let range = RequiresPythonRange::from_range(&range); Some(Self { specifiers, range }) } /// Split the [`RequiresPython`] at the given version. /// /// For example, if the current requirement is `>=3.10`, and the split point is `3.11`, then /// the result will be `>=3.10 and <3.11` and `>=3.11`. pub fn split(&self, bound: Bound<Version>) -> Option<(Self, Self)> { let RequiresPythonRange(.., upper) = &self.range; let upper = Ranges::from_range_bounds((bound, upper.clone().into())); let lower = upper.complement(); // Intersect left and right with the existing range. let lower = lower.intersection(&Ranges::from(self.range.clone())); let upper = upper.intersection(&Ranges::from(self.range.clone())); if lower.is_empty() || upper.is_empty() { None } else { Some(( Self { specifiers: VersionSpecifiers::from_release_only_bounds(lower.iter()), range: RequiresPythonRange::from_range(&lower), }, Self { specifiers: VersionSpecifiers::from_release_only_bounds(upper.iter()), range: RequiresPythonRange::from_range(&upper), }, )) } } /// Narrow the [`RequiresPython`] by computing the intersection with the given range. /// /// Returns `None` if the given range is not narrower than the current range. pub fn narrow(&self, range: &RequiresPythonRange) -> Option<Self> { if *range == self.range { return None; } let lower = if range.0 >= self.range.0 { Some(&range.0) } else { None }; let upper = if range.1 <= self.range.1 { Some(&range.1) } else { None }; let range = match (lower, upper) { (Some(lower), Some(upper)) => Some(RequiresPythonRange(lower.clone(), upper.clone())), (Some(lower), None) => Some(RequiresPythonRange(lower.clone(), self.range.1.clone())), (None, Some(upper)) => Some(RequiresPythonRange(self.range.0.clone(), upper.clone())), (None, None) => None, }?; Some(Self { specifiers: range.specifiers(), range, }) } /// Returns this `Requires-Python` specifier as an equivalent /// [`MarkerTree`] utilizing the `python_full_version` marker field. /// /// This is useful for comparing a `Requires-Python` specifier with /// arbitrary marker expressions. For example, one can ask whether the /// returned marker expression is disjoint with another marker expression. /// If it is, then one can conclude that the `Requires-Python` specifier /// excludes the dependency with that other marker expression. /// /// If this `Requires-Python` specifier has no constraints, then this /// returns a marker tree that evaluates to `true` for all possible marker /// environments. pub fn to_marker_tree(&self) -> MarkerTree { match (self.range.0.as_ref(), self.range.1.as_ref()) { (Bound::Included(lower), Bound::Included(upper)) => { let mut lower = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_equal_version(lower.clone()), }); let upper = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_equal_version(upper.clone()), }); lower.and(upper); lower } (Bound::Included(lower), Bound::Excluded(upper)) => { let mut lower = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_equal_version(lower.clone()), }); let upper = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_version(upper.clone()), }); lower.and(upper); lower } (Bound::Excluded(lower), Bound::Included(upper)) => { let mut lower = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_version(lower.clone()), }); let upper = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_equal_version(upper.clone()), }); lower.and(upper); lower } (Bound::Excluded(lower), Bound::Excluded(upper)) => { let mut lower = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_version(lower.clone()), }); let upper = MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_version(upper.clone()), }); lower.and(upper); lower } (Bound::Unbounded, Bound::Unbounded) => MarkerTree::TRUE, (Bound::Unbounded, Bound::Included(upper)) => { MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_equal_version(upper.clone()), }) } (Bound::Unbounded, Bound::Excluded(upper)) => { MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::less_than_version(upper.clone()), }) } (Bound::Included(lower), Bound::Unbounded) => { MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_equal_version(lower.clone()), }) } (Bound::Excluded(lower), Bound::Unbounded) => { MarkerTree::expression(MarkerExpression::Version { key: MarkerValueVersion::PythonFullVersion, specifier: VersionSpecifier::greater_than_version(lower.clone()), }) } } } /// Returns `true` if the `Requires-Python` is compatible with the given version. /// /// N.B. This operation should primarily be used when evaluating compatibility of Python /// versions against the user's own project. For example, if the user defines a /// `requires-python` in a `pyproject.toml`, this operation could be used to determine whether /// a given Python interpreter is compatible with the user's project. pub fn contains(&self, version: &Version) -> bool { let version = version.only_release(); self.specifiers.contains(&version) } /// Returns `true` if the `Requires-Python` is contained by the given version specifiers. /// /// In this context, we treat `Requires-Python` as a lower bound. For example, if the /// requirement expresses `>=3.8, <4`, we treat it as `>=3.8`. `Requires-Python` itself was /// intended to enable packages to drop support for older versions of Python without breaking /// installations on those versions, and packages cannot know whether they are compatible with /// future, unreleased versions of Python. /// /// The specifiers are considered to "contain" the `Requires-Python` if the specifiers are /// compatible with all versions in the `Requires-Python` range (i.e., have a _lower_ lower /// bound). /// /// For example, if the `Requires-Python` is `>=3.8`, then `>=3.7` would be considered /// compatible, since all versions in the `Requires-Python` range are also covered by the /// provided range. However, `>=3.9` would not be considered compatible, as the /// `Requires-Python` includes Python 3.8, but `>=3.9` does not. /// /// N.B. This operation should primarily be used when evaluating the compatibility of a /// project's `Requires-Python` specifier against a dependency's `Requires-Python` specifier. pub fn is_contained_by(&self, target: &VersionSpecifiers) -> bool { let target = release_specifiers_to_ranges(target.clone()) .bounding_range() .map(|bounding_range| bounding_range.0.cloned()) .unwrap_or(Bound::Unbounded); // We want, e.g., `self.range.lower()` to be `>=3.8` and `target` to be `>=3.7`. // // That is: `target` should be less than or equal to `self.range.lower()`. *self.range.lower() >= LowerBound(target.clone()) } /// Returns the [`VersionSpecifiers`] for the `Requires-Python` specifier. pub fn specifiers(&self) -> &VersionSpecifiers { &self.specifiers } /// Returns `true` if the `Requires-Python` specifier is unbounded. pub fn is_unbounded(&self) -> bool { self.range.lower().as_ref() == Bound::Unbounded } /// Returns `true` if the `Requires-Python` specifier is set to an exact version /// without specifying a patch version. (e.g. `==3.10`) pub fn is_exact_without_patch(&self) -> bool { match self.range.lower().as_ref() { Bound::Included(version) => { version.release().len() == 2 && self.range.upper().as_ref() == Bound::Included(version) } _ => false, } } /// Returns the [`Range`] bounding the `Requires-Python` specifier. pub fn range(&self) -> &RequiresPythonRange { &self.range } /// Returns a wheel tag that's compatible with the `Requires-Python` specifier. pub fn abi_tag(&self) -> Option<AbiTag> { match self.range.lower().as_ref() { Bound::Included(version) | Bound::Excluded(version) => { let major = version.release().first().copied()?; let major = u8::try_from(major).ok()?; let minor = version.release().get(1).copied()?; let minor = u8::try_from(minor).ok()?; Some(AbiTag::CPython { gil_disabled: false, python_version: (major, minor), }) } Bound::Unbounded => None, } } /// Simplifies the given markers in such a way as to assume that /// the Python version is constrained by this Python version bound. /// /// For example, with `requires-python = '>=3.8'`, a marker like this: /// /// ```text /// python_full_version >= '3.8' and python_full_version < '3.12' /// ``` /// /// Will be simplified to: /// /// ```text /// python_full_version < '3.12' /// ``` /// /// That is, `python_full_version >= '3.8'` is assumed to be true by virtue /// of `requires-python`, and is thus not needed in the marker. /// /// This should be used in contexts in which this assumption is valid to /// make. Generally, this means it should not be used inside the resolver, /// but instead near the boundaries of the system (like formatting error /// messages and writing the lock file). The reason for this is that /// this simplification fundamentally changes the meaning of the marker, /// and the *only* correct way to interpret it is in a context in which /// `requires-python` is known to be true. For example, when markers from /// a lock file are deserialized and turned into a `ResolutionGraph`, the /// markers are "complexified" to put the `requires-python` assumption back /// into the marker explicitly. pub fn simplify_markers(&self, marker: MarkerTree) -> MarkerTree { let (lower, upper) = (self.range().lower(), self.range().upper()); marker.simplify_python_versions(lower.as_ref(), upper.as_ref()) } /// The inverse of `simplify_markers`. /// /// This should be applied near the boundaries of uv when markers are /// deserialized from a context where `requires-python` is assumed. For /// example, with `requires-python = '>=3.8'` and a marker like: /// /// ```text /// python_full_version < '3.12' /// ``` /// /// It will be "complexified" to: /// /// ```text /// python_full_version >= '3.8' and python_full_version < '3.12' /// ``` pub fn complexify_markers(&self, marker: MarkerTree) -> MarkerTree { let (lower, upper) = (self.range().lower(), self.range().upper()); marker.complexify_python_versions(lower.as_ref(), upper.as_ref()) } /// Returns `false` if the wheel's tags state it can't be used in the given Python version /// range. /// /// It is meant to filter out clearly unusable wheels with perfect specificity and acceptable /// sensitivity, we return `true` if the tags are unknown. pub fn matches_wheel_tag(&self, wheel: &WheelFilename) -> bool { wheel.abi_tags().iter().any(|abi_tag| { if *abi_tag == AbiTag::Abi3 { // Universal tags are allowed. true } else if *abi_tag == AbiTag::None { wheel.python_tags().iter().any(|python_tag| { // Remove `py2-none-any` and `py27-none-any` and analogous `cp` and `pp` tags. if matches!( python_tag, LanguageTag::Python { major: 2, .. } | LanguageTag::CPython { python_version: (2, ..) } | LanguageTag::PyPy { python_version: (2, ..) } | LanguageTag::GraalPy { python_version: (2, ..) } | LanguageTag::Pyston { python_version: (2, ..) } ) { return false; } // Remove (e.g.) `py312-none-any` if the specifier is `==3.10.*`. However, // `py37-none-any` would be fine, since the `3.7` represents a lower bound. if let LanguageTag::Python { major: 3, minor: Some(minor), } = python_tag { // Ex) If the wheel bound is `3.12`, then it doesn't match `<=3.10.`. let wheel_bound = UpperBound(Bound::Included(Version::new([3, u64::from(*minor)]))); if wheel_bound > self.range.upper().major_minor() { return false; } return true; } // Remove (e.g.) `cp36-none-any` or `cp312-none-any` if the specifier is // `==3.10.*`, since these tags require an exact match. if let LanguageTag::CPython { python_version: (3, minor), } | LanguageTag::PyPy { python_version: (3, minor), } | LanguageTag::GraalPy { python_version: (3, minor), } | LanguageTag::Pyston { python_version: (3, minor), } = python_tag { // Ex) If the wheel bound is `3.6`, then it doesn't match `>=3.10`. let wheel_bound = LowerBound(Bound::Included(Version::new([3, u64::from(*minor)]))); if wheel_bound < self.range.lower().major_minor() { return false; } // Ex) If the wheel bound is `3.12`, then it doesn't match `<=3.10.`. let wheel_bound = UpperBound(Bound::Included(Version::new([3, u64::from(*minor)]))); if wheel_bound > self.range.upper().major_minor() { return false; } return true; } // Unknown tags are allowed. true }) } else if matches!( abi_tag, AbiTag::CPython { python_version: (2, ..), .. } | AbiTag::PyPy { python_version: None | Some((2, ..)), .. } | AbiTag::GraalPy { python_version: (2, ..), .. } ) { // Python 2 is never allowed. false } else if let AbiTag::CPython { python_version: (3, minor), .. } | AbiTag::PyPy { python_version: Some((3, minor)), .. } | AbiTag::GraalPy { python_version: (3, minor), .. } = abi_tag { // Ex) If the wheel bound is `3.6`, then it doesn't match `>=3.10`. let wheel_bound = LowerBound(Bound::Included(Version::new([3, u64::from(*minor)]))); if wheel_bound < self.range.lower().major_minor() { return false; } // Ex) If the wheel bound is `3.12`, then it doesn't match `<=3.10.`. let wheel_bound = UpperBound(Bound::Included(Version::new([3, u64::from(*minor)]))); if wheel_bound > self.range.upper().major_minor() { return false; } true } else { // Unknown tags are allowed. true } }) } } impl std::fmt::Display for RequiresPython { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.specifiers, f) } } impl serde::Serialize for RequiresPython { fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { self.specifiers.serialize(serializer) } } impl<'de> serde::Deserialize<'de> for RequiresPython { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { let specifiers = VersionSpecifiers::deserialize(deserializer)?; let range = release_specifiers_to_ranges(specifiers.clone()); let range = RequiresPythonRange::from_range(&range); Ok(Self { specifiers, range }) } } #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct RequiresPythonRange(LowerBound, UpperBound); impl RequiresPythonRange { /// Initialize a [`RequiresPythonRange`] from a [`Range`]. pub fn from_range(range: &Ranges<Version>) -> Self { let (lower, upper) = range .bounding_range() .map(|(lower_bound, upper_bound)| (lower_bound.cloned(), upper_bound.cloned())) .unwrap_or((Bound::Unbounded, Bound::Unbounded)); Self(LowerBound(lower), UpperBound(upper)) } /// Initialize a [`RequiresPythonRange`] with the given bounds. pub fn new(lower: LowerBound, upper: UpperBound) -> Self { Self(lower, upper) } /// Returns the lower bound. pub fn lower(&self) -> &LowerBound { &self.0 } /// Returns the upper bound. pub fn upper(&self) -> &UpperBound { &self.1 } /// Returns the [`VersionSpecifiers`] for the range. pub fn specifiers(&self) -> VersionSpecifiers { [self.0.specifier(), self.1.specifier()] .into_iter() .flatten() .collect() } } impl Default for RequiresPythonRange { fn default() -> Self { Self(LowerBound(Bound::Unbounded), UpperBound(Bound::Unbounded)) } } impl From<RequiresPythonRange> for Ranges<Version> { fn from(value: RequiresPythonRange) -> Self { Self::from_range_bounds::<(Bound<Version>, Bound<Version>), _>(( value.0.into(), value.1.into(), )) } } /// A simplified marker is just like a normal marker, except it has possibly /// been simplified by `requires-python`. /// /// A simplified marker should only exist in contexts where a `requires-python` /// setting can be assumed. In order to get a "normal" marker out of /// a simplified marker, one must re-contextualize it by adding the /// `requires-python` constraint back to the marker. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq, PartialOrd, Ord, serde::Deserialize)] pub struct SimplifiedMarkerTree(MarkerTree); impl SimplifiedMarkerTree { /// Simplifies the given markers by assuming the given `requires-python` /// bound is true. pub fn new(requires_python: &RequiresPython, marker: MarkerTree) -> Self { Self(requires_python.simplify_markers(marker)) } /// Complexifies the given markers by adding the given `requires-python` as /// a constraint to these simplified markers. pub fn into_marker(self, requires_python: &RequiresPython) -> MarkerTree { requires_python.complexify_markers(self.0) } /// Attempts to convert this simplified marker to a string. /// /// This only returns `None` when the underlying marker is always true, /// i.e., it matches all possible marker environments. pub fn try_to_string(self) -> Option<String> { self.0.try_to_string() } /// Returns the underlying marker tree without re-complexifying them. pub fn as_simplified_marker_tree(self) -> MarkerTree { self.0 } } #[cfg(test)] mod tests { use std::cmp::Ordering; use std::collections::Bound; use std::str::FromStr; use uv_distribution_filename::WheelFilename; use uv_pep440::{LowerBound, UpperBound, Version, VersionSpecifiers}; use crate::RequiresPython; #[test] fn requires_python_included() { let version_specifiers = VersionSpecifiers::from_str("==3.10.*").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &[ "bcrypt-4.1.3-cp37-abi3-macosx_10_12_universal2.whl", "black-24.4.2-cp310-cp310-win_amd64.whl", "black-24.4.2-cp310-none-win_amd64.whl", "cbor2-5.6.4-py3-none-any.whl", "solace_pubsubplus-1.8.0-py36-none-manylinux_2_12_x86_64.whl", "torch-1.10.0-py310-none-macosx_10_9_x86_64.whl", "torch-1.10.0-py37-none-macosx_10_9_x86_64.whl", "watchfiles-0.22.0-pp310-pypy310_pp73-macosx_11_0_arm64.whl", ]; for wheel_name in wheel_names { assert!( requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } let version_specifiers = VersionSpecifiers::from_str(">=3.12.3").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &["dearpygui-1.11.1-cp312-cp312-win_amd64.whl"]; for wheel_name in wheel_names { assert!( requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } let version_specifiers = VersionSpecifiers::from_str("==3.12.6").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &["lxml-5.3.0-cp312-cp312-musllinux_1_2_aarch64.whl"]; for wheel_name in wheel_names { assert!( requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } let version_specifiers = VersionSpecifiers::from_str("==3.12").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &["lxml-5.3.0-cp312-cp312-musllinux_1_2_x86_64.whl"]; for wheel_name in wheel_names { assert!( requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } } #[test] fn requires_python_dropped() { let version_specifiers = VersionSpecifiers::from_str("==3.10.*").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &[ "PySocks-1.7.1-py27-none-any.whl", "black-24.4.2-cp39-cp39-win_amd64.whl", "dearpygui-1.11.1-cp312-cp312-win_amd64.whl", "psutil-6.0.0-cp27-none-win32.whl", "psutil-6.0.0-cp36-cp36m-win32.whl", "pydantic_core-2.20.1-pp39-pypy39_pp73-win_amd64.whl", "torch-1.10.0-cp311-none-macosx_10_9_x86_64.whl", "torch-1.10.0-cp36-none-macosx_10_9_x86_64.whl", "torch-1.10.0-py311-none-macosx_10_9_x86_64.whl", ]; for wheel_name in wheel_names { assert!( !requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } let version_specifiers = VersionSpecifiers::from_str(">=3.12.3").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let wheel_names = &["dearpygui-1.11.1-cp310-cp310-win_amd64.whl"]; for wheel_name in wheel_names { assert!( !requires_python.matches_wheel_tag(&WheelFilename::from_str(wheel_name).unwrap()), "{wheel_name}" ); } } #[test] fn lower_bound_ordering() { let versions = &[ // No bound LowerBound::new(Bound::Unbounded), // >=3.8 LowerBound::new(Bound::Included(Version::new([3, 8]))), // >3.8 LowerBound::new(Bound::Excluded(Version::new([3, 8]))), // >=3.8.1 LowerBound::new(Bound::Included(Version::new([3, 8, 1]))), // >3.8.1 LowerBound::new(Bound::Excluded(Version::new([3, 8, 1]))), ]; for (i, v1) in versions.iter().enumerate() { for v2 in &versions[i + 1..] { assert_eq!(v1.cmp(v2), Ordering::Less, "less: {v1:?}\ngreater: {v2:?}"); } } } #[test] fn upper_bound_ordering() { let versions = &[ // <3.8 UpperBound::new(Bound::Excluded(Version::new([3, 8]))), // <=3.8 UpperBound::new(Bound::Included(Version::new([3, 8]))), // <3.8.1 UpperBound::new(Bound::Excluded(Version::new([3, 8, 1]))), // <=3.8.1 UpperBound::new(Bound::Included(Version::new([3, 8, 1]))), // No bound UpperBound::new(Bound::Unbounded), ]; for (i, v1) in versions.iter().enumerate() { for v2 in &versions[i + 1..] { assert_eq!(v1.cmp(v2), Ordering::Less, "less: {v1:?}\ngreater: {v2:?}"); } } } #[test] fn is_exact_without_patch() { let test_cases = [ ("==3.12", true), ("==3.10, <3.11", true), ("==3.10, <=3.11", true), ("==3.12.1", false), ("==3.12.*", false), ("==3.*", false), (">=3.10", false), (">3.9", false), ("<4.0", false), (">=3.10, <3.11", false), ("", false), ]; for (version, expected) in test_cases { let version_specifiers = VersionSpecifiers::from_str(version).unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); assert_eq!(requires_python.is_exact_without_patch(), expected); } } #[test] fn split_version() { // Splitting `>=3.10` on `>3.12` should result in `>=3.10, <=3.12` and `>3.12`. let version_specifiers = VersionSpecifiers::from_str(">=3.10").unwrap(); let requires_python = RequiresPython::from_specifiers(&version_specifiers); let (lower, upper) = requires_python .split(Bound::Excluded(Version::new([3, 12]))) .unwrap(); assert_eq!( lower,
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/dependency_metadata.rs
crates/uv-distribution-types/src/dependency_metadata.rs
use rustc_hash::FxHashMap; use serde::{Deserialize, Serialize}; use tracing::{debug, warn}; use uv_normalize::{ExtraName, PackageName}; use uv_pep440::{Version, VersionSpecifiers}; use uv_pep508::Requirement; use uv_pypi_types::{ResolutionMetadata, VerbatimParsedUrl}; /// Pre-defined [`StaticMetadata`] entries, indexed by [`PackageName`] and [`Version`]. #[derive(Debug, Clone, Default)] pub struct DependencyMetadata(FxHashMap<PackageName, Vec<StaticMetadata>>); impl DependencyMetadata { /// Index a set of [`StaticMetadata`] entries by [`PackageName`] and [`Version`]. pub fn from_entries(entries: impl IntoIterator<Item = StaticMetadata>) -> Self { let mut map = Self::default(); for entry in entries { map.0.entry(entry.name.clone()).or_default().push(entry); } map } /// Retrieve a [`StaticMetadata`] entry by [`PackageName`] and [`Version`]. pub fn get( &self, package: &PackageName, version: Option<&Version>, ) -> Option<ResolutionMetadata> { let versions = self.0.get(package)?; if let Some(version) = version { // If a specific version was requested, search for an exact match, then a global match. let metadata = if let Some(metadata) = versions .iter() .find(|entry| entry.version.as_ref() == Some(version)) { debug!("Found dependency metadata entry for `{package}=={version}`"); metadata } else if let Some(metadata) = versions.iter().find(|entry| entry.version.is_none()) { debug!("Found global metadata entry for `{package}`"); metadata } else { warn!("No dependency metadata entry found for `{package}=={version}`"); return None; }; Some(ResolutionMetadata { name: metadata.name.clone(), version: version.clone(), requires_dist: metadata.requires_dist.clone(), requires_python: metadata.requires_python.clone(), provides_extra: metadata.provides_extra.clone(), dynamic: false, }) } else { // If no version was requested (i.e., it's a direct URL dependency), allow a single // versioned match. let [metadata] = versions.as_slice() else { warn!("Multiple dependency metadata entries found for `{package}`"); return None; }; let Some(version) = metadata.version.clone() else { warn!("No version found in dependency metadata entry for `{package}`"); return None; }; debug!("Found dependency metadata entry for `{package}` (assuming: `{version}`)"); Some(ResolutionMetadata { name: metadata.name.clone(), version, requires_dist: metadata.requires_dist.clone(), requires_python: metadata.requires_python.clone(), provides_extra: metadata.provides_extra.clone(), dynamic: false, }) } } /// Retrieve all [`StaticMetadata`] entries. pub fn values(&self) -> impl Iterator<Item = &StaticMetadata> { self.0.values().flatten() } } /// A subset of the Python Package Metadata 2.3 standard as specified in /// <https://packaging.python.org/specifications/core-metadata/>. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[serde(rename_all = "kebab-case", deny_unknown_fields)] pub struct StaticMetadata { // Mandatory fields pub name: PackageName, #[cfg_attr( feature = "schemars", schemars( with = "Option<String>", description = "PEP 440-style package version, e.g., `1.2.3`" ) )] pub version: Option<Version>, // Optional fields #[serde(default)] pub requires_dist: Box<[Requirement<VerbatimParsedUrl>]>, #[cfg_attr( feature = "schemars", schemars( with = "Option<String>", description = "PEP 508-style Python requirement, e.g., `>=3.10`" ) )] pub requires_python: Option<VersionSpecifiers>, #[serde(default, alias = "provides-extras")] pub provides_extra: Box<[ExtraName]>, }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/traits.rs
crates/uv-distribution-types/src/traits.rs
use std::borrow::Cow; use uv_normalize::PackageName; use uv_pep508::VerbatimUrl; use crate::error::Error; use crate::{ BuiltDist, CachedDirectUrlDist, CachedDist, CachedRegistryDist, DirectUrlBuiltDist, DirectUrlSourceDist, DirectorySourceDist, Dist, DistributionId, GitSourceDist, InstalledDirectUrlDist, InstalledDist, InstalledEggInfoDirectory, InstalledEggInfoFile, InstalledLegacyEditable, InstalledRegistryDist, InstalledVersion, LocalDist, PackageId, PathBuiltDist, PathSourceDist, RegistryBuiltWheel, RegistrySourceDist, ResourceId, SourceDist, VersionId, VersionOrUrlRef, }; pub trait Name { /// Return the normalized [`PackageName`] of the distribution. fn name(&self) -> &PackageName; } /// Metadata that can be resolved from a requirements specification alone (i.e., prior to building /// or installing the distribution). pub trait DistributionMetadata: Name { /// Return a [`uv_pep440::Version`], for registry-based distributions, or a [`url::Url`], /// for URL-based distributions. fn version_or_url(&self) -> VersionOrUrlRef<'_>; /// Returns a unique identifier for the package at the given version (e.g., `black==23.10.0`). /// /// Note that this is not equivalent to a unique identifier for the _distribution_, as multiple /// registry-based distributions (e.g., different wheels for the same package and version) /// will return the same version ID, but different distribution IDs. fn version_id(&self) -> VersionId { match self.version_or_url() { VersionOrUrlRef::Version(version) => { VersionId::from_registry(self.name().clone(), version.clone()) } VersionOrUrlRef::Url(url) => VersionId::from_url(url), } } /// Returns a unique identifier for a package. A package can either be identified by a name /// (e.g., `black`) or a URL (e.g., `git+https://github.com/psf/black`). /// /// Note that this is not equivalent to a unique identifier for the _distribution_, as multiple /// registry-based distributions (e.g., different wheels for the same package and version) /// will return the same version ID, but different distribution IDs. fn package_id(&self) -> PackageId { match self.version_or_url() { VersionOrUrlRef::Version(_) => PackageId::from_registry(self.name().clone()), VersionOrUrlRef::Url(url) => PackageId::from_url(url), } } } /// Metadata that can be resolved from a built distribution. pub trait InstalledMetadata: Name { /// Return the resolved version of the installed distribution. fn installed_version(&self) -> InstalledVersion<'_>; } pub trait RemoteSource { /// Return an appropriate filename for the distribution. fn filename(&self) -> Result<Cow<'_, str>, Error>; /// Return the size of the distribution, if known. fn size(&self) -> Option<u64>; } pub trait Identifier { /// Return a unique resource identifier for the distribution, like a SHA-256 hash of the /// distribution's contents. /// /// A distribution is a specific archive of a package at a specific version. For a given package /// version, there may be multiple distributions, e.g., source distribution, along with /// multiple binary distributions (wheels) for different platforms. As a concrete example, /// `black-23.10.0-py3-none-any.whl` would represent a (binary) distribution of the `black` package /// at version `23.10.0`. /// /// The distribution ID is used to uniquely identify a distribution. Ideally, the distribution /// ID should be a hash of the distribution's contents, though in practice, it's only required /// that the ID is unique within a single invocation of the resolver (and so, e.g., a hash of /// the URL would also be sufficient). fn distribution_id(&self) -> DistributionId; /// Return a unique resource identifier for the underlying resource backing the distribution. /// /// This is often equivalent to the distribution ID, but may differ in some cases. For example, /// if the same Git repository is used for two different distributions, at two different /// subdirectories or two different commits, then those distributions would share a resource ID, /// but have different distribution IDs. fn resource_id(&self) -> ResourceId; } pub trait Verbatim { /// Return the verbatim representation of the distribution. fn verbatim(&self) -> Cow<'_, str>; } impl Verbatim for VerbatimUrl { fn verbatim(&self) -> Cow<'_, str> { if let Some(given) = self.given() { Cow::Borrowed(given) } else { Cow::Owned(self.to_string()) } } } impl<T: DistributionMetadata> Verbatim for T { fn verbatim(&self) -> Cow<'_, str> { Cow::Owned(format!( "{}{}", self.name(), self.version_or_url().verbatim() )) } } // Implement `Display` for all known types that implement `Metadata`. impl std::fmt::Display for LocalDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for BuiltDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for CachedDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for CachedDirectUrlDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for CachedRegistryDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for DirectUrlBuiltDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for DirectUrlSourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for Dist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for GitSourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for InstalledDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for InstalledDirectUrlDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for InstalledRegistryDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for InstalledEggInfoFile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for InstalledEggInfoDirectory { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for InstalledLegacyEditable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.installed_version()) } } impl std::fmt::Display for PathBuiltDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for PathSourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for DirectorySourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for RegistryBuiltWheel { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for RegistrySourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } } impl std::fmt::Display for SourceDist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}{}", self.name(), self.version_or_url()) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/requirement.rs
crates/uv-distribution-types/src/requirement.rs
use std::fmt::{Display, Formatter}; use std::io; use std::path::Path; use std::str::FromStr; use thiserror::Error; use uv_cache_key::{CacheKey, CacheKeyHasher}; use uv_distribution_filename::DistExtension; use uv_fs::{CWD, PortablePath, PortablePathBuf, relative_to}; use uv_git_types::{GitLfs, GitOid, GitReference, GitUrl, GitUrlParseError, OidParseError}; use uv_normalize::{ExtraName, GroupName, PackageName}; use uv_pep440::VersionSpecifiers; use uv_pep508::{ MarkerEnvironment, MarkerTree, RequirementOrigin, VerbatimUrl, VersionOrUrl, marker, }; use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError}; use crate::{IndexMetadata, IndexUrl}; use uv_pypi_types::{ ConflictItem, Hashes, ParsedArchiveUrl, ParsedDirectoryUrl, ParsedGitUrl, ParsedPathUrl, ParsedUrl, ParsedUrlError, VerbatimParsedUrl, }; #[derive(Debug, Error)] pub enum RequirementError { #[error(transparent)] VerbatimUrlError(#[from] uv_pep508::VerbatimUrlError), #[error(transparent)] ParsedUrlError(#[from] ParsedUrlError), #[error(transparent)] UrlParseError(#[from] DisplaySafeUrlError), #[error(transparent)] OidParseError(#[from] OidParseError), #[error(transparent)] GitUrlParse(#[from] GitUrlParseError), } /// A representation of dependency on a package, an extension over a PEP 508's requirement. /// /// The main change is using [`RequirementSource`] to represent all supported package sources over /// [`VersionOrUrl`], which collapses all URL sources into a single stringly type. /// /// Additionally, this requirement type makes room for dependency groups, which lack a standardized /// representation in PEP 508. In the context of this type, extras and groups are assumed to be /// mutually exclusive, in that if `extras` is non-empty, `groups` must be empty and vice versa. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct Requirement { pub name: PackageName, #[serde(skip_serializing_if = "<[ExtraName]>::is_empty", default)] pub extras: Box<[ExtraName]>, #[serde(skip_serializing_if = "<[GroupName]>::is_empty", default)] pub groups: Box<[GroupName]>, #[serde( skip_serializing_if = "marker::ser::is_empty", serialize_with = "marker::ser::serialize", default )] pub marker: MarkerTree, #[serde(flatten)] pub source: RequirementSource, #[serde(skip)] pub origin: Option<RequirementOrigin>, } impl Requirement { /// Returns whether the markers apply for the given environment. /// /// When `env` is `None`, this specifically evaluates all marker /// expressions based on the environment to `true`. That is, this provides /// environment independent marker evaluation. pub fn evaluate_markers(&self, env: Option<&MarkerEnvironment>, extras: &[ExtraName]) -> bool { self.marker.evaluate_optional_environment(env, extras) } /// Returns `true` if the requirement is editable. pub fn is_editable(&self) -> bool { self.source.is_editable() } /// Convert to a [`Requirement`] with a relative path based on the given root. pub fn relative_to(self, path: &Path) -> Result<Self, io::Error> { Ok(Self { source: self.source.relative_to(path)?, ..self }) } /// Convert to a [`Requirement`] with an absolute path based on the given root. #[must_use] pub fn to_absolute(self, path: &Path) -> Self { Self { source: self.source.to_absolute(path), ..self } } /// Return the hashes of the requirement, as specified in the URL fragment. pub fn hashes(&self) -> Option<Hashes> { let RequirementSource::Url { ref url, .. } = self.source else { return None; }; let fragment = url.fragment()?; Hashes::parse_fragment(fragment).ok() } /// Set the source file containing the requirement. #[must_use] pub fn with_origin(self, origin: RequirementOrigin) -> Self { Self { origin: Some(origin), ..self } } } impl std::hash::Hash for Requirement { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { let Self { name, extras, groups, marker, source, origin: _, } = self; name.hash(state); extras.hash(state); groups.hash(state); marker.hash(state); source.hash(state); } } impl PartialEq for Requirement { fn eq(&self, other: &Self) -> bool { let Self { name, extras, groups, marker, source, origin: _, } = self; let Self { name: other_name, extras: other_extras, groups: other_groups, marker: other_marker, source: other_source, origin: _, } = other; name == other_name && extras == other_extras && groups == other_groups && marker == other_marker && source == other_source } } impl Eq for Requirement {} impl Ord for Requirement { fn cmp(&self, other: &Self) -> std::cmp::Ordering { let Self { name, extras, groups, marker, source, origin: _, } = self; let Self { name: other_name, extras: other_extras, groups: other_groups, marker: other_marker, source: other_source, origin: _, } = other; name.cmp(other_name) .then_with(|| extras.cmp(other_extras)) .then_with(|| groups.cmp(other_groups)) .then_with(|| marker.cmp(other_marker)) .then_with(|| source.cmp(other_source)) } } impl PartialOrd for Requirement { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl From<Requirement> for uv_pep508::Requirement<VerbatimUrl> { /// Convert a [`Requirement`] to a [`uv_pep508::Requirement`]. fn from(requirement: Requirement) -> Self { Self { name: requirement.name, extras: requirement.extras, marker: requirement.marker, origin: requirement.origin, version_or_url: match requirement.source { RequirementSource::Registry { specifier, .. } => { Some(VersionOrUrl::VersionSpecifier(specifier)) } RequirementSource::Url { url, .. } | RequirementSource::Git { url, .. } | RequirementSource::Path { url, .. } | RequirementSource::Directory { url, .. } => Some(VersionOrUrl::Url(url)), }, } } } impl From<Requirement> for uv_pep508::Requirement<VerbatimParsedUrl> { /// Convert a [`Requirement`] to a [`uv_pep508::Requirement`]. fn from(requirement: Requirement) -> Self { Self { name: requirement.name, extras: requirement.extras, marker: requirement.marker, origin: requirement.origin, version_or_url: match requirement.source { RequirementSource::Registry { specifier, .. } => { Some(VersionOrUrl::VersionSpecifier(specifier)) } RequirementSource::Url { location, subdirectory, ext, url, } => Some(VersionOrUrl::Url(VerbatimParsedUrl { parsed_url: ParsedUrl::Archive(ParsedArchiveUrl { url: location, subdirectory, ext, }), verbatim: url, })), RequirementSource::Git { git, subdirectory, url, } => Some(VersionOrUrl::Url(VerbatimParsedUrl { parsed_url: ParsedUrl::Git(ParsedGitUrl { url: git, subdirectory, }), verbatim: url, })), RequirementSource::Path { install_path, ext, url, } => Some(VersionOrUrl::Url(VerbatimParsedUrl { parsed_url: ParsedUrl::Path(ParsedPathUrl { url: url.to_url(), install_path, ext, }), verbatim: url, })), RequirementSource::Directory { install_path, editable, r#virtual, url, } => Some(VersionOrUrl::Url(VerbatimParsedUrl { parsed_url: ParsedUrl::Directory(ParsedDirectoryUrl { url: url.to_url(), install_path, editable, r#virtual, }), verbatim: url, })), }, } } } impl From<uv_pep508::Requirement<VerbatimParsedUrl>> for Requirement { /// Convert a [`uv_pep508::Requirement`] to a [`Requirement`]. fn from(requirement: uv_pep508::Requirement<VerbatimParsedUrl>) -> Self { let source = match requirement.version_or_url { None => RequirementSource::Registry { specifier: VersionSpecifiers::empty(), index: None, conflict: None, }, // The most popular case: just a name, a version range and maybe extras. Some(VersionOrUrl::VersionSpecifier(specifier)) => RequirementSource::Registry { specifier, index: None, conflict: None, }, Some(VersionOrUrl::Url(url)) => { RequirementSource::from_parsed_url(url.parsed_url, url.verbatim) } }; Self { name: requirement.name, groups: Box::new([]), extras: requirement.extras, marker: requirement.marker, source, origin: requirement.origin, } } } impl Display for Requirement { /// Display the [`Requirement`], with the intention of being shown directly to a user, rather /// than for inclusion in a `requirements.txt` file. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.name)?; if !self.extras.is_empty() { write!( f, "[{}]", self.extras .iter() .map(ToString::to_string) .collect::<Vec<_>>() .join(",") )?; } match &self.source { RequirementSource::Registry { specifier, index, .. } => { write!(f, "{specifier}")?; if let Some(index) = index { write!(f, " (index: {})", index.url)?; } } RequirementSource::Url { url, .. } => { write!(f, " @ {url}")?; } RequirementSource::Git { url: _, git, subdirectory, } => { write!(f, " @ git+{}", git.repository())?; if let Some(reference) = git.reference().as_str() { write!(f, "@{reference}")?; } if let Some(subdirectory) = subdirectory { writeln!(f, "#subdirectory={}", subdirectory.display())?; } if git.lfs().enabled() { writeln!( f, "{}lfs=true", if subdirectory.is_some() { "&" } else { "#" } )?; } } RequirementSource::Path { url, .. } => { write!(f, " @ {url}")?; } RequirementSource::Directory { url, .. } => { write!(f, " @ {url}")?; } } if let Some(marker) = self.marker.contents() { write!(f, " ; {marker}")?; } Ok(()) } } impl CacheKey for Requirement { fn cache_key(&self, state: &mut CacheKeyHasher) { self.name.as_str().cache_key(state); self.groups.len().cache_key(state); for group in &self.groups { group.as_str().cache_key(state); } self.extras.len().cache_key(state); for extra in &self.extras { extra.as_str().cache_key(state); } if let Some(marker) = self.marker.contents() { 1u8.cache_key(state); marker.to_string().cache_key(state); } else { 0u8.cache_key(state); } match &self.source { RequirementSource::Registry { specifier, index, conflict: _, } => { 0u8.cache_key(state); specifier.len().cache_key(state); for spec in specifier.iter() { spec.operator().as_str().cache_key(state); spec.version().cache_key(state); } if let Some(index) = index { 1u8.cache_key(state); index.url.cache_key(state); } else { 0u8.cache_key(state); } // `conflict` is intentionally omitted } RequirementSource::Url { location, subdirectory, ext, url, } => { 1u8.cache_key(state); location.cache_key(state); if let Some(subdirectory) = subdirectory { 1u8.cache_key(state); subdirectory.display().to_string().cache_key(state); } else { 0u8.cache_key(state); } ext.name().cache_key(state); url.cache_key(state); } RequirementSource::Git { git, subdirectory, url, } => { 2u8.cache_key(state); git.to_string().cache_key(state); if let Some(subdirectory) = subdirectory { 1u8.cache_key(state); subdirectory.display().to_string().cache_key(state); } else { 0u8.cache_key(state); } if git.lfs().enabled() { 1u8.cache_key(state); } url.cache_key(state); } RequirementSource::Path { install_path, ext, url, } => { 3u8.cache_key(state); install_path.cache_key(state); ext.name().cache_key(state); url.cache_key(state); } RequirementSource::Directory { install_path, editable, r#virtual, url, } => { 4u8.cache_key(state); install_path.cache_key(state); editable.cache_key(state); r#virtual.cache_key(state); url.cache_key(state); } } // `origin` is intentionally omitted } } /// The different locations with can install a distribution from: Version specifier (from an index), /// HTTP(S) URL, git repository, and path. /// /// We store both the parsed fields (such as the plain url and the subdirectory) and the joined /// PEP 508 style url (e.g. `file:///<path>#subdirectory=<subdirectory>`) since we need both in /// different locations. #[derive( Hash, Debug, Clone, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, serde::Deserialize, )] #[serde(try_from = "RequirementSourceWire", into = "RequirementSourceWire")] pub enum RequirementSource { /// The requirement has a version specifier, such as `foo >1,<2`. Registry { specifier: VersionSpecifiers, /// Choose a version from the index at the given URL. index: Option<IndexMetadata>, /// The conflict item associated with the source, if any. conflict: Option<ConflictItem>, }, // TODO(konsti): Track and verify version specifier from `project.dependencies` matches the // version in remote location. /// A remote `http://` or `https://` URL, either a built distribution, /// e.g. `foo @ https://example.org/foo-1.0-py3-none-any.whl`, or a source distribution, /// e.g.`foo @ https://example.org/foo-1.0.zip`. Url { /// The remote location of the archive file, without subdirectory fragment. location: DisplaySafeUrl, /// For source distributions, the path to the distribution if it is not in the archive /// root. subdirectory: Option<Box<Path>>, /// The file extension, e.g. `tar.gz`, `zip`, etc. ext: DistExtension, /// The PEP 508 style URL in the format /// `<scheme>://<domain>/<path>#subdirectory=<subdirectory>`. url: VerbatimUrl, }, /// A remote Git repository, over either HTTPS or SSH. Git { /// The repository URL and reference to the commit to use. git: GitUrl, /// The path to the source distribution if it is not in the repository root. subdirectory: Option<Box<Path>>, /// The PEP 508 style url in the format /// `git+<scheme>://<domain>/<path>@<rev>#subdirectory=<subdirectory>`. url: VerbatimUrl, }, /// A local built or source distribution, either from a path or a `file://` URL. It can either /// be a binary distribution (a `.whl` file) or a source distribution archive (a `.zip` or /// `.tar.gz` file). Path { /// The absolute path to the distribution which we use for installing. install_path: Box<Path>, /// The file extension, e.g. `tar.gz`, `zip`, etc. ext: DistExtension, /// The PEP 508 style URL in the format /// `file:///<path>#subdirectory=<subdirectory>`. url: VerbatimUrl, }, /// A local source tree (a directory with a pyproject.toml in, or a legacy /// source distribution with only a setup.py but non pyproject.toml in it). Directory { /// The absolute path to the distribution which we use for installing. install_path: Box<Path>, /// For a source tree (a directory), whether to install as an editable. editable: Option<bool>, /// For a source tree (a directory), whether the project should be built and installed. r#virtual: Option<bool>, /// The PEP 508 style URL in the format /// `file:///<path>#subdirectory=<subdirectory>`. url: VerbatimUrl, }, } impl RequirementSource { /// Construct a [`RequirementSource`] for a URL source, given a URL parsed into components and /// the PEP 508 string (after the `@`) as [`VerbatimUrl`]. pub fn from_parsed_url(parsed_url: ParsedUrl, url: VerbatimUrl) -> Self { match parsed_url { ParsedUrl::Path(local_file) => Self::Path { install_path: local_file.install_path.clone(), ext: local_file.ext, url, }, ParsedUrl::Directory(directory) => Self::Directory { install_path: directory.install_path.clone(), editable: directory.editable, r#virtual: directory.r#virtual, url, }, ParsedUrl::Git(git) => Self::Git { git: git.url.clone(), url, subdirectory: git.subdirectory, }, ParsedUrl::Archive(archive) => Self::Url { url, location: archive.url, subdirectory: archive.subdirectory, ext: archive.ext, }, } } /// Convert the source to a [`VerbatimParsedUrl`], if it's a URL source. pub fn to_verbatim_parsed_url(&self) -> Option<VerbatimParsedUrl> { match self { Self::Registry { .. } => None, Self::Url { location, subdirectory, ext, url, } => Some(VerbatimParsedUrl { parsed_url: ParsedUrl::Archive(ParsedArchiveUrl::from_source( location.clone(), subdirectory.clone(), *ext, )), verbatim: url.clone(), }), Self::Path { install_path, ext, url, } => Some(VerbatimParsedUrl { parsed_url: ParsedUrl::Path(ParsedPathUrl::from_source( install_path.clone(), *ext, url.to_url(), )), verbatim: url.clone(), }), Self::Directory { install_path, editable, r#virtual, url, } => Some(VerbatimParsedUrl { parsed_url: ParsedUrl::Directory(ParsedDirectoryUrl::from_source( install_path.clone(), *editable, *r#virtual, url.to_url(), )), verbatim: url.clone(), }), Self::Git { git, subdirectory, url, } => Some(VerbatimParsedUrl { parsed_url: ParsedUrl::Git(ParsedGitUrl::from_source( git.clone(), subdirectory.clone(), )), verbatim: url.clone(), }), } } /// Convert the source to a version specifier or URL. /// /// If the source is a registry and the specifier is empty, it returns `None`. pub fn version_or_url(&self) -> Option<VersionOrUrl<VerbatimParsedUrl>> { match self { Self::Registry { specifier, .. } => { if specifier.is_empty() { None } else { Some(VersionOrUrl::VersionSpecifier(specifier.clone())) } } Self::Url { .. } | Self::Git { .. } | Self::Path { .. } | Self::Directory { .. } => { Some(VersionOrUrl::Url(self.to_verbatim_parsed_url()?)) } } } /// Returns `true` if the source is editable. pub fn is_editable(&self) -> bool { matches!( self, Self::Directory { editable: Some(true), .. } ) } /// Returns `true` if the source is empty. pub fn is_empty(&self) -> bool { match self { Self::Registry { specifier, .. } => specifier.is_empty(), Self::Url { .. } | Self::Git { .. } | Self::Path { .. } | Self::Directory { .. } => { false } } } /// If the source is the registry, return the version specifiers pub fn version_specifiers(&self) -> Option<&VersionSpecifiers> { match self { Self::Registry { specifier, .. } => Some(specifier), Self::Url { .. } | Self::Git { .. } | Self::Path { .. } | Self::Directory { .. } => { None } } } /// Convert the source to a [`RequirementSource`] relative to the given path. pub fn relative_to(self, path: &Path) -> Result<Self, io::Error> { match self { Self::Registry { .. } | Self::Url { .. } | Self::Git { .. } => Ok(self), Self::Path { install_path, ext, url, } => Ok(Self::Path { install_path: relative_to(&install_path, path) .or_else(|_| std::path::absolute(install_path))? .into_boxed_path(), ext, url, }), Self::Directory { install_path, editable, r#virtual, url, .. } => Ok(Self::Directory { install_path: relative_to(&install_path, path) .or_else(|_| std::path::absolute(install_path))? .into_boxed_path(), editable, r#virtual, url, }), } } /// Convert the source to a [`RequirementSource`] with an absolute path based on the given root. #[must_use] pub fn to_absolute(self, root: &Path) -> Self { match self { Self::Registry { .. } | Self::Url { .. } | Self::Git { .. } => self, Self::Path { install_path, ext, url, } => Self::Path { install_path: uv_fs::normalize_path_buf(root.join(install_path)).into_boxed_path(), ext, url, }, Self::Directory { install_path, editable, r#virtual, url, .. } => Self::Directory { install_path: uv_fs::normalize_path_buf(root.join(install_path)).into_boxed_path(), editable, r#virtual, url, }, } } } impl Display for RequirementSource { /// Display the [`RequirementSource`], with the intention of being shown directly to a user, /// rather than for inclusion in a `requirements.txt` file. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Registry { specifier, index, .. } => { write!(f, "{specifier}")?; if let Some(index) = index { write!(f, " (index: {})", index.url)?; } } Self::Url { url, .. } => { write!(f, " {url}")?; } Self::Git { url: _, git, subdirectory, } => { write!(f, " git+{}", git.repository())?; if let Some(reference) = git.reference().as_str() { write!(f, "@{reference}")?; } if let Some(subdirectory) = subdirectory { writeln!(f, "#subdirectory={}", subdirectory.display())?; } if git.lfs().enabled() { writeln!( f, "{}lfs=true", if subdirectory.is_some() { "&" } else { "#" } )?; } } Self::Path { url, .. } => { write!(f, "{url}")?; } Self::Directory { url, .. } => { write!(f, "{url}")?; } } Ok(()) } } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(untagged)] enum RequirementSourceWire { /// Ex) `source = { git = "<https://github.com/astral-test/uv-public-pypackage?rev=0.0.1#0dacfd662c64cb4ceb16e6cf65a157a8b715b979>" }` Git { git: String }, /// Ex) `source = { url = "<https://example.org/foo-1.0.zip>" }` Direct { url: DisplaySafeUrl, subdirectory: Option<PortablePathBuf>, }, /// Ex) `source = { path = "/home/ferris/iniconfig-2.0.0-py3-none-any.whl" }` Path { path: PortablePathBuf }, /// Ex) `source = { directory = "/home/ferris/iniconfig" }` Directory { directory: PortablePathBuf }, /// Ex) `source = { editable = "/home/ferris/iniconfig" }` Editable { editable: PortablePathBuf }, /// Ex) `source = { editable = "/home/ferris/iniconfig" }` Virtual { r#virtual: PortablePathBuf }, /// Ex) `source = { specifier = "foo >1,<2" }` Registry { #[serde(skip_serializing_if = "VersionSpecifiers::is_empty", default)] specifier: VersionSpecifiers, index: Option<DisplaySafeUrl>, conflict: Option<ConflictItem>, }, } impl From<RequirementSource> for RequirementSourceWire { fn from(value: RequirementSource) -> Self { match value { RequirementSource::Registry { specifier, index, conflict, } => { let index = index.map(|index| index.url.into_url()).map(|mut index| { index.remove_credentials(); index }); Self::Registry { specifier, index, conflict, } } RequirementSource::Url { subdirectory, location, ext: _, url: _, } => Self::Direct { url: location, subdirectory: subdirectory.map(PortablePathBuf::from), }, RequirementSource::Git { git, subdirectory, url: _, } => { let mut url = git.repository().clone(); // Remove the credentials. url.remove_credentials(); // Clear out any existing state. url.set_fragment(None); url.set_query(None); // Put the subdirectory in the query. if let Some(subdirectory) = subdirectory .as_deref() .map(PortablePath::from) .as_ref() .map(PortablePath::to_string) { url.query_pairs_mut() .append_pair("subdirectory", &subdirectory); } // Persist lfs=true in the distribution metadata only when explicitly enabled. if git.lfs().enabled() { url.query_pairs_mut().append_pair("lfs", "true"); } // Put the requested reference in the query. match git.reference() { GitReference::Branch(branch) => { url.query_pairs_mut().append_pair("branch", branch.as_str()); } GitReference::Tag(tag) => { url.query_pairs_mut().append_pair("tag", tag.as_str()); } GitReference::BranchOrTag(rev) | GitReference::BranchOrTagOrCommit(rev) | GitReference::NamedRef(rev) => { url.query_pairs_mut().append_pair("rev", rev.as_str()); } GitReference::DefaultBranch => {} } // Put the precise commit in the fragment. if let Some(precise) = git.precise() { url.set_fragment(Some(&precise.to_string())); } Self::Git { git: url.to_string(), } } RequirementSource::Path { install_path, ext: _, url: _, } => Self::Path { path: PortablePathBuf::from(install_path), }, RequirementSource::Directory { install_path, editable, r#virtual, url: _, } => { if editable.unwrap_or(false) { Self::Editable { editable: PortablePathBuf::from(install_path), } } else if r#virtual.unwrap_or(false) { Self::Virtual { r#virtual: PortablePathBuf::from(install_path), } } else { Self::Directory { directory: PortablePathBuf::from(install_path), } } } } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/installed.rs
crates/uv-distribution-types/src/installed.rs
use std::borrow::Cow; use std::io::BufReader; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::OnceLock; use fs_err as fs; use thiserror::Error; use tracing::warn; use url::Url; use uv_cache_info::CacheInfo; use uv_distribution_filename::{EggInfoFilename, ExpandedTags}; use uv_fs::Simplified; use uv_install_wheel::WheelFile; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pypi_types::{DirectUrl, MetadataError}; use uv_redacted::DisplaySafeUrl; use crate::{ BuildInfo, DistributionMetadata, InstalledMetadata, InstalledVersion, Name, VersionOrUrlRef, }; #[derive(Error, Debug)] pub enum InstalledDistError { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] UrlParse(#[from] url::ParseError), #[error(transparent)] Json(#[from] serde_json::Error), #[error(transparent)] EggInfoParse(#[from] uv_distribution_filename::EggInfoFilenameError), #[error(transparent)] VersionParse(#[from] uv_pep440::VersionParseError), #[error(transparent)] PackageNameParse(#[from] uv_normalize::InvalidNameError), #[error(transparent)] WheelFileParse(#[from] uv_install_wheel::Error), #[error(transparent)] ExpandedTagParse(#[from] uv_distribution_filename::ExpandedTagError), #[error("Invalid .egg-link path: `{}`", _0.user_display())] InvalidEggLinkPath(PathBuf), #[error("Invalid .egg-link target: `{}`", _0.user_display())] InvalidEggLinkTarget(PathBuf), #[error("Failed to parse METADATA file: `{}`", path.user_display())] MetadataParse { path: PathBuf, #[source] err: Box<MetadataError>, }, #[error("Failed to parse `PKG-INFO` file: `{}`", path.user_display())] PkgInfoParse { path: PathBuf, #[source] err: Box<MetadataError>, }, } #[derive(Debug, Clone)] pub struct InstalledDist { pub kind: InstalledDistKind, // Cache data that must be read from the `.dist-info` directory. These are safe to cache as // the `InstalledDist` is immutable after creation. metadata_cache: OnceLock<uv_pypi_types::ResolutionMetadata>, tags_cache: OnceLock<Option<ExpandedTags>>, } impl From<InstalledDistKind> for InstalledDist { fn from(kind: InstalledDistKind) -> Self { Self { kind, metadata_cache: OnceLock::new(), tags_cache: OnceLock::new(), } } } impl std::hash::Hash for InstalledDist { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.kind.hash(state); } } impl PartialEq for InstalledDist { fn eq(&self, other: &Self) -> bool { self.kind == other.kind } } impl Eq for InstalledDist {} /// A built distribution (wheel) that is installed in a virtual environment. #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub enum InstalledDistKind { /// The distribution was derived from a registry, like `PyPI`. Registry(InstalledRegistryDist), /// The distribution was derived from an arbitrary URL. Url(InstalledDirectUrlDist), /// The distribution was derived from pre-existing `.egg-info` file (as installed by distutils). EggInfoFile(InstalledEggInfoFile), /// The distribution was derived from pre-existing `.egg-info` directory. EggInfoDirectory(InstalledEggInfoDirectory), /// The distribution was derived from an `.egg-link` pointer. LegacyEditable(InstalledLegacyEditable), } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct InstalledRegistryDist { pub name: PackageName, pub version: Version, pub path: Box<Path>, pub cache_info: Option<CacheInfo>, pub build_info: Option<BuildInfo>, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct InstalledDirectUrlDist { pub name: PackageName, pub version: Version, pub direct_url: Box<DirectUrl>, pub url: DisplaySafeUrl, pub editable: bool, pub path: Box<Path>, pub cache_info: Option<CacheInfo>, pub build_info: Option<BuildInfo>, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct InstalledEggInfoFile { pub name: PackageName, pub version: Version, pub path: Box<Path>, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct InstalledEggInfoDirectory { pub name: PackageName, pub version: Version, pub path: Box<Path>, } #[derive(Debug, Clone, Hash, PartialEq, Eq)] pub struct InstalledLegacyEditable { pub name: PackageName, pub version: Version, pub egg_link: Box<Path>, pub target: Box<Path>, pub target_url: DisplaySafeUrl, pub egg_info: Box<Path>, } impl InstalledDist { /// Try to parse a distribution from a `.dist-info` directory name (like `django-5.0a1.dist-info`). /// /// See: <https://packaging.python.org/en/latest/specifications/recording-installed-packages/#recording-installed-packages> pub fn try_from_path(path: &Path) -> Result<Option<Self>, InstalledDistError> { // Ex) `cffi-1.16.0.dist-info` if path.extension().is_some_and(|ext| ext == "dist-info") { let Some(file_stem) = path.file_stem() else { return Ok(None); }; let Some(file_stem) = file_stem.to_str() else { return Ok(None); }; let Some((name, version)) = file_stem.split_once('-') else { return Ok(None); }; let name = PackageName::from_str(name)?; let version = Version::from_str(version)?; let cache_info = Self::read_cache_info(path)?; let build_info = Self::read_build_info(path)?; return if let Some(direct_url) = Self::read_direct_url(path)? { match DisplaySafeUrl::try_from(&direct_url) { Ok(url) => Ok(Some(Self::from(InstalledDistKind::Url( InstalledDirectUrlDist { name, version, editable: matches!(&direct_url, DirectUrl::LocalDirectory { dir_info, .. } if dir_info.editable == Some(true)), direct_url: Box::new(direct_url), url, path: path.to_path_buf().into_boxed_path(), cache_info, build_info, }, )))), Err(err) => { warn!("Failed to parse direct URL: {err}"); Ok(Some(Self::from(InstalledDistKind::Registry( InstalledRegistryDist { name, version, path: path.to_path_buf().into_boxed_path(), cache_info, build_info, }, )))) } } } else { Ok(Some(Self::from(InstalledDistKind::Registry( InstalledRegistryDist { name, version, path: path.to_path_buf().into_boxed_path(), cache_info, build_info, }, )))) }; } // Ex) `zstandard-0.22.0-py3.12.egg-info` or `vtk-9.2.6.egg-info` if path.extension().is_some_and(|ext| ext == "egg-info") { let metadata = match fs_err::metadata(path) { Ok(metadata) => metadata, Err(err) => { warn!("Invalid `.egg-info` path: {err}"); return Ok(None); } }; let Some(file_stem) = path.file_stem() else { return Ok(None); }; let Some(file_stem) = file_stem.to_str() else { return Ok(None); }; let file_name = EggInfoFilename::parse(file_stem)?; if let Some(version) = file_name.version { if metadata.is_dir() { return Ok(Some(Self::from(InstalledDistKind::EggInfoDirectory( InstalledEggInfoDirectory { name: file_name.name, version, path: path.to_path_buf().into_boxed_path(), }, )))); } if metadata.is_file() { return Ok(Some(Self::from(InstalledDistKind::EggInfoFile( InstalledEggInfoFile { name: file_name.name, version, path: path.to_path_buf().into_boxed_path(), }, )))); } } if metadata.is_dir() { let Some(egg_metadata) = read_metadata(&path.join("PKG-INFO")) else { return Ok(None); }; return Ok(Some(Self::from(InstalledDistKind::EggInfoDirectory( InstalledEggInfoDirectory { name: file_name.name, version: Version::from_str(&egg_metadata.version)?, path: path.to_path_buf().into_boxed_path(), }, )))); } if metadata.is_file() { let Some(egg_metadata) = read_metadata(path) else { return Ok(None); }; return Ok(Some(Self::from(InstalledDistKind::EggInfoDirectory( InstalledEggInfoDirectory { name: file_name.name, version: Version::from_str(&egg_metadata.version)?, path: path.to_path_buf().into_boxed_path(), }, )))); } } // Ex) `zstandard.egg-link` if path.extension().is_some_and(|ext| ext == "egg-link") { let Some(file_stem) = path.file_stem() else { return Ok(None); }; let Some(file_stem) = file_stem.to_str() else { return Ok(None); }; // https://setuptools.pypa.io/en/latest/deprecated/python_eggs.html#egg-links // https://github.com/pypa/pip/blob/946f95d17431f645da8e2e0bf4054a72db5be766/src/pip/_internal/metadata/importlib/_envs.py#L86-L108 let contents = fs::read_to_string(path)?; let Some(target) = contents.lines().find_map(|line| { let line = line.trim(); if line.is_empty() { None } else { Some(PathBuf::from(line)) } }) else { warn!("Invalid `.egg-link` file: {path:?}"); return Ok(None); }; // Match pip, but note setuptools only puts absolute paths in `.egg-link` files. let target = path .parent() .ok_or_else(|| InstalledDistError::InvalidEggLinkPath(path.to_path_buf()))? .join(target); // Normalisation comes from `pkg_resources.to_filename`. let egg_info = target.join(file_stem.replace('-', "_") + ".egg-info"); let url = DisplaySafeUrl::from_file_path(&target) .map_err(|()| InstalledDistError::InvalidEggLinkTarget(path.to_path_buf()))?; // Mildly unfortunate that we must read metadata to get the version. let Some(egg_metadata) = read_metadata(&egg_info.join("PKG-INFO")) else { return Ok(None); }; return Ok(Some(Self::from(InstalledDistKind::LegacyEditable( InstalledLegacyEditable { name: egg_metadata.name, version: Version::from_str(&egg_metadata.version)?, egg_link: path.to_path_buf().into_boxed_path(), target: target.into_boxed_path(), target_url: url, egg_info: egg_info.into_boxed_path(), }, )))); } Ok(None) } /// Return the [`Path`] at which the distribution is stored on-disk. pub fn install_path(&self) -> &Path { match &self.kind { InstalledDistKind::Registry(dist) => &dist.path, InstalledDistKind::Url(dist) => &dist.path, InstalledDistKind::EggInfoDirectory(dist) => &dist.path, InstalledDistKind::EggInfoFile(dist) => &dist.path, InstalledDistKind::LegacyEditable(dist) => &dist.egg_info, } } /// Return the [`Version`] of the distribution. pub fn version(&self) -> &Version { match &self.kind { InstalledDistKind::Registry(dist) => &dist.version, InstalledDistKind::Url(dist) => &dist.version, InstalledDistKind::EggInfoDirectory(dist) => &dist.version, InstalledDistKind::EggInfoFile(dist) => &dist.version, InstalledDistKind::LegacyEditable(dist) => &dist.version, } } /// Return the [`CacheInfo`] of the distribution, if any. pub fn cache_info(&self) -> Option<&CacheInfo> { match &self.kind { InstalledDistKind::Registry(dist) => dist.cache_info.as_ref(), InstalledDistKind::Url(dist) => dist.cache_info.as_ref(), InstalledDistKind::EggInfoDirectory(..) => None, InstalledDistKind::EggInfoFile(..) => None, InstalledDistKind::LegacyEditable(..) => None, } } /// Return the [`BuildInfo`] of the distribution, if any. pub fn build_info(&self) -> Option<&BuildInfo> { match &self.kind { InstalledDistKind::Registry(dist) => dist.build_info.as_ref(), InstalledDistKind::Url(dist) => dist.build_info.as_ref(), InstalledDistKind::EggInfoDirectory(..) => None, InstalledDistKind::EggInfoFile(..) => None, InstalledDistKind::LegacyEditable(..) => None, } } /// Read the `direct_url.json` file from a `.dist-info` directory. pub fn read_direct_url(path: &Path) -> Result<Option<DirectUrl>, InstalledDistError> { let path = path.join("direct_url.json"); let file = match fs_err::File::open(&path) { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(err) => return Err(err.into()), }; let direct_url = serde_json::from_reader::<BufReader<fs_err::File>, DirectUrl>(BufReader::new(file))?; Ok(Some(direct_url)) } /// Read the `uv_cache.json` file from a `.dist-info` directory. pub fn read_cache_info(path: &Path) -> Result<Option<CacheInfo>, InstalledDistError> { let path = path.join("uv_cache.json"); let file = match fs_err::File::open(&path) { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(err) => return Err(err.into()), }; let cache_info = serde_json::from_reader::<BufReader<fs_err::File>, CacheInfo>(BufReader::new(file))?; Ok(Some(cache_info)) } /// Read the `uv_build.json` file from a `.dist-info` directory. pub fn read_build_info(path: &Path) -> Result<Option<BuildInfo>, InstalledDistError> { let path = path.join("uv_build.json"); let file = match fs_err::File::open(&path) { Ok(file) => file, Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(err) => return Err(err.into()), }; let build_info = serde_json::from_reader::<BufReader<fs_err::File>, BuildInfo>(BufReader::new(file))?; Ok(Some(build_info)) } /// Read the `METADATA` file from a `.dist-info` directory. pub fn read_metadata(&self) -> Result<&uv_pypi_types::ResolutionMetadata, InstalledDistError> { if let Some(metadata) = self.metadata_cache.get() { return Ok(metadata); } let metadata = match &self.kind { InstalledDistKind::Registry(_) | InstalledDistKind::Url(_) => { let path = self.install_path().join("METADATA"); let contents = fs::read(&path)?; // TODO(zanieb): Update this to use thiserror so we can unpack parse errors downstream uv_pypi_types::ResolutionMetadata::parse_metadata(&contents).map_err(|err| { InstalledDistError::MetadataParse { path: path.clone(), err: Box::new(err), } })? } InstalledDistKind::EggInfoFile(_) | InstalledDistKind::EggInfoDirectory(_) | InstalledDistKind::LegacyEditable(_) => { let path = match &self.kind { InstalledDistKind::EggInfoFile(dist) => Cow::Borrowed(&*dist.path), InstalledDistKind::EggInfoDirectory(dist) => { Cow::Owned(dist.path.join("PKG-INFO")) } InstalledDistKind::LegacyEditable(dist) => { Cow::Owned(dist.egg_info.join("PKG-INFO")) } _ => unreachable!(), }; let contents = fs::read(path.as_ref())?; uv_pypi_types::ResolutionMetadata::parse_metadata(&contents).map_err(|err| { InstalledDistError::PkgInfoParse { path: path.to_path_buf(), err: Box::new(err), } })? } }; let _ = self.metadata_cache.set(metadata); Ok(self.metadata_cache.get().expect("metadata should be set")) } /// Return the `INSTALLER` of the distribution. pub fn read_installer(&self) -> Result<Option<String>, InstalledDistError> { let path = self.install_path().join("INSTALLER"); match fs::read_to_string(path) { Ok(installer) => Ok(Some(installer.trim().to_owned())), Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(err) => Err(err.into()), } } /// Return the supported wheel tags for the distribution from the `WHEEL` file, if available. pub fn read_tags(&self) -> Result<Option<&ExpandedTags>, InstalledDistError> { if let Some(tags) = self.tags_cache.get() { return Ok(tags.as_ref()); } let path = match &self.kind { InstalledDistKind::Registry(dist) => &dist.path, InstalledDistKind::Url(dist) => &dist.path, InstalledDistKind::EggInfoFile(_) => return Ok(None), InstalledDistKind::EggInfoDirectory(_) => return Ok(None), InstalledDistKind::LegacyEditable(_) => return Ok(None), }; // Read the `WHEEL` file. let contents = fs_err::read_to_string(path.join("WHEEL"))?; let wheel_file = WheelFile::parse(&contents)?; // Parse the tags. let tags = if let Some(tags) = wheel_file.tags() { Some(ExpandedTags::parse(tags.iter().map(String::as_str))?) } else { None }; let _ = self.tags_cache.set(tags); Ok(self.tags_cache.get().expect("tags should be set").as_ref()) } /// Return true if the distribution is editable. pub fn is_editable(&self) -> bool { matches!( &self.kind, InstalledDistKind::LegacyEditable(_) | InstalledDistKind::Url(InstalledDirectUrlDist { editable: true, .. }) ) } /// Return the [`Url`] of the distribution, if it is editable. pub fn as_editable(&self) -> Option<&Url> { match &self.kind { InstalledDistKind::Registry(_) => None, InstalledDistKind::Url(dist) => dist.editable.then_some(&dist.url), InstalledDistKind::EggInfoFile(_) => None, InstalledDistKind::EggInfoDirectory(_) => None, InstalledDistKind::LegacyEditable(dist) => Some(&dist.target_url), } } /// Return true if the distribution refers to a local file or directory. pub fn is_local(&self) -> bool { match &self.kind { InstalledDistKind::Registry(_) => false, InstalledDistKind::Url(dist) => { matches!(&*dist.direct_url, DirectUrl::LocalDirectory { .. }) } InstalledDistKind::EggInfoFile(_) => false, InstalledDistKind::EggInfoDirectory(_) => false, InstalledDistKind::LegacyEditable(_) => true, } } } impl DistributionMetadata for InstalledDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { VersionOrUrlRef::Version(self.version()) } } impl Name for InstalledRegistryDist { fn name(&self) -> &PackageName { &self.name } } impl Name for InstalledDirectUrlDist { fn name(&self) -> &PackageName { &self.name } } impl Name for InstalledEggInfoFile { fn name(&self) -> &PackageName { &self.name } } impl Name for InstalledEggInfoDirectory { fn name(&self) -> &PackageName { &self.name } } impl Name for InstalledLegacyEditable { fn name(&self) -> &PackageName { &self.name } } impl Name for InstalledDist { fn name(&self) -> &PackageName { match &self.kind { InstalledDistKind::Registry(dist) => dist.name(), InstalledDistKind::Url(dist) => dist.name(), InstalledDistKind::EggInfoDirectory(dist) => dist.name(), InstalledDistKind::EggInfoFile(dist) => dist.name(), InstalledDistKind::LegacyEditable(dist) => dist.name(), } } } impl InstalledMetadata for InstalledRegistryDist { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Version(&self.version) } } impl InstalledMetadata for InstalledDirectUrlDist { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Url(&self.url, &self.version) } } impl InstalledMetadata for InstalledEggInfoFile { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Version(&self.version) } } impl InstalledMetadata for InstalledEggInfoDirectory { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Version(&self.version) } } impl InstalledMetadata for InstalledLegacyEditable { fn installed_version(&self) -> InstalledVersion<'_> { InstalledVersion::Version(&self.version) } } impl InstalledMetadata for InstalledDist { fn installed_version(&self) -> InstalledVersion<'_> { match &self.kind { InstalledDistKind::Registry(dist) => dist.installed_version(), InstalledDistKind::Url(dist) => dist.installed_version(), InstalledDistKind::EggInfoFile(dist) => dist.installed_version(), InstalledDistKind::EggInfoDirectory(dist) => dist.installed_version(), InstalledDistKind::LegacyEditable(dist) => dist.installed_version(), } } } fn read_metadata(path: &Path) -> Option<uv_pypi_types::Metadata10> { let content = match fs::read(path) { Ok(content) => content, Err(err) => { warn!("Failed to read metadata for {path:?}: {err}"); return None; } }; let metadata = match uv_pypi_types::Metadata10::parse_pkg_info(&content) { Ok(metadata) => metadata, Err(err) => { warn!("Failed to parse metadata for {path:?}: {err}"); return None; } }; Some(metadata) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/resolved.rs
crates/uv-distribution-types/src/resolved.rs
use std::fmt::{Display, Formatter}; use std::path::Path; use std::sync::Arc; use uv_normalize::PackageName; use uv_pep440::Version; use uv_pypi_types::Yanked; use crate::{ BuiltDist, Dist, DistributionId, DistributionMetadata, Identifier, IndexUrl, InstalledDist, Name, PrioritizedDist, RegistryBuiltWheel, RegistrySourceDist, ResourceId, SourceDist, VersionOrUrlRef, }; /// A distribution that can be used for resolution and installation. /// /// Either an already-installed distribution or a distribution that can be installed. #[derive(Debug, Clone, Hash)] #[allow(clippy::large_enum_variant)] pub enum ResolvedDist { Installed { dist: Arc<InstalledDist>, }, Installable { dist: Arc<Dist>, version: Option<Version>, }, } /// A variant of [`ResolvedDist`] with borrowed inner distributions. #[derive(Debug, Clone)] pub enum ResolvedDistRef<'a> { Installed { dist: &'a InstalledDist, }, InstallableRegistrySourceDist { /// The source distribution that should be used. sdist: &'a RegistrySourceDist, /// The prioritized distribution that the wheel came from. prioritized: &'a PrioritizedDist, }, InstallableRegistryBuiltDist { /// The wheel that should be used. wheel: &'a RegistryBuiltWheel, /// The prioritized distribution that the wheel came from. prioritized: &'a PrioritizedDist, }, } impl ResolvedDist { /// Return true if the distribution is editable. pub fn is_editable(&self) -> bool { match self { Self::Installable { dist, .. } => dist.is_editable(), Self::Installed { dist } => dist.is_editable(), } } /// Return true if the distribution refers to a local file or directory. pub fn is_local(&self) -> bool { match self { Self::Installable { dist, .. } => dist.is_local(), Self::Installed { dist } => dist.is_local(), } } /// Returns the [`IndexUrl`], if the distribution is from a registry. pub fn index(&self) -> Option<&IndexUrl> { match self { Self::Installable { dist, .. } => dist.index(), Self::Installed { .. } => None, } } /// Returns the [`Yanked`] status of the distribution, if available. pub fn yanked(&self) -> Option<&Yanked> { match self { Self::Installable { dist, .. } => match dist.as_ref() { Dist::Source(SourceDist::Registry(sdist)) => sdist.file.yanked.as_deref(), Dist::Built(BuiltDist::Registry(wheel)) => { wheel.best_wheel().file.yanked.as_deref() } _ => None, }, Self::Installed { .. } => None, } } /// Returns the version of the distribution, if available. pub fn version(&self) -> Option<&Version> { match self { Self::Installable { version, dist } => dist.version().or(version.as_ref()), Self::Installed { dist } => Some(dist.version()), } } /// Return the source tree of the distribution, if available. pub fn source_tree(&self) -> Option<&Path> { match self { Self::Installable { dist, .. } => dist.source_tree(), Self::Installed { .. } => None, } } } impl ResolvedDistRef<'_> { pub fn to_owned(&self) -> ResolvedDist { match self { Self::InstallableRegistrySourceDist { sdist, prioritized } => { // This is okay because we're only here if the prioritized dist // has an sdist, so this always succeeds. let source = prioritized.source_dist().expect("a source distribution"); assert_eq!( (&sdist.name, &sdist.version), (&source.name, &source.version), "expected chosen sdist to match prioritized sdist" ); ResolvedDist::Installable { dist: Arc::new(Dist::Source(SourceDist::Registry(source))), version: Some(sdist.version.clone()), } } Self::InstallableRegistryBuiltDist { wheel, prioritized, .. } => { assert_eq!( Some(&wheel.filename), prioritized.best_wheel().map(|(wheel, _)| &wheel.filename), "expected chosen wheel to match best wheel" ); // This is okay because we're only here if the prioritized dist // has at least one wheel, so this always succeeds. let built = prioritized.built_dist().expect("at least one wheel"); ResolvedDist::Installable { dist: Arc::new(Dist::Built(BuiltDist::Registry(built))), version: Some(wheel.filename.version.clone()), } } Self::Installed { dist } => ResolvedDist::Installed { dist: Arc::new((*dist).clone()), }, } } /// Returns the [`IndexUrl`], if the distribution is from a registry. pub fn index(&self) -> Option<&IndexUrl> { match self { Self::InstallableRegistrySourceDist { sdist, .. } => Some(&sdist.index), Self::InstallableRegistryBuiltDist { wheel, .. } => Some(&wheel.index), Self::Installed { .. } => None, } } } impl Display for ResolvedDistRef<'_> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::InstallableRegistrySourceDist { sdist, .. } => Display::fmt(sdist, f), Self::InstallableRegistryBuiltDist { wheel, .. } => Display::fmt(wheel, f), Self::Installed { dist } => Display::fmt(dist, f), } } } impl Name for ResolvedDistRef<'_> { fn name(&self) -> &PackageName { match self { Self::InstallableRegistrySourceDist { sdist, .. } => sdist.name(), Self::InstallableRegistryBuiltDist { wheel, .. } => wheel.name(), Self::Installed { dist } => dist.name(), } } } impl DistributionMetadata for ResolvedDistRef<'_> { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Installed { dist } => VersionOrUrlRef::Version(dist.version()), Self::InstallableRegistrySourceDist { sdist, .. } => sdist.version_or_url(), Self::InstallableRegistryBuiltDist { wheel, .. } => wheel.version_or_url(), } } } impl Identifier for ResolvedDistRef<'_> { fn distribution_id(&self) -> DistributionId { match self { Self::Installed { dist } => dist.distribution_id(), Self::InstallableRegistrySourceDist { sdist, .. } => sdist.distribution_id(), Self::InstallableRegistryBuiltDist { wheel, .. } => wheel.distribution_id(), } } fn resource_id(&self) -> ResourceId { match self { Self::Installed { dist } => dist.resource_id(), Self::InstallableRegistrySourceDist { sdist, .. } => sdist.resource_id(), Self::InstallableRegistryBuiltDist { wheel, .. } => wheel.resource_id(), } } } impl Name for ResolvedDist { fn name(&self) -> &PackageName { match self { Self::Installable { dist, .. } => dist.name(), Self::Installed { dist } => dist.name(), } } } impl DistributionMetadata for ResolvedDist { fn version_or_url(&self) -> VersionOrUrlRef<'_> { match self { Self::Installed { dist } => dist.version_or_url(), Self::Installable { dist, .. } => dist.version_or_url(), } } } impl Identifier for ResolvedDist { fn distribution_id(&self) -> DistributionId { match self { Self::Installed { dist } => dist.distribution_id(), Self::Installable { dist, .. } => dist.distribution_id(), } } fn resource_id(&self) -> ResourceId { match self { Self::Installed { dist } => dist.resource_id(), Self::Installable { dist, .. } => dist.resource_id(), } } } impl Display for ResolvedDist { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Installed { dist } => dist.fmt(f), Self::Installable { dist, .. } => dist.fmt(f), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-distribution-types/src/diagnostic.rs
crates/uv-distribution-types/src/diagnostic.rs
use uv_normalize::PackageName; pub trait Diagnostic { /// Convert the diagnostic into a user-facing message. fn message(&self) -> String; /// Returns `true` if the [`PackageName`] is involved in this diagnostic. fn includes(&self, name: &PackageName) -> bool; }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-warnings/src/lib.rs
crates/uv-warnings/src/lib.rs
use std::error::Error; use std::iter; use std::sync::atomic::AtomicBool; use std::sync::{LazyLock, Mutex}; // macro hygiene: The user might not have direct dependencies on those crates #[doc(hidden)] pub use anstream; #[doc(hidden)] pub use owo_colors; use owo_colors::{DynColor, OwoColorize}; use rustc_hash::FxHashSet; /// Whether user-facing warnings are enabled. pub static ENABLED: AtomicBool = AtomicBool::new(false); /// Enable user-facing warnings. pub fn enable() { ENABLED.store(true, std::sync::atomic::Ordering::Relaxed); } /// Disable user-facing warnings. pub fn disable() { ENABLED.store(false, std::sync::atomic::Ordering::Relaxed); } /// Warn a user, if warnings are enabled. #[macro_export] macro_rules! warn_user { ($($arg:tt)*) => {{ use $crate::anstream::eprintln; use $crate::owo_colors::OwoColorize; if $crate::ENABLED.load(std::sync::atomic::Ordering::Relaxed) { let message = format!("{}", format_args!($($arg)*)); let formatted = message.bold(); eprintln!("{}{} {formatted}", "warning".yellow().bold(), ":".bold()); } }}; } pub static WARNINGS: LazyLock<Mutex<FxHashSet<String>>> = LazyLock::new(Mutex::default); /// Warn a user once, if warnings are enabled, with uniqueness determined by the content of the /// message. #[macro_export] macro_rules! warn_user_once { ($($arg:tt)*) => {{ use $crate::anstream::eprintln; use $crate::owo_colors::OwoColorize; if $crate::ENABLED.load(std::sync::atomic::Ordering::Relaxed) { if let Ok(mut states) = $crate::WARNINGS.lock() { let message = format!("{}", format_args!($($arg)*)); if states.insert(message.clone()) { eprintln!("{}{} {}", "warning".yellow().bold(), ":".bold(), message.bold()); } } } }}; } /// Format an error or warning chain. /// /// # Example /// /// ```text /// error: Failed to install app /// Caused By: Failed to install dependency /// Caused By: Error writing failed `/home/ferris/deps/foo`: Permission denied /// ``` /// /// ```text /// warning: Failed to create registry entry for Python 3.12 /// Caused By: Security policy forbids chaining registry entries /// ``` /// /// ```text /// error: Failed to download Python 3.12 /// Caused by: Failed to fetch https://example.com/upload/python3.13.tar.zst /// Server says: This endpoint only support POST requests. /// /// For downloads, please refer to https://example.com/download/python3.13.tar.zst /// Caused by: Caused By: HTTP Error 400 /// ``` pub fn write_error_chain( err: &dyn Error, mut stream: impl std::fmt::Write, level: impl AsRef<str>, color: impl DynColor + Copy, ) -> std::fmt::Result { writeln!( &mut stream, "{}{} {}", level.as_ref().color(color).bold(), ":".bold(), err.to_string().trim() )?; for source in iter::successors(err.source(), |&err| err.source()) { let msg = source.to_string(); let mut lines = msg.lines(); if let Some(first) = lines.next() { let padding = " "; let cause = "Caused by"; let child_padding = " ".repeat(padding.len() + cause.len() + 2); writeln!( &mut stream, "{}{}: {}", padding, cause.color(color).bold(), first.trim() )?; for line in lines { let line = line.trim_end(); if line.is_empty() { // Avoid showing indents on empty lines writeln!(&mut stream)?; } else { writeln!(&mut stream, "{}{}", child_padding, line.trim_end())?; } } } } Ok(()) } #[cfg(test)] mod tests { use crate::write_error_chain; use anyhow::anyhow; use indoc::indoc; use insta::assert_snapshot; use owo_colors::AnsiColors; #[test] fn format_multiline_message() { let err_middle = indoc! {"Failed to fetch https://example.com/upload/python3.13.tar.zst Server says: This endpoint only support POST requests. For downloads, please refer to https://example.com/download/python3.13.tar.zst"}; let err = anyhow!("Caused By: HTTP Error 400") .context(err_middle) .context("Failed to download Python 3.12"); let mut rendered = String::new(); write_error_chain(err.as_ref(), &mut rendered, "error", AnsiColors::Red).unwrap(); let rendered = anstream::adapter::strip_str(&rendered); assert_snapshot!(rendered, @r" error: Failed to download Python 3.12 Caused by: Failed to fetch https://example.com/upload/python3.13.tar.zst Server says: This endpoint only support POST requests. For downloads, please refer to https://example.com/download/python3.13.tar.zst Caused by: Caused By: HTTP Error 400 "); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-trampoline-builder/src/lib.rs
crates/uv-trampoline-builder/src/lib.rs
use std::io; use std::path::{Path, PathBuf}; use std::str::Utf8Error; use fs_err::File; use thiserror::Error; #[cfg(all(windows, target_arch = "x86"))] const LAUNCHER_I686_GUI: &[u8] = include_bytes!("../trampolines/uv-trampoline-i686-gui.exe"); #[cfg(all(windows, target_arch = "x86"))] const LAUNCHER_I686_CONSOLE: &[u8] = include_bytes!("../trampolines/uv-trampoline-i686-console.exe"); #[cfg(all(windows, target_arch = "x86_64"))] const LAUNCHER_X86_64_GUI: &[u8] = include_bytes!("../trampolines/uv-trampoline-x86_64-gui.exe"); #[cfg(all(windows, target_arch = "x86_64"))] const LAUNCHER_X86_64_CONSOLE: &[u8] = include_bytes!("../trampolines/uv-trampoline-x86_64-console.exe"); #[cfg(all(windows, target_arch = "aarch64"))] const LAUNCHER_AARCH64_GUI: &[u8] = include_bytes!("../trampolines/uv-trampoline-aarch64-gui.exe"); #[cfg(all(windows, target_arch = "aarch64"))] const LAUNCHER_AARCH64_CONSOLE: &[u8] = include_bytes!("../trampolines/uv-trampoline-aarch64-console.exe"); // https://learn.microsoft.com/en-us/windows/win32/menurc/resource-types #[cfg(windows)] const RT_RCDATA: u16 = 10; // Resource IDs matching uv-trampoline #[cfg(windows)] const RESOURCE_TRAMPOLINE_KIND: windows::core::PCWSTR = windows::core::w!("UV_TRAMPOLINE_KIND"); #[cfg(windows)] const RESOURCE_PYTHON_PATH: windows::core::PCWSTR = windows::core::w!("UV_PYTHON_PATH"); // Note: This does not need to be looked up as a resource, as we rely on `zipimport` // to do the loading work. Still, keeping the content under a resource means that it // sits nicely under the PE format. #[cfg(windows)] const RESOURCE_SCRIPT_DATA: windows::core::PCWSTR = windows::core::w!("UV_SCRIPT_DATA"); #[derive(Debug)] pub struct Launcher { pub kind: LauncherKind, pub python_path: PathBuf, pub script_data: Option<Vec<u8>>, } impl Launcher { /// Attempt to read [`Launcher`] metadata from a trampoline executable file. /// /// On Unix, this always returns [`None`]. Trampolines are a Windows-specific feature and cannot /// be read on other platforms. #[cfg(not(windows))] pub fn try_from_path(_path: &Path) -> Result<Option<Self>, Error> { Ok(None) } /// Read [`Launcher`] metadata from a trampoline executable file. /// /// Returns `Ok(None)` if the file is not a trampoline executable. /// Returns `Err` if the file looks like a trampoline executable but is formatted incorrectly. #[cfg(windows)] pub fn try_from_path(path: &Path) -> Result<Option<Self>, Error> { use std::os::windows::ffi::OsStrExt; use windows::Win32::System::LibraryLoader::LOAD_LIBRARY_AS_DATAFILE; use windows::Win32::System::LibraryLoader::LoadLibraryExW; let path_str = path .as_os_str() .encode_wide() .chain(std::iter::once(0)) .collect::<Vec<_>>(); // SAFETY: winapi call; null-terminated strings #[allow(unsafe_code)] let Some(module) = (unsafe { LoadLibraryExW( windows::core::PCWSTR(path_str.as_ptr()), None, LOAD_LIBRARY_AS_DATAFILE, ) .ok() }) else { return Ok(None); }; let result = (|| { let Some(kind_data) = read_resource(module, RESOURCE_TRAMPOLINE_KIND) else { return Ok(None); }; let Some(kind) = LauncherKind::from_resource_value(kind_data[0]) else { return Err(Error::UnprocessableMetadata); }; let Some(path_data) = read_resource(module, RESOURCE_PYTHON_PATH) else { return Ok(None); }; let python_path = PathBuf::from( String::from_utf8(path_data).map_err(|err| Error::InvalidPath(err.utf8_error()))?, ); let script_data = read_resource(module, RESOURCE_SCRIPT_DATA); Ok(Some(Self { kind, python_path, script_data, })) })(); // SAFETY: winapi call; handle is known to be valid. #[allow(unsafe_code)] unsafe { windows::Win32::Foundation::FreeLibrary(module) .map_err(|err| Error::Io(io::Error::from_raw_os_error(err.code().0)))?; }; result } /// Write this trampoline launcher to a file. /// /// On Unix, this always returns [`Error::NotWindows`]. Trampolines are a Windows-specific /// feature and cannot be written on other platforms. #[cfg(not(windows))] pub fn write_to_file(self, _file: &mut File, _is_gui: bool) -> Result<(), Error> { Err(Error::NotWindows) } /// Write this trampoline launcher to a file. #[cfg(windows)] pub fn write_to_file(self, file: &mut File, is_gui: bool) -> Result<(), Error> { use std::io::Write; use uv_fs::Simplified; let python_path = self.python_path.simplified_display().to_string(); // Create temporary file for the base launcher let temp_dir = tempfile::TempDir::new()?; let temp_file = temp_dir .path() .join(format!("uv-trampoline-{}.exe", std::process::id())); // Write the launcher binary fs_err::write(&temp_file, get_launcher_bin(is_gui)?)?; // Write resources let resources = &[ ( RESOURCE_TRAMPOLINE_KIND, &[self.kind.to_resource_value()][..], ), (RESOURCE_PYTHON_PATH, python_path.as_bytes()), ]; if let Some(script_data) = self.script_data { let mut all_resources = resources.to_vec(); all_resources.push((RESOURCE_SCRIPT_DATA, &script_data)); write_resources(&temp_file, &all_resources)?; } else { write_resources(&temp_file, resources)?; } // Read back the complete file let launcher = fs_err::read(&temp_file)?; fs_err::remove_file(&temp_file)?; // Then write it to the handle file.write_all(&launcher)?; Ok(()) } #[must_use] pub fn with_python_path(self, path: PathBuf) -> Self { Self { kind: self.kind, python_path: path, script_data: self.script_data, } } } /// The kind of trampoline launcher to create. /// /// See [`uv-trampoline::bounce::TrampolineKind`]. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum LauncherKind { /// The trampoline should execute itself, it's a zipped Python script. Script, /// The trampoline should just execute Python, it's a proxy Python executable. Python, } impl LauncherKind { #[cfg(windows)] fn to_resource_value(self) -> u8 { match self { Self::Script => 1, Self::Python => 2, } } #[cfg(windows)] fn from_resource_value(value: u8) -> Option<Self> { match value { 1 => Some(Self::Script), 2 => Some(Self::Python), _ => None, } } } /// Note: The caller is responsible for adding the path of the wheel we're installing. #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), #[error("Failed to parse executable path")] InvalidPath(#[source] Utf8Error), #[error( "Unable to create Windows launcher for: {0} (only x86_64, x86, and arm64 are supported)" )] UnsupportedWindowsArch(&'static str), #[error("Unable to create Windows launcher on non-Windows platform")] NotWindows, #[error("Cannot process launcher metadata from resource")] UnprocessableMetadata, #[error("Resources over 2^32 bytes are not supported")] ResourceTooLarge, } #[allow(clippy::unnecessary_wraps, unused_variables)] #[cfg(windows)] fn get_launcher_bin(gui: bool) -> Result<&'static [u8], Error> { Ok(match std::env::consts::ARCH { #[cfg(all(windows, target_arch = "x86"))] "x86" => { if gui { LAUNCHER_I686_GUI } else { LAUNCHER_I686_CONSOLE } } #[cfg(all(windows, target_arch = "x86_64"))] "x86_64" => { if gui { LAUNCHER_X86_64_GUI } else { LAUNCHER_X86_64_CONSOLE } } #[cfg(all(windows, target_arch = "aarch64"))] "aarch64" => { if gui { LAUNCHER_AARCH64_GUI } else { LAUNCHER_AARCH64_CONSOLE } } #[cfg(windows)] arch => { return Err(Error::UnsupportedWindowsArch(arch)); } }) } /// Helper to write Windows PE resources #[cfg(windows)] fn write_resources(path: &Path, resources: &[(windows::core::PCWSTR, &[u8])]) -> Result<(), Error> { // SAFETY: winapi calls; null-terminated strings #[allow(unsafe_code)] unsafe { use std::os::windows::ffi::OsStrExt; use windows::Win32::System::LibraryLoader::{ BeginUpdateResourceW, EndUpdateResourceW, UpdateResourceW, }; let path_str = path .as_os_str() .encode_wide() .chain(std::iter::once(0)) .collect::<Vec<_>>(); let handle = BeginUpdateResourceW(windows::core::PCWSTR(path_str.as_ptr()), false) .map_err(|err| Error::Io(io::Error::from_raw_os_error(err.code().0)))?; for (name, data) in resources { UpdateResourceW( handle, windows::core::PCWSTR(RT_RCDATA as *const _), *name, 0, Some(data.as_ptr().cast()), u32::try_from(data.len()).map_err(|_| Error::ResourceTooLarge)?, ) .map_err(|err| Error::Io(io::Error::from_raw_os_error(err.code().0)))?; } EndUpdateResourceW(handle, false) .map_err(|err| Error::Io(io::Error::from_raw_os_error(err.code().0)))?; } Ok(()) } /// Safely reads a resource from a PE file #[cfg(windows)] fn read_resource( handle: windows::Win32::Foundation::HMODULE, name: windows::core::PCWSTR, ) -> Option<Vec<u8>> { // SAFETY: winapi calls; null-terminated strings; all pointers are checked. #[allow(unsafe_code)] unsafe { use windows::Win32::System::LibraryLoader::{ FindResourceW, LoadResource, LockResource, SizeofResource, }; // Find the resource let resource = FindResourceW( Some(handle), name, windows::core::PCWSTR(RT_RCDATA as *const _), ); if resource.is_invalid() { return None; } // Get resource size and data let size = SizeofResource(Some(handle), resource); if size == 0 { return None; } let data = LoadResource(Some(handle), resource).ok()?; let ptr = LockResource(data) as *const u8; if ptr.is_null() { return None; } // Copy the resource data into a Vec Some(std::slice::from_raw_parts(ptr, size as usize).to_vec()) } } /// Construct a Windows script launcher. /// /// On Unix, this always returns [`Error::NotWindows`]. Trampolines are a Windows-specific feature /// and cannot be created on other platforms. #[cfg(not(windows))] pub fn windows_script_launcher( _launcher_python_script: &str, _is_gui: bool, _python_executable: impl AsRef<Path>, ) -> Result<Vec<u8>, Error> { Err(Error::NotWindows) } /// Construct a Windows script launcher. /// /// A Windows script is a minimal .exe launcher binary with the python entrypoint script appended as /// stored zip file. /// /// <https://github.com/pypa/pip/blob/fd0ea6bc5e8cb95e518c23d901c26ca14db17f89/src/pip/_vendor/distlib/scripts.py#L248-L262> #[cfg(windows)] pub fn windows_script_launcher( launcher_python_script: &str, is_gui: bool, python_executable: impl AsRef<Path>, ) -> Result<Vec<u8>, Error> { use std::io::{Cursor, Write}; use zip::ZipWriter; use zip::write::SimpleFileOptions; use uv_fs::Simplified; let launcher_bin: &[u8] = get_launcher_bin(is_gui)?; let mut payload: Vec<u8> = Vec::new(); { // We're using the zip writer, but with stored compression // https://github.com/njsmith/posy/blob/04927e657ca97a5e35bb2252d168125de9a3a025/src/trampolines/mod.rs#L75-L82 // https://github.com/pypa/distlib/blob/8ed03aab48add854f377ce392efffb79bb4d6091/PC/launcher.c#L259-L271 let stored = SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); let mut archive = ZipWriter::new(Cursor::new(&mut payload)); let error_msg = "Writing to Vec<u8> should never fail"; archive.start_file("__main__.py", stored).expect(error_msg); archive .write_all(launcher_python_script.as_bytes()) .expect(error_msg); archive.finish().expect(error_msg); } let python = python_executable.as_ref(); let python_path = python.simplified_display().to_string(); // Start with base launcher binary // Create temporary file for the launcher let temp_dir = tempfile::TempDir::new()?; let temp_file = temp_dir .path() .join(format!("uv-trampoline-{}.exe", std::process::id())); fs_err::write(&temp_file, launcher_bin)?; // Write resources let resources = &[ ( RESOURCE_TRAMPOLINE_KIND, &[LauncherKind::Script.to_resource_value()][..], ), (RESOURCE_PYTHON_PATH, python_path.as_bytes()), (RESOURCE_SCRIPT_DATA, &payload), ]; write_resources(&temp_file, resources)?; // Read back the complete file // TODO(zanieb): It's weird that we write/read from a temporary file here because in the main // usage at `write_script_entrypoints` we do the same thing again. We should refactor these // to avoid repeated work. let launcher = fs_err::read(&temp_file)?; fs_err::remove_file(temp_file)?; Ok(launcher) } /// Construct a Windows Python launcher. /// /// On Unix, this always returns [`Error::NotWindows`]. Trampolines are a Windows-specific feature /// and cannot be created on other platforms. #[cfg(not(windows))] pub fn windows_python_launcher( _python_executable: impl AsRef<Path>, _is_gui: bool, ) -> Result<Vec<u8>, Error> { Err(Error::NotWindows) } /// Construct a Windows Python launcher. /// /// A minimal .exe launcher binary for Python. /// /// Sort of equivalent to a `python` symlink on Unix. #[cfg(windows)] pub fn windows_python_launcher( python_executable: impl AsRef<Path>, is_gui: bool, ) -> Result<Vec<u8>, Error> { use uv_fs::Simplified; let launcher_bin: &[u8] = get_launcher_bin(is_gui)?; let python = python_executable.as_ref(); let python_path = python.simplified_display().to_string(); // Create temporary file for the launcher let temp_dir = tempfile::TempDir::new()?; let temp_file = temp_dir .path() .join(format!("uv-trampoline-{}.exe", std::process::id())); fs_err::write(&temp_file, launcher_bin)?; // Write resources let resources = &[ ( RESOURCE_TRAMPOLINE_KIND, &[LauncherKind::Python.to_resource_value()][..], ), (RESOURCE_PYTHON_PATH, python_path.as_bytes()), ]; write_resources(&temp_file, resources)?; // Read back the complete file let launcher = fs_err::read(&temp_file)?; fs_err::remove_file(temp_file)?; Ok(launcher) } #[cfg(all(test, windows))] #[allow(clippy::print_stdout)] mod test { use std::io::Write; use std::path::Path; use std::path::PathBuf; use std::process::Command; use anyhow::Result; use assert_cmd::prelude::OutputAssertExt; use assert_fs::prelude::PathChild; use fs_err::File; use which::which; use super::{Launcher, LauncherKind, windows_python_launcher, windows_script_launcher}; #[test] #[cfg(all(windows, target_arch = "x86", feature = "production"))] fn test_launchers_are_small() { // At time of writing, they are ~45kb. assert!( super::LAUNCHER_I686_GUI.len() < 45 * 1024, "GUI launcher: {}", super::LAUNCHER_I686_GUI.len() ); assert!( super::LAUNCHER_I686_CONSOLE.len() < 45 * 1024, "CLI launcher: {}", super::LAUNCHER_I686_CONSOLE.len() ); } #[test] #[cfg(all(windows, target_arch = "x86_64", feature = "production"))] fn test_launchers_are_small() { // At time of writing, they are ~45kb. assert!( super::LAUNCHER_X86_64_GUI.len() < 45 * 1024, "GUI launcher: {}", super::LAUNCHER_X86_64_GUI.len() ); assert!( super::LAUNCHER_X86_64_CONSOLE.len() < 45 * 1024, "CLI launcher: {}", super::LAUNCHER_X86_64_CONSOLE.len() ); } #[test] #[cfg(all(windows, target_arch = "aarch64", feature = "production"))] fn test_launchers_are_small() { // At time of writing, they are ~45kb. assert!( super::LAUNCHER_AARCH64_GUI.len() < 45 * 1024, "GUI launcher: {}", super::LAUNCHER_AARCH64_GUI.len() ); assert!( super::LAUNCHER_AARCH64_CONSOLE.len() < 45 * 1024, "CLI launcher: {}", super::LAUNCHER_AARCH64_CONSOLE.len() ); } /// Utility script for the test. fn get_script_launcher(shebang: &str, is_gui: bool) -> String { if is_gui { format!( r#"{shebang} # -*- coding: utf-8 -*- import re import sys def make_gui() -> None: from tkinter import Tk, ttk root = Tk() root.title("uv Test App") frm = ttk.Frame(root, padding=10) frm.grid() ttk.Label(frm, text="Hello from uv-trampoline-gui.exe").grid(column=0, row=0) root.mainloop() if __name__ == "__main__": sys.argv[0] = re.sub(r"(-script\.pyw|\.exe)?$", "", sys.argv[0]) sys.exit(make_gui()) "# ) } else { format!( r#"{shebang} # -*- coding: utf-8 -*- import re import sys def main_console() -> None: print("Hello from uv-trampoline-console.exe", file=sys.stdout) print("Hello from uv-trampoline-console.exe", file=sys.stderr) for arg in sys.argv[1:]: print(arg, file=sys.stderr) if __name__ == "__main__": sys.argv[0] = re.sub(r"(-script\.pyw|\.exe)?$", "", sys.argv[0]) sys.exit(main_console()) "# ) } } /// See [`uv-install-wheel::wheel::format_shebang`]. fn format_shebang(executable: impl AsRef<Path>) -> String { // Convert the executable to a simplified path. let executable = executable.as_ref().display().to_string(); format!("#!{executable}") } /// Creates a self-signed certificate and returns its path. fn create_temp_certificate(temp_dir: &tempfile::TempDir) -> Result<(PathBuf, PathBuf)> { use rcgen::{ CertificateParams, DnType, ExtendedKeyUsagePurpose, KeyPair, KeyUsagePurpose, SanType, }; let mut params = CertificateParams::default(); params.key_usages.push(KeyUsagePurpose::DigitalSignature); params .extended_key_usages .push(ExtendedKeyUsagePurpose::CodeSigning); params .distinguished_name .push(DnType::OrganizationName, "Astral Software Inc."); params .distinguished_name .push(DnType::CommonName, "uv-test-signer"); params .subject_alt_names .push(SanType::DnsName("uv-test-signer".try_into()?)); let private_key = KeyPair::generate()?; let public_cert = params.self_signed(&private_key)?; let public_cert_path = temp_dir.path().join("uv-trampoline-test.crt"); let private_key_path = temp_dir.path().join("uv-trampoline-test.key"); fs_err::write(public_cert_path.as_path(), public_cert.pem())?; fs_err::write(private_key_path.as_path(), private_key.serialize_pem())?; Ok((public_cert_path, private_key_path)) } /// Signs the given binary using `PowerShell`'s `Set-AuthenticodeSignature` with a temporary certificate. fn sign_authenticode(bin_path: impl AsRef<Path>) { let temp_dir = tempfile::TempDir::new().expect("Failed to create temporary directory"); let (public_cert, private_key) = create_temp_certificate(&temp_dir).expect("Failed to create self-signed certificate"); // Instead of powershell, we rely on pwsh which supports CreateFromPemFile. Command::new("pwsh") .args([ "-NoProfile", "-NonInteractive", "-Command", &format!( r" $ErrorActionPreference = 'Stop' Import-Module Microsoft.PowerShell.Security $cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromPemFile('{}', '{}') Set-AuthenticodeSignature -FilePath '{}' -Certificate $cert; ", public_cert.display().to_string().replace('\'', "''"), private_key.display().to_string().replace('\'', "''"), bin_path.as_ref().display().to_string().replace('\'', "''"), ), ]) .env_remove("PSModulePath") .assert() .success(); println!("Signed binary: {}", bin_path.as_ref().display()); } #[test] fn console_script_launcher() -> Result<()> { // Create Temp Dirs let temp_dir = assert_fs::TempDir::new()?; let console_bin_path = temp_dir.child("launcher.console.exe"); // Locate an arbitrary python installation from PATH let python_executable_path = which("python")?; // Generate Launcher Script let launcher_console_script = get_script_launcher(&format_shebang(&python_executable_path), false); // Generate Launcher Payload let console_launcher = windows_script_launcher(&launcher_console_script, false, &python_executable_path)?; // Create Launcher File::create(console_bin_path.path())?.write_all(console_launcher.as_ref())?; println!( "Wrote Console Launcher in {}", console_bin_path.path().display() ); let stdout_predicate = "Hello from uv-trampoline-console.exe\r\n"; let stderr_predicate = "Hello from uv-trampoline-console.exe\r\n"; // Test Console Launcher #[cfg(windows)] Command::new(console_bin_path.path()) .assert() .success() .stdout(stdout_predicate) .stderr(stderr_predicate); let args_to_test = vec!["foo", "bar", "foo bar", "foo \"bar\"", "foo 'bar'"]; let stderr_predicate = format!("{}{}\r\n", stderr_predicate, args_to_test.join("\r\n")); // Test Console Launcher (with args) Command::new(console_bin_path.path()) .args(args_to_test) .assert() .success() .stdout(stdout_predicate) .stderr(stderr_predicate); let launcher = Launcher::try_from_path(console_bin_path.path()) .expect("We should succeed at reading the launcher") .expect("The launcher should be valid"); assert!(launcher.kind == LauncherKind::Script); assert!(launcher.python_path == python_executable_path); // Now code-sign the launcher and verify that it still works. sign_authenticode(console_bin_path.path()); let stdout_predicate = "Hello from uv-trampoline-console.exe\r\n"; let stderr_predicate = "Hello from uv-trampoline-console.exe\r\n"; Command::new(console_bin_path.path()) .assert() .success() .stdout(stdout_predicate) .stderr(stderr_predicate); Ok(()) } #[test] fn console_python_launcher() -> Result<()> { // Create Temp Dirs let temp_dir = assert_fs::TempDir::new()?; let console_bin_path = temp_dir.child("launcher.console.exe"); // Locate an arbitrary python installation from PATH let python_executable_path = which("python")?; // Generate Launcher Payload let console_launcher = windows_python_launcher(&python_executable_path, false)?; // Create Launcher { File::create(console_bin_path.path())?.write_all(console_launcher.as_ref())?; } println!( "Wrote Python Launcher in {}", console_bin_path.path().display() ); // Test Console Launcher Command::new(console_bin_path.path()) .arg("-c") .arg("print('Hello from Python Launcher')") .assert() .success() .stdout("Hello from Python Launcher\r\n"); let launcher = Launcher::try_from_path(console_bin_path.path()) .expect("We should succeed at reading the launcher") .expect("The launcher should be valid"); assert!(launcher.kind == LauncherKind::Python); assert!(launcher.python_path == python_executable_path); // Now code-sign the launcher and verify that it still works. sign_authenticode(console_bin_path.path()); Command::new(console_bin_path.path()) .arg("-c") .arg("print('Hello from Python Launcher')") .assert() .success() .stdout("Hello from Python Launcher\r\n"); Ok(()) } #[test] #[ignore = "This test will spawn a GUI and wait until you close the window."] fn gui_launcher() -> Result<()> { // Create Temp Dirs let temp_dir = assert_fs::TempDir::new()?; let gui_bin_path = temp_dir.child("launcher.gui.exe"); // Locate an arbitrary pythonw installation from PATH let pythonw_executable_path = which("pythonw")?; // Generate Launcher Script let launcher_gui_script = get_script_launcher(&format_shebang(&pythonw_executable_path), true); // Generate Launcher Payload let gui_launcher = windows_script_launcher(&launcher_gui_script, true, &pythonw_executable_path)?; // Create Launcher { File::create(gui_bin_path.path())?.write_all(gui_launcher.as_ref())?; } println!("Wrote GUI Launcher in {}", gui_bin_path.path().display()); // Test GUI Launcher // NOTICE: This will spawn a GUI and will wait until you close the window. Command::new(gui_bin_path.path()).assert().success(); Ok(()) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-options-metadata/src/lib.rs
crates/uv-options-metadata/src/lib.rs
//! Taken directly from Ruff. //! //! See: <https://github.com/astral-sh/ruff/blob/dc8db1afb08704ad6a788c497068b01edf8b460d/crates/ruff_workspace/sr.rs> use serde::{Serialize, Serializer}; use std::collections::BTreeMap; use std::fmt::{Debug, Display, Formatter}; /// Visits [`OptionsMetadata`]. /// /// An instance of [`Visit`] represents the logic for inspecting an object's options metadata. pub trait Visit { /// Visits an [`OptionField`] value named `name`. fn record_field(&mut self, name: &str, field: OptionField); /// Visits an [`OptionSet`] value named `name`. fn record_set(&mut self, name: &str, group: OptionSet); } /// Returns metadata for its options. pub trait OptionsMetadata { /// Visits the options metadata of this object by calling `visit` for each option. fn record(visit: &mut dyn Visit); fn documentation() -> Option<&'static str> { None } /// Returns the extracted metadata. fn metadata() -> OptionSet where Self: Sized + 'static, { OptionSet::of::<Self>() } } impl<T> OptionsMetadata for Option<T> where T: OptionsMetadata, { fn record(visit: &mut dyn Visit) { T::record(visit); } } /// Metadata of an option that can either be a [`OptionField`] or [`OptionSet`]. #[derive(Clone, PartialEq, Eq, Debug, Serialize)] #[serde(untagged)] pub enum OptionEntry { /// A single option. Field(OptionField), /// A set of options. Set(OptionSet), } impl Display for OptionEntry { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Set(set) => std::fmt::Display::fmt(set, f), Self::Field(field) => std::fmt::Display::fmt(&field, f), } } } /// A set of options. /// /// It extracts the options by calling the [`OptionsMetadata::record`] of a type implementing /// [`OptionsMetadata`]. #[derive(Copy, Clone)] pub struct OptionSet { record: fn(&mut dyn Visit), doc: fn() -> Option<&'static str>, } impl PartialEq for OptionSet { fn eq(&self, other: &Self) -> bool { std::ptr::fn_addr_eq(self.record, other.record) && std::ptr::fn_addr_eq(self.doc, other.doc) } } impl Eq for OptionSet {} impl OptionSet { pub fn of<T>() -> Self where T: OptionsMetadata + 'static, { Self { record: T::record, doc: T::documentation, } } /// Visits the options in this set by calling `visit` for each option. pub fn record(&self, visit: &mut dyn Visit) { let record = self.record; record(visit); } pub fn documentation(&self) -> Option<&'static str> { let documentation = self.doc; documentation() } /// Returns `true` if this set has an option that resolves to `name`. /// /// The name can be separated by `.` to find a nested option. pub fn has(&self, name: &str) -> bool { self.find(name).is_some() } /// Returns `Some` if this set has an option that resolves to `name` and `None` otherwise. /// /// The name can be separated by `.` to find a nested option. pub fn find(&self, name: &str) -> Option<OptionEntry> { struct FindOptionVisitor<'a> { option: Option<OptionEntry>, parts: std::str::Split<'a, char>, needle: &'a str, } impl Visit for FindOptionVisitor<'_> { fn record_set(&mut self, name: &str, set: OptionSet) { if self.option.is_none() && name == self.needle { if let Some(next) = self.parts.next() { self.needle = next; set.record(self); } else { self.option = Some(OptionEntry::Set(set)); } } } fn record_field(&mut self, name: &str, field: OptionField) { if self.option.is_none() && name == self.needle { if self.parts.next().is_none() { self.option = Some(OptionEntry::Field(field)); } } } } let mut parts = name.split('.'); if let Some(first) = parts.next() { let mut visitor = FindOptionVisitor { parts, needle: first, option: None, }; self.record(&mut visitor); visitor.option } else { None } } } /// Visitor that writes out the names of all fields and sets. struct DisplayVisitor<'fmt, 'buf> { f: &'fmt mut Formatter<'buf>, result: std::fmt::Result, } impl<'fmt, 'buf> DisplayVisitor<'fmt, 'buf> { fn new(f: &'fmt mut Formatter<'buf>) -> Self { Self { f, result: Ok(()) } } fn finish(self) -> std::fmt::Result { self.result } } impl Visit for DisplayVisitor<'_, '_> { fn record_set(&mut self, name: &str, _: OptionSet) { self.result = self.result.and_then(|()| writeln!(self.f, "{name}")); } fn record_field(&mut self, name: &str, field: OptionField) { self.result = self.result.and_then(|()| { write!(self.f, "{name}")?; if field.deprecated.is_some() { write!(self.f, " (deprecated)")?; } writeln!(self.f) }); } } impl Display for OptionSet { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let mut visitor = DisplayVisitor::new(f); self.record(&mut visitor); visitor.finish() } } struct SerializeVisitor<'a> { entries: &'a mut BTreeMap<String, OptionField>, } impl Visit for SerializeVisitor<'_> { fn record_set(&mut self, name: &str, set: OptionSet) { // Collect the entries of the set. let mut entries = BTreeMap::new(); let mut visitor = SerializeVisitor { entries: &mut entries, }; set.record(&mut visitor); // Insert the set into the entries. for (key, value) in entries { self.entries.insert(format!("{name}.{key}"), value); } } fn record_field(&mut self, name: &str, field: OptionField) { self.entries.insert(name.to_string(), field); } } impl Serialize for OptionSet { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut entries = BTreeMap::new(); let mut visitor = SerializeVisitor { entries: &mut entries, }; self.record(&mut visitor); entries.serialize(serializer) } } impl Debug for OptionSet { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(self, f) } } #[derive(Debug, Eq, PartialEq, Clone, Serialize)] pub struct OptionField { pub doc: &'static str, /// Ex) `"false"` pub default: &'static str, /// Ex) `"bool"` pub value_type: &'static str, /// Ex) `"per-file-ignores"` pub scope: Option<&'static str>, pub example: &'static str, pub deprecated: Option<Deprecated>, pub possible_values: Option<Vec<PossibleValue>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize)] pub struct Deprecated { pub since: Option<&'static str>, pub message: Option<&'static str>, } impl Display for OptionField { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { writeln!(f, "{}", self.doc)?; writeln!(f)?; writeln!(f, "Default value: {}", self.default)?; if let Some(possible_values) = self .possible_values .as_ref() .filter(|values| !values.is_empty()) { writeln!(f, "Possible values:")?; writeln!(f)?; for value in possible_values { writeln!(f, "- {value}")?; } } else { writeln!(f, "Type: {}", self.value_type)?; } if let Some(deprecated) = &self.deprecated { write!(f, "Deprecated")?; if let Some(since) = deprecated.since { write!(f, " (since {since})")?; } if let Some(message) = deprecated.message { write!(f, ": {message}")?; } writeln!(f)?; } writeln!(f, "Example usage:\n```toml\n{}\n```", self.example) } } /// A possible value for an enum, similar to Clap's `PossibleValue` type (but without a dependency /// on Clap). #[derive(Debug, Eq, PartialEq, Clone, Serialize)] pub struct PossibleValue { pub name: String, pub help: Option<String>, } impl Display for PossibleValue { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "`\"{}\"`", self.name)?; if let Some(help) = &self.help { write!(f, ": {help}")?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_has_child_option() { struct WithOptions; impl OptionsMetadata for WithOptions { fn record(visit: &mut dyn Visit) { visit.record_field( "ignore-git-ignore", OptionField { doc: "Whether Ruff should respect the gitignore file", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }, ); } } assert!(WithOptions::metadata().has("ignore-git-ignore")); assert!(!WithOptions::metadata().has("does-not-exist")); } #[test] fn test_has_nested_option() { struct Root; impl OptionsMetadata for Root { fn record(visit: &mut dyn Visit) { visit.record_field( "ignore-git-ignore", OptionField { doc: "Whether Ruff should respect the gitignore file", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }, ); visit.record_set("format", Nested::metadata()); } } struct Nested; impl OptionsMetadata for Nested { fn record(visit: &mut dyn Visit) { visit.record_field( "hard-tabs", OptionField { doc: "Use hard tabs for indentation and spaces for alignment.", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }, ); } } assert!(Root::metadata().has("format.hard-tabs")); assert!(!Root::metadata().has("format.spaces")); assert!(!Root::metadata().has("lint.hard-tabs")); } #[test] fn test_find_child_option() { struct WithOptions; static IGNORE_GIT_IGNORE: OptionField = OptionField { doc: "Whether Ruff should respect the gitignore file", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }; impl OptionsMetadata for WithOptions { fn record(visit: &mut dyn Visit) { visit.record_field("ignore-git-ignore", IGNORE_GIT_IGNORE.clone()); } } assert_eq!( WithOptions::metadata().find("ignore-git-ignore"), Some(OptionEntry::Field(IGNORE_GIT_IGNORE.clone())) ); assert_eq!(WithOptions::metadata().find("does-not-exist"), None); } #[test] fn test_find_nested_option() { static HARD_TABS: OptionField = OptionField { doc: "Use hard tabs for indentation and spaces for alignment.", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }; struct Root; impl OptionsMetadata for Root { fn record(visit: &mut dyn Visit) { visit.record_field( "ignore-git-ignore", OptionField { doc: "Whether Ruff should respect the gitignore file", default: "false", value_type: "bool", example: "", scope: None, deprecated: None, possible_values: None, }, ); visit.record_set("format", Nested::metadata()); } } struct Nested; impl OptionsMetadata for Nested { fn record(visit: &mut dyn Visit) { visit.record_field("hard-tabs", HARD_TABS.clone()); } } assert_eq!( Root::metadata().find("format.hard-tabs"), Some(OptionEntry::Field(HARD_TABS.clone())) ); assert_eq!( Root::metadata().find("format"), Some(OptionEntry::Set(Nested::metadata())) ); assert_eq!(Root::metadata().find("format.spaces"), None); assert_eq!(Root::metadata().find("lint.hard-tabs"), None); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-metadata/src/lib.rs
crates/uv-metadata/src/lib.rs
//! Read metadata from wheels and source distributions. //! //! This module reads all fields exhaustively. The fields are defined in the [Core metadata //! specification](https://packaging.python.org/en/latest/specifications/core-metadata/). use std::io; use std::io::{Read, Seek}; use std::path::Path; use thiserror::Error; use tokio::io::AsyncReadExt; use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt}; use uv_distribution_filename::WheelFilename; use uv_normalize::{DistInfoName, InvalidNameError}; use uv_pypi_types::ResolutionMetadata; use zip::ZipArchive; /// The caller is responsible for attaching the path or url we failed to read. #[derive(Debug, Error)] pub enum Error { #[error("Failed to read `dist-info` metadata from built wheel")] DistInfo, #[error("No .dist-info directory found")] MissingDistInfo, #[error("Multiple .dist-info directories found: {0}")] MultipleDistInfo(String), #[error( "The .dist-info directory does not consist of the normalized package name and version: `{0}`" )] MissingDistInfoSegments(String), #[error("The .dist-info directory {0} does not start with the normalized package name: {1}")] MissingDistInfoPackageName(String, String), #[error("The .dist-info directory name contains invalid characters")] InvalidName(#[from] InvalidNameError), #[error("The metadata at {0} is invalid")] InvalidMetadata(String, Box<uv_pypi_types::MetadataError>), #[error("Bad CRC (got {computed:08x}, expected {expected:08x}) for file: {path}")] BadCrc32 { path: String, computed: u32, expected: u32, }, #[error("Failed to read from zip file")] Zip(#[from] zip::result::ZipError), #[error("Failed to read from zip file")] AsyncZip(#[from] async_zip::error::ZipError), // No `#[from]` to enforce manual review of `io::Error` sources. #[error(transparent)] Io(io::Error), } /// Find the `.dist-info` directory in a zipped wheel. /// /// Returns the dist info dir prefix without the `.dist-info` extension. /// /// Reference implementation: <https://github.com/pypa/pip/blob/36823099a9cdd83261fdbc8c1d2a24fa2eea72ca/src/pip/_internal/utils/wheel.py#L38> pub fn find_archive_dist_info<'a, T: Copy>( filename: &WheelFilename, files: impl Iterator<Item = (T, &'a str)>, ) -> Result<(T, &'a str), Error> { let metadatas: Vec<_> = files .filter_map(|(payload, path)| { let (dist_info_dir, file) = path.split_once('/')?; if file != "METADATA" { return None; } let dist_info_prefix = dist_info_dir.strip_suffix(".dist-info")?; Some((payload, dist_info_prefix)) }) .collect(); // Like `pip`, assert that there is exactly one `.dist-info` directory. let (payload, dist_info_prefix) = match metadatas[..] { [] => { return Err(Error::MissingDistInfo); } [(payload, path)] => (payload, path), _ => { return Err(Error::MultipleDistInfo( metadatas .into_iter() .map(|(_, dist_info_dir)| dist_info_dir.to_string()) .collect::<Vec<_>>() .join(", "), )); } }; // Like `pip`, validate that the `.dist-info` directory is prefixed with the canonical // package name. let normalized_prefix = DistInfoName::new(dist_info_prefix); if !normalized_prefix .as_ref() .starts_with(filename.name.as_str()) { return Err(Error::MissingDistInfoPackageName( dist_info_prefix.to_string(), filename.name.to_string(), )); } Ok((payload, dist_info_prefix)) } /// Returns `true` if the file is a `METADATA` file in a `.dist-info` directory that matches the /// wheel filename. pub fn is_metadata_entry(path: &str, filename: &WheelFilename) -> Result<bool, Error> { let Some((dist_info_dir, file)) = path.split_once('/') else { return Ok(false); }; if file != "METADATA" { return Ok(false); } let Some(dist_info_prefix) = dist_info_dir.strip_suffix(".dist-info") else { return Ok(false); }; // Like `pip`, validate that the `.dist-info` directory is prefixed with the canonical // package name. let normalized_prefix = DistInfoName::new(dist_info_prefix); if !normalized_prefix .as_ref() .starts_with(filename.name.as_str()) { return Err(Error::MissingDistInfoPackageName( dist_info_prefix.to_string(), filename.name.to_string(), )); } Ok(true) } /// Given an archive, read the `METADATA` from the `.dist-info` directory. pub fn read_archive_metadata( filename: &WheelFilename, archive: &mut ZipArchive<impl Read + Seek + Sized>, ) -> Result<Vec<u8>, Error> { let dist_info_prefix = find_archive_dist_info(filename, archive.file_names().map(|name| (name, name)))?.1; let mut file = archive.by_name(&format!("{dist_info_prefix}.dist-info/METADATA"))?; #[allow(clippy::cast_possible_truncation)] let mut buffer = Vec::with_capacity(file.size() as usize); file.read_to_end(&mut buffer).map_err(Error::Io)?; Ok(buffer) } /// Find the `.dist-info` directory in an unzipped wheel. /// /// See: <https://github.com/PyO3/python-pkginfo-rs> pub fn find_flat_dist_info( filename: &WheelFilename, path: impl AsRef<Path>, ) -> Result<String, Error> { // Iterate over `path` to find the `.dist-info` directory. It should be at the top-level. let Some(dist_info_prefix) = fs_err::read_dir(path.as_ref()) .map_err(Error::Io)? .find_map(|entry| { let entry = entry.ok()?; let file_type = entry.file_type().ok()?; if file_type.is_dir() { let path = entry.path(); let extension = path.extension()?; if extension != "dist-info" { return None; } let dist_info_prefix = path.file_stem()?.to_str()?; Some(dist_info_prefix.to_string()) } else { None } }) else { return Err(Error::MissingDistInfo); }; // Like `pip`, validate that the `.dist-info` directory is prefixed with the canonical // package name. let normalized_prefix = DistInfoName::new(&dist_info_prefix); if !normalized_prefix .as_ref() .starts_with(filename.name.as_str()) { return Err(Error::MissingDistInfoPackageName( dist_info_prefix, filename.name.to_string(), )); } Ok(dist_info_prefix) } /// Read the wheel `METADATA` metadata from a `.dist-info` directory. pub fn read_dist_info_metadata( dist_info_prefix: &str, wheel: impl AsRef<Path>, ) -> Result<Vec<u8>, Error> { let metadata_file = wheel .as_ref() .join(format!("{dist_info_prefix}.dist-info/METADATA")); fs_err::read(metadata_file).map_err(Error::Io) } /// Read a wheel's `METADATA` file from a zip file. pub async fn read_metadata_async_seek( filename: &WheelFilename, reader: impl tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin, ) -> Result<Vec<u8>, Error> { let reader = futures::io::BufReader::new(reader.compat()); let mut zip_reader = async_zip::base::read::seek::ZipFileReader::new(reader).await?; let (metadata_idx, _dist_info_prefix) = find_archive_dist_info( filename, zip_reader .file() .entries() .iter() .enumerate() .filter_map(|(index, entry)| Some((index, entry.filename().as_str().ok()?))), )?; // Read the contents of the `METADATA` file. let mut contents = Vec::new(); zip_reader .reader_with_entry(metadata_idx) .await? .read_to_end_checked(&mut contents) .await?; Ok(contents) } /// Like [`read_metadata_async_seek`], but doesn't use seek. pub async fn read_metadata_async_stream<R: futures::AsyncRead + Unpin>( filename: &WheelFilename, debug_path: &str, reader: R, ) -> Result<ResolutionMetadata, Error> { let reader = futures::io::BufReader::with_capacity(128 * 1024, reader); let mut zip = async_zip::base::read::stream::ZipFileReader::new(reader); while let Some(mut entry) = zip.next_with_entry().await? { // Find the `METADATA` entry. let path = entry.reader().entry().filename().as_str()?.to_owned(); if is_metadata_entry(&path, filename)? { let mut reader = entry.reader_mut().compat(); let mut contents = Vec::new(); reader.read_to_end(&mut contents).await.unwrap(); // Validate the CRC of any file we unpack // (It would be nice if async_zip made it harder to Not do this...) let reader = reader.into_inner(); let computed = reader.compute_hash(); let expected = reader.entry().crc32(); if computed != expected { let error = Error::BadCrc32 { path, computed, expected, }; // There are some cases where we fail to get a proper CRC. // This is probably connected to out-of-line data descriptors // which are problematic to access in a streaming context. // In those cases the CRC seems to reliably be stubbed inline as 0, // so we downgrade this to a (hidden-by-default) warning. if expected == 0 { tracing::warn!("presumed missing CRC: {error}"); } else { return Err(error); } } let metadata = ResolutionMetadata::parse_metadata(&contents) .map_err(|err| Error::InvalidMetadata(debug_path.to_string(), Box::new(err)))?; return Ok(metadata); } // Close current file to get access to the next one. See docs: // https://docs.rs/async_zip/0.0.16/async_zip/base/read/stream/ (.., zip) = entry.skip().await?; } Err(Error::MissingDistInfo) } /// Read the [`ResolutionMetadata`] from an unzipped wheel. pub fn read_flat_wheel_metadata( filename: &WheelFilename, wheel: impl AsRef<Path>, ) -> Result<ResolutionMetadata, Error> { let dist_info_prefix = find_flat_dist_info(filename, &wheel)?; let metadata = read_dist_info_metadata(&dist_info_prefix, &wheel)?; ResolutionMetadata::parse_metadata(&metadata).map_err(|err| { Error::InvalidMetadata( format!("{dist_info_prefix}.dist-info/METADATA"), Box::new(err), ) }) } #[cfg(test)] mod test { use super::find_archive_dist_info; use std::str::FromStr; use uv_distribution_filename::WheelFilename; #[test] fn test_dot_in_name() { let files = [ "mastodon/Mastodon.py", "mastodon/__init__.py", "mastodon/streaming.py", "Mastodon.py-1.5.1.dist-info/DESCRIPTION.rst", "Mastodon.py-1.5.1.dist-info/metadata.json", "Mastodon.py-1.5.1.dist-info/top_level.txt", "Mastodon.py-1.5.1.dist-info/WHEEL", "Mastodon.py-1.5.1.dist-info/METADATA", "Mastodon.py-1.5.1.dist-info/RECORD", ]; let filename = WheelFilename::from_str("Mastodon.py-1.5.1-py2.py3-none-any.whl").unwrap(); let (_, dist_info_prefix) = find_archive_dist_info(&filename, files.into_iter().map(|file| (file, file))).unwrap(); assert_eq!(dist_info_prefix, "Mastodon.py-1.5.1"); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements-txt/src/shquote.rs
crates/uv-requirements-txt/src/shquote.rs
//! POSIX Shell Compatible Argument Parser //! //! This implementation is vendored from the [`r-shquote`](https://github.com/r-util/r-shquote) //! crate under the Apache 2.0 license: //! //! ```text //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! https://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. //! ``` #[derive(Debug, Clone)] #[allow(dead_code)] pub(crate) enum UnquoteError { UnterminatedSingleQuote { char_cursor: usize, byte_cursor: usize, }, UnterminatedDoubleQuote { char_cursor: usize, byte_cursor: usize, }, } impl std::fmt::Display for UnquoteError { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "{self:?}") } } impl std::error::Error for UnquoteError {} fn unquote_open_single( acc: &mut String, cursor: &mut std::iter::Enumerate<std::str::CharIndices>, ) -> bool { // This decodes a single-quote sequence. The opening single-quote was already parsed by // the caller. Both `&source[start]` and `cursor` point to the first character following // the opening single-quote. // Anything inside the single-quote sequence is copied verbatim to the output until the // next single-quote. No escape sequences are supported, not even a single-quote can be // escaped. However, if the sequence is not terminated, the entire operation is considered // invalid. for i in cursor { match i { (_, (_, '\'')) => return true, (_, (_, c)) => acc.push(c), } } false } fn unquote_open_double( acc: &mut String, cursor: &mut std::iter::Enumerate<std::str::CharIndices>, ) -> bool { // This decodes a double-quote sequence. The opening double-quote was already parsed by // the caller. Both `&source[start]` and `cursor` point to the first character following // the opening double-quote. // A double-quote sequence allows escape-sequences and goes until the closing // double-quote. If the sequence is not terminated, though, the entire operation is // considered invalid. loop { match cursor.next() { Some((_, (_, '"'))) => { // An unescaped double-quote character terminates the double-quote sequence. // It produces no output. return true; } Some((_, (_, '\\'))) => { // Inside a double-quote sequence several escape sequences are allowed. In // general, any unknown sequence is copied verbatim in its entirety including // the backslash. Known sequences produce the escaped character in its output // and makes the parser not interpret it. If the sequence is non-terminated, // it implies that the double-quote sequence is non-terminated and thus // invokes the same behavior, meaning the entire operation is refused. match cursor.next() { Some((_, (_, esc_ch))) if esc_ch == '"' || esc_ch == '\\' || esc_ch == '`' || esc_ch == '$' || esc_ch == '\n' => { acc.push(esc_ch); } Some((_, (_, esc_ch))) => { acc.push('\\'); acc.push(esc_ch); } None => { return false; } } } Some((_, (_, inner_ch))) => { // Any non-special character inside a double-quote is copied // literally just like characters outside of it. acc.push(inner_ch); } None => { // The double-quote sequence was not terminated. The entire // operation is considered invalid and we have to refuse producing // any resulting value. return false; } } } } fn unquote_open_escape(acc: &mut String, cursor: &mut std::iter::Enumerate<std::str::CharIndices>) { // This decodes an escape sequence outside of any quote. The opening backslash was already // parsed by the caller. Both `&source[start]` and `cursor` point to the first character // following the opening backslash. // Outside of quotes, an escape sequence simply treats the next character literally, and // does not interpret it. The exceptions are literal <NL> (newline character) and a single // backslash as last character in the string. In these cases the escape-sequence is // stripped and produces no output. The <NL> case is a remnant of human shell input, where // you can input multiple lines by appending a backslash to the previous line. This causes // both the backslash and <NL> to be ignore, since they purely serve readability of user // input. if let Some((_, (_, esc_ch))) = cursor.next() { if esc_ch != '\n' { acc.push(esc_ch); } } } /// Unquote String /// /// Unquote a single string according to POSIX Shell quoting and escaping rules. If the input /// string is not a valid input, the operation will fail and provide diagnosis information on /// where the first invalid part was encountered. /// /// The result is canonical. There is only one valid unquoted result for a given input. /// /// If the string does not require any quoting or escaping, returns `Ok(None)`. /// /// # Examples /// /// ```no_build /// assert_eq!(unquote("foobar").unwrap(), "foobar"); /// ``` pub(crate) fn unquote(source: &str) -> Result<Option<String>, UnquoteError> { // If the string does not contain any single-quotes, double-quotes, or escape sequences, it // does not require any unquoting. if memchr::memchr3(b'\'', b'"', b'\\', source.as_bytes()).is_none() { return Ok(None); } // An unquote-operation never results in a longer string. Furthermore, the common case is // most of the string is unquoted / unescaped. Hence, we simply allocate the same space // for the resulting string as the input. let mut acc = String::with_capacity(source.len()); // We loop over the string. When a single-quote, double-quote, or escape sequence is // opened, we let our helpers parse the sub-strings. Anything else is copied over // literally until the end of the line. let mut cursor = source.char_indices().enumerate(); loop { match cursor.next() { Some((next_idx, (next_pos, '\''))) => { if !unquote_open_single(&mut acc, &mut cursor) { break Err(UnquoteError::UnterminatedSingleQuote { char_cursor: next_idx, byte_cursor: next_pos, }); } } Some((next_idx, (next_pos, '"'))) => { if !unquote_open_double(&mut acc, &mut cursor) { break Err(UnquoteError::UnterminatedDoubleQuote { char_cursor: next_idx, byte_cursor: next_pos, }); } } Some((_, (_, '\\'))) => { unquote_open_escape(&mut acc, &mut cursor); } Some((_, (_, next_ch))) => { acc.push(next_ch); } None => { break Ok(Some(acc)); } } } } #[cfg(test)] mod tests { use super::*; #[test] fn basic() { assert_eq!(unquote("foobar").unwrap(), None); assert_eq!(unquote("foo'bar'").unwrap().unwrap(), "foobar"); assert_eq!(unquote("foo\"bar\"").unwrap().unwrap(), "foobar"); assert_eq!(unquote("\\foobar\\").unwrap().unwrap(), "foobar"); assert_eq!(unquote("\\'foobar\\'").unwrap().unwrap(), "'foobar'"); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements-txt/src/lib.rs
crates/uv-requirements-txt/src/lib.rs
//! Parses a subset of requirement.txt syntax //! //! <https://pip.pypa.io/en/stable/reference/requirements-file-format/> //! //! Supported: //! * [PEP 508 requirements](https://packaging.python.org/en/latest/specifications/dependency-specifiers/) //! * `-r` //! * `-c` //! * `--hash` (postfix) //! * `-e` //! //! Unsupported: //! * `<path>`. TBD //! * `<archive_url>`. TBD //! * Options without a requirement, such as `--find-links` or `--index-url` //! //! Grammar as implemented: //! //! ```text //! file = (statement | empty ('#' any*)? '\n')* //! empty = whitespace* //! statement = constraint_include | requirements_include | editable_requirement | requirement //! constraint_include = '-c' ('=' | wrappable_whitespaces) filepath //! requirements_include = '-r' ('=' | wrappable_whitespaces) filepath //! editable_requirement = '-e' ('=' | wrappable_whitespaces) requirement //! # We check whether the line starts with a letter or a number, in that case we assume it's a //! # PEP 508 requirement //! # https://packaging.python.org/en/latest/specifications/name-normalization/#valid-non-normalized-names //! # This does not (yet?) support plain files or urls, we use a letter or a number as first //! # character to assume a PEP 508 requirement //! requirement = [a-zA-Z0-9] pep508_grammar_tail wrappable_whitespaces hashes //! hashes = ('--hash' ('=' | wrappable_whitespaces) [a-zA-Z0-9-_]+ ':' [a-zA-Z0-9-_] wrappable_whitespaces+)* //! # This should indicate a single backslash before a newline //! wrappable_whitespaces = whitespace ('\\\n' | whitespace)* //! ``` use std::borrow::Cow; use std::fmt::{Display, Formatter}; use std::io; use std::path::{Path, PathBuf}; use std::str::FromStr; use rustc_hash::{FxHashMap, FxHashSet}; use tracing::instrument; use unscanny::{Pattern, Scanner}; use url::Url; #[cfg(feature = "http")] use uv_client::BaseClient; use uv_client::{BaseClientBuilder, Connectivity}; use uv_configuration::{NoBinary, NoBuild, PackageNameSpecifier}; use uv_distribution_types::{ Requirement, UnresolvedRequirement, UnresolvedRequirementSpecification, }; use uv_fs::Simplified; use uv_pep508::{Pep508Error, RequirementOrigin, VerbatimUrl, expand_env_vars}; use uv_pypi_types::VerbatimParsedUrl; #[cfg(feature = "http")] use uv_redacted::DisplaySafeUrl; use uv_redacted::DisplaySafeUrlError; use crate::requirement::EditableError; pub use crate::requirement::RequirementsTxtRequirement; use crate::shquote::unquote; mod requirement; mod shquote; /// A cache of file contents, keyed by path, to avoid re-reading files from disk. pub type SourceCache = FxHashMap<PathBuf, String>; /// We emit one of those for each `requirements.txt` entry. enum RequirementsTxtStatement { /// `-r` inclusion filename Requirements { filename: String, start: usize, end: usize, }, /// `-c` inclusion filename Constraint { filename: String, start: usize, end: usize, }, /// PEP 508 requirement plus metadata RequirementEntry(RequirementEntry), /// `-e` EditableRequirementEntry(RequirementEntry), /// `--index-url` IndexUrl(VerbatimUrl), /// `--extra-index-url` ExtraIndexUrl(VerbatimUrl), /// `--find-links` FindLinks(VerbatimUrl), /// `--no-index` NoIndex, /// `--no-binary` NoBinary(NoBinary), /// `--only-binary` OnlyBinary(NoBuild), /// An unsupported option (e.g., `--trusted-host`). UnsupportedOption(UnsupportedOption), } /// A [Requirement] with additional metadata from the `requirements.txt`, currently only hashes but in /// the future also editable and similar information. #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct RequirementEntry { /// The actual PEP 508 requirement. pub requirement: RequirementsTxtRequirement, /// Hashes of the downloadable packages. pub hashes: Vec<String>, } // We place the impl here instead of next to `UnresolvedRequirementSpecification` because // `UnresolvedRequirementSpecification` is defined in `distribution-types` and `requirements-txt` // depends on `distribution-types`. impl From<RequirementEntry> for UnresolvedRequirementSpecification { fn from(value: RequirementEntry) -> Self { Self { requirement: match value.requirement { RequirementsTxtRequirement::Named(named) => { UnresolvedRequirement::Named(Requirement::from(named)) } RequirementsTxtRequirement::Unnamed(unnamed) => { UnresolvedRequirement::Unnamed(unnamed) } }, hashes: value.hashes, } } } impl From<RequirementsTxtRequirement> for UnresolvedRequirementSpecification { fn from(value: RequirementsTxtRequirement) -> Self { Self::from(RequirementEntry { requirement: value, hashes: vec![], }) } } /// Parsed and flattened requirements.txt with requirements and constraints #[derive(Debug, Default, Clone, PartialEq, Eq)] pub struct RequirementsTxt { /// The actual requirements with the hashes. pub requirements: Vec<RequirementEntry>, /// Constraints included with `-c`. pub constraints: Vec<uv_pep508::Requirement<VerbatimParsedUrl>>, /// Editables with `-e`. pub editables: Vec<RequirementEntry>, /// The index URL, specified with `--index-url`. pub index_url: Option<VerbatimUrl>, /// The extra index URLs, specified with `--extra-index-url`. pub extra_index_urls: Vec<VerbatimUrl>, /// The find links locations, specified with `--find-links`. pub find_links: Vec<VerbatimUrl>, /// Whether to ignore the index, specified with `--no-index`. pub no_index: bool, /// Whether to disallow wheels, specified with `--no-binary`. pub no_binary: NoBinary, /// Whether to allow only wheels, specified with `--only-binary`. pub only_binary: NoBuild, } impl RequirementsTxt { /// See module level documentation. #[instrument( skip_all, fields(requirements_txt = requirements_txt.as_ref().as_os_str().to_str()) )] pub async fn parse( requirements_txt: impl AsRef<Path>, working_dir: impl AsRef<Path>, ) -> Result<Self, RequirementsTxtFileError> { Self::parse_with_cache( requirements_txt, working_dir, &BaseClientBuilder::default().connectivity(Connectivity::Offline), &mut SourceCache::default(), ) .await } /// Parse a `requirements.txt` file, using the given cache to avoid re-reading files from disk. #[instrument( skip_all, fields(requirements_txt = requirements_txt.as_ref().as_os_str().to_str()) )] pub async fn parse_with_cache( requirements_txt: impl AsRef<Path>, working_dir: impl AsRef<Path>, client_builder: &BaseClientBuilder<'_>, cache: &mut SourceCache, ) -> Result<Self, RequirementsTxtFileError> { let mut visited = VisitedFiles::Requirements { requirements: &mut FxHashSet::default(), constraints: &mut FxHashSet::default(), }; Self::parse_impl( requirements_txt, working_dir, client_builder, &mut visited, cache, ) .await } /// Parse requirements from a string, using the given path for error messages and resolving /// relative paths. pub async fn parse_str( content: &str, requirements_txt: impl AsRef<Path>, working_dir: impl AsRef<Path>, client_builder: &BaseClientBuilder<'_>, source_contents: &mut SourceCache, ) -> Result<Self, RequirementsTxtFileError> { let requirements_txt = requirements_txt.as_ref(); let working_dir = working_dir.as_ref(); let requirements_dir = requirements_txt.parent().unwrap_or(working_dir); let mut visited = VisitedFiles::Requirements { requirements: &mut FxHashSet::default(), constraints: &mut FxHashSet::default(), }; Self::parse_inner( content, working_dir, requirements_dir, client_builder, requirements_txt, &mut visited, source_contents, ) .await .map_err(|err| RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: err, }) } /// See module level documentation #[instrument( skip_all, fields(requirements_txt = requirements_txt.as_ref().as_os_str().to_str()) )] async fn parse_impl( requirements_txt: impl AsRef<Path>, working_dir: impl AsRef<Path>, client_builder: &BaseClientBuilder<'_>, visited: &mut VisitedFiles<'_>, cache: &mut SourceCache, ) -> Result<Self, RequirementsTxtFileError> { let requirements_txt = requirements_txt.as_ref(); let working_dir = working_dir.as_ref(); let content = if let Some(content) = cache.get(requirements_txt) { // Use cached content if available. content.clone() } else if requirements_txt.starts_with("http://") | requirements_txt.starts_with("https://") { #[cfg(not(feature = "http"))] { return Err(RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: RequirementsTxtParserError::Io(io::Error::new( io::ErrorKind::InvalidInput, "Remote file not supported without `http` feature", )), }); } #[cfg(feature = "http")] { // Avoid constructing a client if network is disabled already if client_builder.is_offline() { return Err(RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: RequirementsTxtParserError::Io(io::Error::new( io::ErrorKind::InvalidInput, format!( "Network connectivity is disabled, but a remote requirements file was requested: {}", requirements_txt.display() ), )), }); } let client = client_builder.build(); let content = read_url_to_string(&requirements_txt, client) .await .map_err(|err| RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: err, })?; cache.insert(requirements_txt.to_path_buf(), content.clone()); content } } else { // Ex) `file:///home/ferris/project/requirements.txt` let content = uv_fs::read_to_string_transcode(&requirements_txt) .await .map_err(|err| RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: RequirementsTxtParserError::Io(err), })?; cache.insert(requirements_txt.to_path_buf(), content.clone()); content }; let requirements_dir = requirements_txt.parent().unwrap_or(working_dir); let data = Self::parse_inner( &content, working_dir, requirements_dir, client_builder, requirements_txt, visited, cache, ) .await .map_err(|err| RequirementsTxtFileError { file: requirements_txt.to_path_buf(), error: err, })?; Ok(data) } /// See module level documentation. /// /// When parsing, relative paths to requirements (e.g., `-e ../editable/`) are resolved against /// the current working directory. However, relative paths to sub-files (e.g., `-r ../requirements.txt`) /// are resolved against the directory of the containing `requirements.txt` file, to match /// `pip`'s behavior. async fn parse_inner( content: &str, working_dir: &Path, requirements_dir: &Path, client_builder: &BaseClientBuilder<'_>, requirements_txt: &Path, visited: &mut VisitedFiles<'_>, cache: &mut SourceCache, ) -> Result<Self, RequirementsTxtParserError> { let mut s = Scanner::new(content); let mut data = Self::default(); while let Some(statement) = parse_entry(&mut s, content, working_dir, requirements_txt)? { match statement { RequirementsTxtStatement::Requirements { filename, start, end, } => { let filename = expand_env_vars(&filename); let sub_file = if filename.starts_with("http://") || filename.starts_with("https://") { PathBuf::from(filename.as_ref()) } else if filename.starts_with("file://") { requirements_txt.join( Url::parse(filename.as_ref()) .map_err(|err| RequirementsTxtParserError::Url { source: DisplaySafeUrlError::Url(err).into(), url: filename.to_string(), start, end, })? .to_file_path() .map_err(|()| RequirementsTxtParserError::FileUrl { url: filename.to_string(), start, end, })?, ) } else { requirements_dir.join(filename.as_ref()) }; match visited { VisitedFiles::Requirements { requirements, .. } => { if !requirements.insert(sub_file.clone()) { continue; } } // Treat any nested requirements or constraints as constraints. This differs // from `pip`, which seems to treat `-r` requirements in constraints files as // _requirements_, but we don't want to support that. VisitedFiles::Constraints { constraints } => { if !constraints.insert(sub_file.clone()) { continue; } } } let sub_requirements = Box::pin(Self::parse_impl( &sub_file, working_dir, client_builder, visited, cache, )) .await .map_err(|err| RequirementsTxtParserError::Subfile { source: Box::new(err), start, end, })?; // Disallow conflicting `--index-url` in nested `requirements` files. if sub_requirements.index_url.is_some() && data.index_url.is_some() && sub_requirements.index_url != data.index_url { let (line, column) = calculate_row_column(content, s.cursor()); return Err(RequirementsTxtParserError::Parser { message: "Nested `requirements` file contains conflicting `--index-url`" .to_string(), line, column, }); } // Add each to the correct category. data.update_from(sub_requirements); } RequirementsTxtStatement::Constraint { filename, start, end, } => { let filename = expand_env_vars(&filename); let sub_file = if filename.starts_with("http://") || filename.starts_with("https://") { PathBuf::from(filename.as_ref()) } else if filename.starts_with("file://") { requirements_txt.join( Url::parse(filename.as_ref()) .map_err(|err| RequirementsTxtParserError::Url { source: DisplaySafeUrlError::Url(err).into(), url: filename.to_string(), start, end, })? .to_file_path() .map_err(|()| RequirementsTxtParserError::FileUrl { url: filename.to_string(), start, end, })?, ) } else { requirements_dir.join(filename.as_ref()) }; // Switch to constraints mode, if we aren't in it already. let mut visited = match visited { VisitedFiles::Requirements { constraints, .. } => { if !constraints.insert(sub_file.clone()) { continue; } VisitedFiles::Constraints { constraints } } VisitedFiles::Constraints { constraints } => { if !constraints.insert(sub_file.clone()) { continue; } VisitedFiles::Constraints { constraints } } }; let sub_constraints = Box::pin(Self::parse_impl( &sub_file, working_dir, client_builder, &mut visited, cache, )) .await .map_err(|err| RequirementsTxtParserError::Subfile { source: Box::new(err), start, end, })?; // Treat any nested requirements or constraints as constraints. This differs // from `pip`, which seems to treat `-r` requirements in constraints files as // _requirements_, but we don't want to support that. for entry in sub_constraints.requirements { match entry.requirement { RequirementsTxtRequirement::Named(requirement) => { data.constraints.push(requirement); } RequirementsTxtRequirement::Unnamed(_) => { return Err(RequirementsTxtParserError::UnnamedConstraint { start, end, }); } } } for constraint in sub_constraints.constraints { data.constraints.push(constraint); } } RequirementsTxtStatement::RequirementEntry(requirement_entry) => { data.requirements.push(requirement_entry); } RequirementsTxtStatement::EditableRequirementEntry(editable) => { data.editables.push(editable); } RequirementsTxtStatement::IndexUrl(url) => { if data.index_url.is_some() { let (line, column) = calculate_row_column(content, s.cursor()); return Err(RequirementsTxtParserError::Parser { message: "Multiple `--index-url` values provided".to_string(), line, column, }); } data.index_url = Some(url); } RequirementsTxtStatement::ExtraIndexUrl(url) => { data.extra_index_urls.push(url); } RequirementsTxtStatement::FindLinks(url) => { data.find_links.push(url); } RequirementsTxtStatement::NoIndex => { data.no_index = true; } RequirementsTxtStatement::NoBinary(no_binary) => { data.no_binary.extend(no_binary); } RequirementsTxtStatement::OnlyBinary(only_binary) => { data.only_binary.extend(only_binary); } RequirementsTxtStatement::UnsupportedOption(flag) => { if requirements_txt == Path::new("-") { if flag.cli() { uv_warnings::warn_user!( "Ignoring unsupported option from stdin: `{flag}` (hint: pass `{flag}` on the command line instead)", flag = flag.green() ); } else { uv_warnings::warn_user!( "Ignoring unsupported option from stdin: `{flag}`", flag = flag.green() ); } } else { if flag.cli() { uv_warnings::warn_user!( "Ignoring unsupported option in `{path}`: `{flag}` (hint: pass `{flag}` on the command line instead)", path = requirements_txt.user_display().cyan(), flag = flag.green() ); } else { uv_warnings::warn_user!( "Ignoring unsupported option in `{path}`: `{flag}`", path = requirements_txt.user_display().cyan(), flag = flag.green() ); } } } } } Ok(data) } /// Merge the data from a nested `requirements` file (`other`) into this one. pub fn update_from(&mut self, other: Self) { let Self { requirements, constraints, editables, index_url, extra_index_urls, find_links, no_index, no_binary, only_binary, } = other; self.requirements.extend(requirements); self.constraints.extend(constraints); self.editables.extend(editables); if self.index_url.is_none() { self.index_url = index_url; } self.extra_index_urls.extend(extra_index_urls); self.find_links.extend(find_links); self.no_index = self.no_index || no_index; self.no_binary.extend(no_binary); self.only_binary.extend(only_binary); } } /// An unsupported option (e.g., `--trusted-host`). /// /// See: <https://pip.pypa.io/en/stable/reference/requirements-file-format/#global-options> #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum UnsupportedOption { PreferBinary, RequireHashes, Pre, TrustedHost, UseFeature, } impl UnsupportedOption { /// The name of the unsupported option. fn name(self) -> &'static str { match self { Self::PreferBinary => "--prefer-binary", Self::RequireHashes => "--require-hashes", Self::Pre => "--pre", Self::TrustedHost => "--trusted-host", Self::UseFeature => "--use-feature", } } /// Returns `true` if the option is supported on the CLI. fn cli(self) -> bool { match self { Self::PreferBinary => false, Self::RequireHashes => true, Self::Pre => true, Self::TrustedHost => true, Self::UseFeature => false, } } /// Returns an iterator over all unsupported options. fn iter() -> impl Iterator<Item = Self> { [ Self::PreferBinary, Self::RequireHashes, Self::Pre, Self::TrustedHost, Self::UseFeature, ] .iter() .copied() } } impl Display for UnsupportedOption { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.name()) } } /// Returns `true` if the character is a newline or a comment character. const fn is_terminal(c: char) -> bool { matches!(c, '\n' | '\r' | '#') } /// Parse a single entry, that is a requirement, an inclusion or a comment line. /// /// Consumes all preceding trivia (whitespace and comments). If it returns `None`, we've reached /// the end of file. fn parse_entry( s: &mut Scanner, content: &str, working_dir: &Path, requirements_txt: &Path, ) -> Result<Option<RequirementsTxtStatement>, RequirementsTxtParserError> { // Eat all preceding whitespace, this may run us to the end of file eat_wrappable_whitespace(s); while s.at(['\n', '\r', '#']) { // skip comments eat_trailing_line(content, s)?; eat_wrappable_whitespace(s); } let start = s.cursor(); Ok(Some(if s.eat_if("-r") || s.eat_if("--requirement") { let filename = parse_value("--requirement", content, s, |c: char| !is_terminal(c))?; let filename = unquote(filename) .ok() .flatten() .unwrap_or_else(|| filename.to_string()); let end = s.cursor(); RequirementsTxtStatement::Requirements { filename, start, end, } } else if s.eat_if("-c") || s.eat_if("--constraint") { let filename = parse_value("--constraint", content, s, |c: char| !is_terminal(c))?; let filename = unquote(filename) .ok() .flatten() .unwrap_or_else(|| filename.to_string()); let end = s.cursor(); RequirementsTxtStatement::Constraint { filename, start, end, } } else if s.eat_if("-e") || s.eat_if("--editable") { if s.eat_if('=') { // Explicit equals sign. } else if s.eat_if(char::is_whitespace) { // Key and value are separated by whitespace instead. s.eat_whitespace(); } else { let (line, column) = calculate_row_column(content, s.cursor()); return Err(RequirementsTxtParserError::Parser { message: format!("Expected '=' or whitespace, found {:?}", s.peek()), line, column, }); } let source = if requirements_txt == Path::new("-") { None } else { Some(requirements_txt) }; let (requirement, hashes) = parse_requirement_and_hashes(s, content, source, working_dir, true)?; let requirement = requirement .into_editable() .map_err(|err| RequirementsTxtParserError::NonEditable { source: err, start, end: s.cursor(), })?; RequirementsTxtStatement::EditableRequirementEntry(RequirementEntry { requirement, hashes, }) } else if s.eat_if("-i") || s.eat_if("--index-url") { let given = parse_value("--index-url", content, s, |c: char| !is_terminal(c))?; let given = unquote(given) .ok() .flatten() .map(Cow::Owned) .unwrap_or(Cow::Borrowed(given)); let expanded = expand_env_vars(given.as_ref()); let url = if let Some(path) = std::path::absolute(expanded.as_ref()) .ok() .filter(|path| path.exists()) { VerbatimUrl::from_absolute_path(path).map_err(|err| { RequirementsTxtParserError::VerbatimUrl { source: err, url: given.to_string(), start, end: s.cursor(), } })? } else { VerbatimUrl::parse_url(expanded.as_ref()).map_err(|err| { RequirementsTxtParserError::Url { source: err, url: given.to_string(), start, end: s.cursor(), } })? }; RequirementsTxtStatement::IndexUrl(url.with_given(given)) } else if s.eat_if("--extra-index-url") { let given = parse_value("--extra-index-url", content, s, |c: char| !is_terminal(c))?; let given = unquote(given) .ok() .flatten() .map(Cow::Owned) .unwrap_or(Cow::Borrowed(given)); let expanded = expand_env_vars(given.as_ref()); let url = if let Some(path) = std::path::absolute(expanded.as_ref()) .ok() .filter(|path| path.exists()) { VerbatimUrl::from_absolute_path(path).map_err(|err| { RequirementsTxtParserError::VerbatimUrl { source: err, url: given.to_string(), start, end: s.cursor(), } })? } else { VerbatimUrl::parse_url(expanded.as_ref()).map_err(|err| { RequirementsTxtParserError::Url { source: err, url: given.to_string(), start, end: s.cursor(), } })? }; RequirementsTxtStatement::ExtraIndexUrl(url.with_given(given)) } else if s.eat_if("--no-index") { RequirementsTxtStatement::NoIndex } else if s.eat_if("--find-links") || s.eat_if("-f") { let given = parse_value("--find-links", content, s, |c: char| !is_terminal(c))?; let given = unquote(given) .ok() .flatten() .map(Cow::Owned) .unwrap_or(Cow::Borrowed(given)); let expanded = expand_env_vars(given.as_ref()); let url = if let Some(path) = std::path::absolute(expanded.as_ref()) .ok() .filter(|path| path.exists()) { VerbatimUrl::from_absolute_path(path).map_err(|err| { RequirementsTxtParserError::VerbatimUrl { source: err, url: given.to_string(), start, end: s.cursor(), } })? } else { VerbatimUrl::parse_url(expanded.as_ref()).map_err(|err| { RequirementsTxtParserError::Url { source: err, url: given.to_string(), start, end: s.cursor(), } })? }; RequirementsTxtStatement::FindLinks(url.with_given(given)) } else if s.eat_if("--no-binary") { let given = parse_value("--no-binary", content, s, |c: char| !is_terminal(c))?; let given = unquote(given) .ok() .flatten() .map(Cow::Owned) .unwrap_or(Cow::Borrowed(given)); let specifier = PackageNameSpecifier::from_str(given.as_ref()).map_err(|err| {
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-requirements-txt/src/requirement.rs
crates/uv-requirements-txt/src/requirement.rs
use std::fmt::Display; use std::path::Path; use uv_normalize::PackageName; use uv_pep508::{ Pep508Error, Pep508ErrorSource, RequirementOrigin, TracingReporter, UnnamedRequirement, }; use uv_pypi_types::{ParsedDirectoryUrl, ParsedUrl, VerbatimParsedUrl}; #[derive(Debug, thiserror::Error)] pub enum EditableError { #[error("Editable `{0}` must refer to a local directory")] MissingVersion(PackageName), #[error("Editable `{0}` must refer to a local directory, not a versioned package")] Versioned(PackageName), #[error("Editable `{0}` must refer to a local directory, not an archive: `{1}`")] File(PackageName, String), #[error("Editable `{0}` must refer to a local directory, not an HTTPS URL: `{1}`")] Https(PackageName, String), #[error("Editable `{0}` must refer to a local directory, not a Git URL: `{1}`")] Git(PackageName, String), #[error("Editable must refer to a local directory, not an archive: `{0}`")] UnnamedFile(String), #[error("Editable must refer to a local directory, not an HTTPS URL: `{0}`")] UnnamedHttps(String), #[error("Editable must refer to a local directory, not a Git URL: `{0}`")] UnnamedGit(String), } /// A requirement specifier in a `requirements.txt` file. /// /// Analog to `UnresolvedRequirement` but with `uv_pep508::Requirement` instead of /// `distribution_types::Requirement`. #[derive(Hash, Debug, Clone, Eq, PartialEq)] pub enum RequirementsTxtRequirement { /// The uv-specific superset over PEP 508 requirements specifier incorporating /// `tool.uv.sources`. Named(uv_pep508::Requirement<VerbatimParsedUrl>), /// A PEP 508-like, direct URL dependency specifier. Unnamed(UnnamedRequirement<VerbatimParsedUrl>), } impl RequirementsTxtRequirement { /// Set the source file containing the requirement. #[must_use] pub fn with_origin(self, origin: RequirementOrigin) -> Self { match self { Self::Named(requirement) => Self::Named(requirement.with_origin(origin)), Self::Unnamed(requirement) => Self::Unnamed(requirement.with_origin(origin)), } } /// Convert the [`RequirementsTxtRequirement`] into an editable requirement. /// /// # Errors /// /// Returns [`EditableError`] if the requirement cannot be interpreted as editable. /// Specifically, only local directory URLs are supported. pub fn into_editable(self) -> Result<Self, EditableError> { match self { Self::Named(requirement) => { let Some(version_or_url) = requirement.version_or_url else { return Err(EditableError::MissingVersion(requirement.name)); }; let uv_pep508::VersionOrUrl::Url(url) = version_or_url else { return Err(EditableError::Versioned(requirement.name)); }; let parsed_url = match url.parsed_url { ParsedUrl::Directory(parsed_url) => parsed_url, ParsedUrl::Path(_) => { return Err(EditableError::File(requirement.name, url.to_string())); } ParsedUrl::Archive(_) => { return Err(EditableError::Https(requirement.name, url.to_string())); } ParsedUrl::Git(_) => { return Err(EditableError::Git(requirement.name, url.to_string())); } }; Ok(Self::Named(uv_pep508::Requirement { version_or_url: Some(uv_pep508::VersionOrUrl::Url(VerbatimParsedUrl { verbatim: url.verbatim, parsed_url: ParsedUrl::Directory(ParsedDirectoryUrl { editable: Some(true), ..parsed_url }), })), ..requirement })) } Self::Unnamed(requirement) => { let parsed_url = match requirement.url.parsed_url { ParsedUrl::Directory(parsed_url) => parsed_url, ParsedUrl::Path(_) => { return Err(EditableError::UnnamedFile(requirement.to_string())); } ParsedUrl::Archive(_) => { return Err(EditableError::UnnamedHttps(requirement.to_string())); } ParsedUrl::Git(_) => { return Err(EditableError::UnnamedGit(requirement.to_string())); } }; Ok(Self::Unnamed(UnnamedRequirement { url: VerbatimParsedUrl { verbatim: requirement.url.verbatim, parsed_url: ParsedUrl::Directory(ParsedDirectoryUrl { editable: Some(true), ..parsed_url }), }, ..requirement })) } } } /// Parse a requirement as seen in a `requirements.txt` file. pub fn parse( input: &str, working_dir: impl AsRef<Path>, editable: bool, ) -> Result<Self, Box<Pep508Error<VerbatimParsedUrl>>> { // Attempt to parse as a PEP 508-compliant requirement. match uv_pep508::Requirement::parse(input, &working_dir) { Ok(requirement) => { // As a special-case, interpret `dagster` as `./dagster` if we're in editable mode. if editable && requirement.version_or_url.is_none() { Ok(Self::Unnamed(UnnamedRequirement::parse( input, &working_dir, &mut TracingReporter, )?)) } else { Ok(Self::Named(requirement)) } } Err(err) => match err.message { Pep508ErrorSource::UnsupportedRequirement(_) => { // If that fails, attempt to parse as a direct URL requirement. Ok(Self::Unnamed(UnnamedRequirement::parse( input, &working_dir, &mut TracingReporter, )?)) } _ => Err(err), }, } .map_err(Box::new) } } impl Display for RequirementsTxtRequirement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Named(requirement) => Display::fmt(&requirement, f), Self::Unnamed(requirement) => Display::fmt(&requirement, f), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-bin-install/src/lib.rs
crates/uv-bin-install/src/lib.rs
//! Binary download and installation utilities for uv. //! //! These utilities are specifically for consuming distributions that are _not_ Python packages, //! e.g., `ruff` (which does have a Python package, but also has standalone binaries on GitHub). use std::path::PathBuf; use std::pin::Pin; use std::task::{Context, Poll}; use futures::TryStreamExt; use reqwest_retry::policies::ExponentialBackoff; use std::fmt; use thiserror::Error; use tokio::io::{AsyncRead, ReadBuf}; use tokio_util::compat::FuturesAsyncReadCompatExt; use url::Url; use uv_distribution_filename::SourceDistExtension; use uv_cache::{Cache, CacheBucket, CacheEntry, Error as CacheError}; use uv_client::{BaseClient, RetryState}; use uv_extract::{Error as ExtractError, stream}; use uv_pep440::Version; use uv_platform::Platform; use uv_redacted::DisplaySafeUrl; /// Binary tools that can be installed. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Binary { Ruff, } impl Binary { /// Get the default version for this binary. pub fn default_version(&self) -> Version { match self { // TODO(zanieb): Figure out a nice way to automate updating this Self::Ruff => Version::new([0, 12, 5]), } } /// The name of the binary. /// /// See [`Binary::executable`] for the platform-specific executable name. pub fn name(&self) -> &'static str { match self { Self::Ruff => "ruff", } } /// Get the download URL for a specific version and platform. pub fn download_url( &self, version: &Version, platform: &str, format: ArchiveFormat, ) -> Result<Url, Error> { match self { Self::Ruff => { let url = format!( "https://github.com/astral-sh/ruff/releases/download/{version}/ruff-{platform}.{}", format.extension() ); Url::parse(&url).map_err(|err| Error::UrlParse { url, source: err }) } } } /// Get the executable name pub fn executable(&self) -> String { format!("{}{}", self.name(), std::env::consts::EXE_SUFFIX) } } impl fmt::Display for Binary { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.name()) } } /// Archive formats for binary downloads. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ArchiveFormat { Zip, TarGz, } impl ArchiveFormat { /// Get the file extension for this archive format. pub fn extension(&self) -> &'static str { match self { Self::Zip => "zip", Self::TarGz => "tar.gz", } } } impl From<ArchiveFormat> for SourceDistExtension { fn from(val: ArchiveFormat) -> Self { match val { ArchiveFormat::Zip => Self::Zip, ArchiveFormat::TarGz => Self::TarGz, } } } /// Errors that can occur during binary download and installation. #[derive(Debug, Error)] pub enum Error { #[error("Failed to download from: {url}")] Download { url: Url, #[source] source: reqwest_middleware::Error, }, #[error("Failed to parse URL: {url}")] UrlParse { url: String, #[source] source: url::ParseError, }, #[error("Failed to extract archive")] Extract { #[source] source: ExtractError, }, #[error("Binary not found in archive at expected location: {expected}")] BinaryNotFound { expected: PathBuf }, #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] Cache(#[from] CacheError), #[error("Failed to detect platform")] Platform(#[from] uv_platform::Error), #[error("Request failed after {retries} {subject}", subject = if *retries > 1 { "retries" } else { "retry" })] RetriedError { #[source] err: Box<Error>, retries: u32, }, } impl Error { /// Return the number of retries that were made to complete this request before this error was /// returned. /// /// Note that e.g. 3 retries equates to 4 attempts. fn retries(&self) -> u32 { if let Self::RetriedError { retries, .. } = self { return *retries; } 0 } } /// Install the given binary. pub async fn bin_install( binary: Binary, version: &Version, client: &BaseClient, retry_policy: &ExponentialBackoff, cache: &Cache, reporter: &dyn Reporter, ) -> Result<PathBuf, Error> { let platform = Platform::from_env()?; let platform_name = platform.as_cargo_dist_triple(); let cache_entry = CacheEntry::new( cache .bucket(CacheBucket::Binaries) .join(binary.name()) .join(version.to_string()) .join(&platform_name), binary.executable(), ); // Lock the directory to prevent racing installs let _lock = cache_entry.with_file(".lock").lock().await?; if cache_entry.path().exists() { return Ok(cache_entry.into_path_buf()); } let format = if platform.os.is_windows() { ArchiveFormat::Zip } else { ArchiveFormat::TarGz }; let download_url = binary.download_url(version, &platform_name, format)?; let cache_dir = cache_entry.dir(); fs_err::tokio::create_dir_all(&cache_dir).await?; let path = download_and_unpack_with_retry( binary, version, client, retry_policy, cache, reporter, &platform_name, format, &download_url, &cache_entry, ) .await?; // Add executable bit #[cfg(unix)] { use std::fs::Permissions; use std::os::unix::fs::PermissionsExt; let permissions = fs_err::tokio::metadata(&path).await?.permissions(); if permissions.mode() & 0o111 != 0o111 { fs_err::tokio::set_permissions( &path, Permissions::from_mode(permissions.mode() | 0o111), ) .await?; } } Ok(path) } /// Download and unpack a binary with retry on stream failures. async fn download_and_unpack_with_retry( binary: Binary, version: &Version, client: &BaseClient, retry_policy: &ExponentialBackoff, cache: &Cache, reporter: &dyn Reporter, platform_name: &str, format: ArchiveFormat, download_url: &Url, cache_entry: &CacheEntry, ) -> Result<PathBuf, Error> { let mut retry_state = RetryState::start(*retry_policy, download_url.clone()); loop { let result = download_and_unpack( binary, version, client, cache, reporter, platform_name, format, download_url, cache_entry, ) .await; match result { Ok(path) => return Ok(path), Err(err) => { if let Some(backoff) = retry_state.should_retry(&err, err.retries()) { retry_state.sleep_backoff(backoff).await; continue; } return if retry_state.total_retries() > 0 { Err(Error::RetriedError { err: Box::new(err), retries: retry_state.total_retries(), }) } else { Err(err) }; } } } } /// Download and unpackage a binary, /// /// NOTE [`download_and_unpack_with_retry`] should be used instead. async fn download_and_unpack( binary: Binary, version: &Version, client: &BaseClient, cache: &Cache, reporter: &dyn Reporter, platform_name: &str, format: ArchiveFormat, download_url: &Url, cache_entry: &CacheEntry, ) -> Result<PathBuf, Error> { // Create a temporary directory for extraction let temp_dir = tempfile::tempdir_in(cache.bucket(CacheBucket::Binaries))?; let response = client .for_host(&DisplaySafeUrl::from_url(download_url.clone())) .get(download_url.clone()) .send() .await .map_err(|err| Error::Download { url: download_url.clone(), source: err, })?; let inner_retries = response .extensions() .get::<reqwest_retry::RetryCount>() .map(|retries| retries.value()); if let Err(status_error) = response.error_for_status_ref() { let err = Error::Download { url: download_url.clone(), source: reqwest_middleware::Error::from(status_error), }; if let Some(retries) = inner_retries { return Err(Error::RetriedError { err: Box::new(err), retries, }); } return Err(err); } // Get the download size from headers if available let size = response .headers() .get(reqwest::header::CONTENT_LENGTH) .and_then(|val| val.to_str().ok()) .and_then(|val| val.parse::<u64>().ok()); // Stream download directly to extraction let reader = response .bytes_stream() .map_err(std::io::Error::other) .into_async_read() .compat(); let id = reporter.on_download_start(binary.name(), version, size); let mut progress_reader = ProgressReader::new(reader, id, reporter); stream::archive(&mut progress_reader, format.into(), temp_dir.path()) .await .map_err(|e| Error::Extract { source: e })?; reporter.on_download_complete(id); // Find the binary in the extracted files let extracted_binary = match format { ArchiveFormat::Zip => { // Windows ZIP archives contain the binary directly in the root temp_dir.path().join(binary.executable()) } ArchiveFormat::TarGz => { // tar.gz archives contain the binary in a subdirectory temp_dir .path() .join(format!("{}-{platform_name}", binary.name())) .join(binary.executable()) } }; if !extracted_binary.exists() { return Err(Error::BinaryNotFound { expected: extracted_binary, }); } // Move the binary to its final location before the temp directory is dropped fs_err::tokio::rename(&extracted_binary, cache_entry.path()).await?; Ok(cache_entry.path().to_path_buf()) } /// Progress reporter for binary downloads. pub trait Reporter: Send + Sync { /// Called when a download starts. fn on_download_start(&self, name: &str, version: &Version, size: Option<u64>) -> usize; /// Called when download progress is made. fn on_download_progress(&self, id: usize, inc: u64); /// Called when a download completes. fn on_download_complete(&self, id: usize); } /// An asynchronous reader that reports progress as bytes are read. struct ProgressReader<'a, R> { reader: R, index: usize, reporter: &'a dyn Reporter, } impl<'a, R> ProgressReader<'a, R> { /// Create a new [`ProgressReader`] that wraps another reader. fn new(reader: R, index: usize, reporter: &'a dyn Reporter) -> Self { Self { reader, index, reporter, } } } impl<R> AsyncRead for ProgressReader<'_, R> where R: AsyncRead + Unpin, { fn poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<std::io::Result<()>> { Pin::new(&mut self.as_mut().reader) .poll_read(cx, buf) .map_ok(|()| { self.reporter .on_download_progress(self.index, buf.filled().len() as u64); }) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/build.rs
crates/uv-python/build.rs
#[allow(clippy::disallowed_types)] use std::fs::{File, FileTimes}; use std::io::Write; use std::path::PathBuf; use std::{env, fs}; use uv_static::EnvVars; fn process_json(data: &serde_json::Value) -> serde_json::Value { let mut out_data = serde_json::Map::new(); if let Some(obj) = data.as_object() { for (key, value) in obj { out_data.insert(key.clone(), value.clone()); } } serde_json::Value::Object(out_data) } fn main() { let version_metadata = PathBuf::from_iter([ env::var(EnvVars::CARGO_MANIFEST_DIR).unwrap(), "download-metadata.json".into(), ]); let version_metadata_minified = PathBuf::from_iter([ env::var(EnvVars::OUT_DIR).unwrap(), "download-metadata-minified.json".into(), ]); println!( "cargo::rerun-if-changed={}", version_metadata.to_str().unwrap() ); println!( "cargo::rerun-if-changed={}", version_metadata_minified.to_str().unwrap() ); let json_data: serde_json::Value = serde_json::from_str( #[allow(clippy::disallowed_methods)] &fs::read_to_string(&version_metadata).expect("Failed to read download-metadata.json"), ) .expect("Failed to parse JSON"); let filtered_data = process_json(&json_data); #[allow(clippy::disallowed_types)] let mut out_file = File::create(version_metadata_minified) .expect("failed to open download-metadata-minified.json"); #[allow(clippy::disallowed_methods)] out_file .write_all( serde_json::to_string(&filtered_data) .expect("Failed to serialize JSON") .as_bytes(), ) .expect("Failed to write minified JSON"); // Cargo uses the modified times of the paths specified in // `rerun-if-changed`, so fetch the current file times and set them the same // on the output file. #[allow(clippy::disallowed_methods)] let meta = fs::metadata(version_metadata).expect("failed to read metadata for download-metadata.json"); out_file .set_times( FileTimes::new() .set_accessed(meta.accessed().unwrap()) .set_modified(meta.modified().unwrap()), ) .expect("failed to write file times to download-metadata-minified.json"); }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/discovery.rs
crates/uv-python/src/discovery.rs
use itertools::{Either, Itertools}; use regex::Regex; use rustc_hash::{FxBuildHasher, FxHashSet}; use same_file::is_same_file; use std::borrow::Cow; use std::env::consts::EXE_SUFFIX; use std::fmt::{self, Debug, Formatter}; use std::{env, io, iter}; use std::{path::Path, path::PathBuf, str::FromStr}; use thiserror::Error; use tracing::{debug, instrument, trace}; use uv_cache::Cache; use uv_fs::Simplified; use uv_fs::which::is_executable; use uv_pep440::{ LowerBound, Prerelease, UpperBound, Version, VersionSpecifier, VersionSpecifiers, release_specifiers_to_ranges, }; use uv_preview::Preview; use uv_static::EnvVars; use uv_warnings::warn_user_once; use which::{which, which_all}; use crate::downloads::{PlatformRequest, PythonDownloadRequest}; use crate::implementation::ImplementationName; use crate::installation::PythonInstallation; use crate::interpreter::Error as InterpreterError; use crate::interpreter::{StatusCodeError, UnexpectedResponseError}; use crate::managed::{ManagedPythonInstallations, PythonMinorVersionLink}; #[cfg(windows)] use crate::microsoft_store::find_microsoft_store_pythons; use crate::python_version::python_build_versions_from_env; use crate::virtualenv::Error as VirtualEnvError; use crate::virtualenv::{ CondaEnvironmentKind, conda_environment_from_env, virtualenv_from_env, virtualenv_from_working_dir, virtualenv_python_executable, }; #[cfg(windows)] use crate::windows_registry::{WindowsPython, registry_pythons}; use crate::{BrokenSymlink, Interpreter, PythonVersion}; /// A request to find a Python installation. /// /// See [`PythonRequest::from_str`]. #[derive(Debug, Clone, PartialEq, Eq, Default, Hash)] pub enum PythonRequest { /// An appropriate default Python installation /// /// This may skip some Python installations, such as pre-release versions or alternative /// implementations. #[default] Default, /// Any Python installation Any, /// A Python version without an implementation name e.g. `3.10` or `>=3.12,<3.13` Version(VersionRequest), /// A path to a directory containing a Python installation, e.g. `.venv` Directory(PathBuf), /// A path to a Python executable e.g. `~/bin/python` File(PathBuf), /// The name of a Python executable (i.e. for lookup in the PATH) e.g. `foopython3` ExecutableName(String), /// A Python implementation without a version e.g. `pypy` or `pp` Implementation(ImplementationName), /// A Python implementation name and version e.g. `pypy3.8` or `pypy@3.8` or `pp38` ImplementationVersion(ImplementationName, VersionRequest), /// A request for a specific Python installation key e.g. `cpython-3.12-x86_64-linux-gnu` /// Generally these refer to managed Python downloads. Key(PythonDownloadRequest), } impl<'a> serde::Deserialize<'a> for PythonRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'a>, { let s = String::deserialize(deserializer)?; Ok(Self::parse(&s)) } } impl serde::Serialize for PythonRequest { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let s = self.to_canonical_string(); serializer.serialize_str(&s) } } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum PythonPreference { /// Only use managed Python installations; never use system Python installations. OnlyManaged, #[default] /// Prefer managed Python installations over system Python installations. /// /// System Python installations are still preferred over downloading managed Python versions. /// Use `only-managed` to always fetch a managed Python version. Managed, /// Prefer system Python installations over managed Python installations. /// /// If a system Python installation cannot be found, a managed Python installation can be used. System, /// Only use system Python installations; never use managed Python installations. OnlySystem, } #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)] #[serde(deny_unknown_fields, rename_all = "kebab-case")] #[cfg_attr(feature = "clap", derive(clap::ValueEnum))] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] pub enum PythonDownloads { /// Automatically download managed Python installations when needed. #[default] #[serde(alias = "auto")] Automatic, /// Do not automatically download managed Python installations; require explicit installation. Manual, /// Do not ever allow Python downloads. Never, } impl FromStr for PythonDownloads { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "auto" | "automatic" | "true" | "1" => Ok(Self::Automatic), "manual" => Ok(Self::Manual), "never" | "false" | "0" => Ok(Self::Never), _ => Err(format!("Invalid value for `python-download`: '{s}'")), } } } impl From<bool> for PythonDownloads { fn from(value: bool) -> Self { if value { Self::Automatic } else { Self::Never } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub enum EnvironmentPreference { /// Only use virtual environments, never allow a system environment. #[default] OnlyVirtual, /// Prefer virtual environments and allow a system environment if explicitly requested. ExplicitSystem, /// Only use a system environment, ignore virtual environments. OnlySystem, /// Allow any environment. Any, } #[derive(Debug, Clone, PartialEq, Eq, Default)] pub(crate) struct DiscoveryPreferences { python_preference: PythonPreference, environment_preference: EnvironmentPreference, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum PythonVariant { #[default] Default, Debug, Freethreaded, FreethreadedDebug, Gil, GilDebug, } /// A Python discovery version request. #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] pub enum VersionRequest { /// Allow an appropriate default Python version. #[default] Default, /// Allow any Python version. Any, Major(u8, PythonVariant), MajorMinor(u8, u8, PythonVariant), MajorMinorPatch(u8, u8, u8, PythonVariant), MajorMinorPrerelease(u8, u8, Prerelease, PythonVariant), Range(VersionSpecifiers, PythonVariant), } /// The result of an Python installation search. /// /// Returned by [`find_python_installation`]. type FindPythonResult = Result<PythonInstallation, PythonNotFound>; /// The result of failed Python installation discovery. /// /// See [`FindPythonResult`]. #[derive(Clone, Debug, Error)] pub struct PythonNotFound { pub request: PythonRequest, pub python_preference: PythonPreference, pub environment_preference: EnvironmentPreference, } /// A location for discovery of a Python installation or interpreter. #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash, PartialOrd, Ord)] pub enum PythonSource { /// The path was provided directly ProvidedPath, /// An environment was active e.g. via `VIRTUAL_ENV` ActiveEnvironment, /// A conda environment was active e.g. via `CONDA_PREFIX` CondaPrefix, /// A base conda environment was active e.g. via `CONDA_PREFIX` BaseCondaPrefix, /// An environment was discovered e.g. via `.venv` DiscoveredEnvironment, /// An executable was found in the search path i.e. `PATH` SearchPath, /// The first executable found in the search path i.e. `PATH` SearchPathFirst, /// An executable was found in the Windows registry via PEP 514 Registry, /// An executable was found in the known Microsoft Store locations MicrosoftStore, /// The Python installation was found in the uv managed Python directory Managed, /// The Python installation was found via the invoking interpreter i.e. via `python -m uv ...` ParentInterpreter, } #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), /// An error was encountering when retrieving interpreter information. #[error("Failed to inspect Python interpreter from {} at `{}` ", _2, _1.user_display())] Query( #[source] Box<crate::interpreter::Error>, PathBuf, PythonSource, ), /// An error was encountered while trying to find a managed Python installation matching the /// current platform. #[error("Failed to discover managed Python installations")] ManagedPython(#[from] crate::managed::Error), /// An error was encountered when inspecting a virtual environment. #[error(transparent)] VirtualEnv(#[from] crate::virtualenv::Error), #[cfg(windows)] #[error("Failed to query installed Python versions from the Windows registry")] RegistryError(#[from] windows::core::Error), /// An invalid version request was given #[error("Invalid version request: {0}")] InvalidVersionRequest(String), /// The @latest version request was given #[error("Requesting the 'latest' Python version is not yet supported")] LatestVersionRequest, // TODO(zanieb): Is this error case necessary still? We should probably drop it. #[error("Interpreter discovery for `{0}` requires `{1}` but only `{2}` is allowed")] SourceNotAllowed(PythonRequest, PythonSource, PythonPreference), #[error(transparent)] BuildVersion(#[from] crate::python_version::BuildVersionError), } /// Lazily iterate over Python executables in mutable virtual environments. /// /// The following sources are supported: /// /// - Active virtual environment (via `VIRTUAL_ENV`) /// - Discovered virtual environment (e.g. `.venv` in a parent directory) /// /// Notably, "system" environments are excluded. See [`python_executables_from_installed`]. fn python_executables_from_virtual_environments<'a>() -> impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a { let from_active_environment = iter::once_with(|| { virtualenv_from_env() .into_iter() .map(virtualenv_python_executable) .map(|path| Ok((PythonSource::ActiveEnvironment, path))) }) .flatten(); // N.B. we prefer the conda environment over discovered virtual environments let from_conda_environment = iter::once_with(|| { conda_environment_from_env(CondaEnvironmentKind::Child) .into_iter() .map(virtualenv_python_executable) .map(|path| Ok((PythonSource::CondaPrefix, path))) }) .flatten(); let from_discovered_environment = iter::once_with(|| { virtualenv_from_working_dir() .map(|path| { path.map(virtualenv_python_executable) .map(|path| (PythonSource::DiscoveredEnvironment, path)) .into_iter() }) .map_err(Error::from) }) .flatten_ok(); from_active_environment .chain(from_conda_environment) .chain(from_discovered_environment) } /// Lazily iterate over Python executables installed on the system. /// /// The following sources are supported: /// /// - Managed Python installations (e.g. `uv python install`) /// - The search path (i.e. `PATH`) /// - The registry (Windows only) /// /// The ordering and presence of each source is determined by the [`PythonPreference`]. /// /// If a [`VersionRequest`] is provided, we will skip executables that we know do not satisfy the request /// and (as discussed in [`python_executables_from_search_path`]) additional version-specific executables may /// be included. However, the caller MUST query the returned executables to ensure they satisfy the request; /// this function does not guarantee that the executables provide any particular version. See /// [`find_python_installation`] instead. /// /// This function does not guarantee that the executables are valid Python interpreters. /// See [`python_interpreters_from_executables`]. fn python_executables_from_installed<'a>( version: &'a VersionRequest, implementation: Option<&'a ImplementationName>, platform: PlatformRequest, preference: PythonPreference, preview: Preview, ) -> Box<dyn Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a> { let from_managed_installations = iter::once_with(move || { ManagedPythonInstallations::from_settings(None) .map_err(Error::from) .and_then(|installed_installations| { debug!( "Searching for managed installations at `{}`", installed_installations.root().user_display() ); let installations = installed_installations.find_matching_current_platform()?; let build_versions = python_build_versions_from_env()?; // Check that the Python version and platform satisfy the request to avoid // unnecessary interpreter queries later Ok(installations .into_iter() .filter(move |installation| { if !version.matches_version(&installation.version()) { debug!("Skipping managed installation `{installation}`: does not satisfy `{version}`"); return false; } if !platform.matches(installation.platform()) { debug!("Skipping managed installation `{installation}`: does not satisfy requested platform `{platform}`"); return false; } if let Some(requested_build) = build_versions.get(&installation.implementation()) { let Some(installation_build) = installation.build() else { debug!( "Skipping managed installation `{installation}`: a build version was requested but is not recorded for this installation" ); return false; }; if installation_build != requested_build { debug!( "Skipping managed installation `{installation}`: requested build version `{requested_build}` does not match installation build version `{installation_build}`" ); return false; } } true }) .inspect(|installation| debug!("Found managed installation `{installation}`")) .map(move |installation| { // If it's not a patch version request, then attempt to read the stable // minor version link. let executable = version .patch() .is_none() .then(|| { PythonMinorVersionLink::from_installation( &installation, preview, ) .filter(PythonMinorVersionLink::exists) .map( |minor_version_link| { minor_version_link.symlink_executable.clone() }, ) }) .flatten() .unwrap_or_else(|| installation.executable(false)); (PythonSource::Managed, executable) }) ) }) }) .flatten_ok(); let from_search_path = iter::once_with(move || { python_executables_from_search_path(version, implementation) .enumerate() .map(|(i, path)| { if i == 0 { Ok((PythonSource::SearchPathFirst, path)) } else { Ok((PythonSource::SearchPath, path)) } }) }) .flatten(); let from_windows_registry = iter::once_with(move || { #[cfg(windows)] { // Skip interpreter probing if we already know the version doesn't match. let version_filter = move |entry: &WindowsPython| { if let Some(found) = &entry.version { // Some distributions emit the patch version (example: `SysVersion: 3.9`) if found.string.chars().filter(|c| *c == '.').count() == 1 { version.matches_major_minor(found.major(), found.minor()) } else { version.matches_version(found) } } else { true } }; env::var_os(EnvVars::UV_TEST_PYTHON_PATH) .is_none() .then(|| { registry_pythons() .map(|entries| { entries .into_iter() .filter(version_filter) .map(|entry| (PythonSource::Registry, entry.path)) .chain( find_microsoft_store_pythons() .filter(version_filter) .map(|entry| (PythonSource::MicrosoftStore, entry.path)), ) }) .map_err(Error::from) }) .into_iter() .flatten_ok() } #[cfg(not(windows))] { Vec::new() } }) .flatten(); match preference { PythonPreference::OnlyManaged => { // TODO(zanieb): Ideally, we'd create "fake" managed installation directories for tests, // but for now... we'll just include the test interpreters which are always on the // search path. if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok() { Box::new(from_managed_installations.chain(from_search_path)) } else { Box::new(from_managed_installations) } } PythonPreference::Managed => Box::new( from_managed_installations .chain(from_search_path) .chain(from_windows_registry), ), PythonPreference::System => Box::new( from_search_path .chain(from_windows_registry) .chain(from_managed_installations), ), PythonPreference::OnlySystem => Box::new(from_search_path.chain(from_windows_registry)), } } /// Lazily iterate over all discoverable Python executables. /// /// Note that Python executables may be excluded by the given [`EnvironmentPreference`], /// [`PythonPreference`], and [`PlatformRequest`]. However, these filters are only applied for /// performance. We cannot guarantee that the all requests or preferences are satisfied until we /// query the interpreter. /// /// See [`python_executables_from_installed`] and [`python_executables_from_virtual_environments`] /// for more information on discovery. fn python_executables<'a>( version: &'a VersionRequest, implementation: Option<&'a ImplementationName>, platform: PlatformRequest, environments: EnvironmentPreference, preference: PythonPreference, preview: Preview, ) -> Box<dyn Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a> { // Always read from `UV_INTERNAL__PARENT_INTERPRETER` — it could be a system interpreter let from_parent_interpreter = iter::once_with(|| { env::var_os(EnvVars::UV_INTERNAL__PARENT_INTERPRETER) .into_iter() .map(|path| Ok((PythonSource::ParentInterpreter, PathBuf::from(path)))) }) .flatten(); // Check if the base conda environment is active let from_base_conda_environment = iter::once_with(|| { conda_environment_from_env(CondaEnvironmentKind::Base) .into_iter() .map(virtualenv_python_executable) .map(|path| Ok((PythonSource::BaseCondaPrefix, path))) }) .flatten(); let from_virtual_environments = python_executables_from_virtual_environments(); let from_installed = python_executables_from_installed(version, implementation, platform, preference, preview); // Limit the search to the relevant environment preference; this avoids unnecessary work like // traversal of the file system. Subsequent filtering should be done by the caller with // `source_satisfies_environment_preference` and `interpreter_satisfies_environment_preference`. match environments { EnvironmentPreference::OnlyVirtual => { Box::new(from_parent_interpreter.chain(from_virtual_environments)) } EnvironmentPreference::ExplicitSystem | EnvironmentPreference::Any => Box::new( from_parent_interpreter .chain(from_virtual_environments) .chain(from_base_conda_environment) .chain(from_installed), ), EnvironmentPreference::OnlySystem => Box::new( from_parent_interpreter .chain(from_base_conda_environment) .chain(from_installed), ), } } /// Lazily iterate over Python executables in the `PATH`. /// /// The [`VersionRequest`] and [`ImplementationName`] are used to determine the possible /// Python interpreter names, e.g. if looking for Python 3.9 we will look for `python3.9` /// or if looking for `PyPy` we will look for `pypy` in addition to the default names. /// /// Executables are returned in the search path order, then by specificity of the name, e.g. /// `python3.9` is preferred over `python3` and `pypy3.9` is preferred over `python3.9`. /// /// If a `version` is not provided, we will only look for default executable names e.g. /// `python3` and `python` — `python3.9` and similar will not be included. fn python_executables_from_search_path<'a>( version: &'a VersionRequest, implementation: Option<&'a ImplementationName>, ) -> impl Iterator<Item = PathBuf> + 'a { // `UV_TEST_PYTHON_PATH` can be used to override `PATH` to limit Python executable availability in the test suite let search_path = env::var_os(EnvVars::UV_TEST_PYTHON_PATH) .unwrap_or(env::var_os(EnvVars::PATH).unwrap_or_default()); let possible_names: Vec<_> = version .executable_names(implementation) .into_iter() .map(|name| name.to_string()) .collect(); trace!( "Searching PATH for executables: {}", possible_names.join(", ") ); // Split and iterate over the paths instead of using `which_all` so we can // check multiple names per directory while respecting the search path order and python names // precedence. let search_dirs: Vec<_> = env::split_paths(&search_path).collect(); let mut seen_dirs = FxHashSet::with_capacity_and_hasher(search_dirs.len(), FxBuildHasher); search_dirs .into_iter() .filter(|dir| dir.is_dir()) .flat_map(move |dir| { // Clone the directory for second closure let dir_clone = dir.clone(); trace!( "Checking `PATH` directory for interpreters: {}", dir.display() ); same_file::Handle::from_path(&dir) // Skip directories we've already seen, to avoid inspecting interpreters multiple // times when directories are repeated or symlinked in the `PATH` .map(|handle| seen_dirs.insert(handle)) .inspect(|fresh_dir| { if !fresh_dir { trace!("Skipping already seen directory: {}", dir.display()); } }) // If we cannot determine if the directory is unique, we'll assume it is .unwrap_or(true) .then(|| { possible_names .clone() .into_iter() .flat_map(move |name| { // Since we're just working with a single directory at a time, we collect to simplify ownership which::which_in_global(&*name, Some(&dir)) .into_iter() .flatten() // We have to collect since `which` requires that the regex outlives its // parameters, and the dir is local while we return the iterator. .collect::<Vec<_>>() }) .chain(find_all_minor(implementation, version, &dir_clone)) .filter(|path| !is_windows_store_shim(path)) .inspect(|path| { trace!("Found possible Python executable: {}", path.display()); }) .chain( // TODO(zanieb): Consider moving `python.bat` into `possible_names` to avoid a chain cfg!(windows) .then(move || { which::which_in_global("python.bat", Some(&dir_clone)) .into_iter() .flatten() .collect::<Vec<_>>() }) .into_iter() .flatten(), ) }) .into_iter() .flatten() }) } /// Find all acceptable `python3.x` minor versions. /// /// For example, let's say `python` and `python3` are Python 3.10. When a user requests `>= 3.11`, /// we still need to find a `python3.12` in PATH. fn find_all_minor( implementation: Option<&ImplementationName>, version_request: &VersionRequest, dir: &Path, ) -> impl Iterator<Item = PathBuf> + use<> { match version_request { &VersionRequest::Any | VersionRequest::Default | VersionRequest::Major(_, _) | VersionRequest::Range(_, _) => { let regex = if let Some(implementation) = implementation { Regex::new(&format!( r"^({}|python3)\.(?<minor>\d\d?)t?{}$", regex::escape(&implementation.to_string()), regex::escape(EXE_SUFFIX) )) .unwrap() } else { Regex::new(&format!( r"^python3\.(?<minor>\d\d?)t?{}$", regex::escape(EXE_SUFFIX) )) .unwrap() }; let all_minors = fs_err::read_dir(dir) .into_iter() .flatten() .flatten() .map(|entry| entry.path()) .filter(move |path| { let Some(filename) = path.file_name() else { return false; }; let Some(filename) = filename.to_str() else { return false; }; let Some(captures) = regex.captures(filename) else { return false; }; // Filter out interpreter we already know have a too low minor version. let minor = captures["minor"].parse().ok(); if let Some(minor) = minor { // Optimization: Skip generally unsupported Python versions without querying. if minor < 7 { return false; } // Optimization 2: Skip excluded Python (minor) versions without querying. if !version_request.matches_major_minor(3, minor) { return false; } } true }) .filter(|path| is_executable(path)) .collect::<Vec<_>>(); Either::Left(all_minors.into_iter()) } VersionRequest::MajorMinor(_, _, _) | VersionRequest::MajorMinorPatch(_, _, _, _) | VersionRequest::MajorMinorPrerelease(_, _, _, _) => Either::Right(iter::empty()), } } /// Lazily iterate over all discoverable Python interpreters. /// /// Note interpreters may be excluded by the given [`EnvironmentPreference`], [`PythonPreference`], /// [`VersionRequest`], or [`PlatformRequest`]. /// /// The [`PlatformRequest`] is currently only applied to managed Python installations before querying /// the interpreter. The caller is responsible for ensuring it is applied otherwise. /// /// See [`python_executables`] for more information on discovery. fn python_interpreters<'a>( version: &'a VersionRequest, implementation: Option<&'a ImplementationName>, platform: PlatformRequest, environments: EnvironmentPreference, preference: PythonPreference, cache: &'a Cache, preview: Preview, ) -> impl Iterator<Item = Result<(PythonSource, Interpreter), Error>> + 'a { let interpreters = python_interpreters_from_executables( // Perform filtering on the discovered executables based on their source. This avoids // unnecessary interpreter queries, which are generally expensive. We'll filter again // with `interpreter_satisfies_environment_preference` after querying. python_executables( version, implementation, platform, environments, preference, preview, ) .filter_ok(move |(source, path)| { source_satisfies_environment_preference(*source, path, environments) }), cache, ) .filter_ok(move |(source, interpreter)| { interpreter_satisfies_environment_preference(*source, interpreter, environments) }) .filter_ok(move |(source, interpreter)| { let request = version.clone().into_request_for_source(*source); if request.matches_interpreter(interpreter) { true } else { debug!( "Skipping interpreter at `{}` from {source}: does not satisfy request `{request}`", interpreter.sys_executable().user_display() ); false } }) .filter_ok(move |(source, interpreter)| { satisfies_python_preference(*source, interpreter, preference) }); if std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED).is_ok() { Either::Left(interpreters.map_ok(|(source, interpreter)| { // In test mode, change the source to `Managed` if a version was marked as such via // `TestContext::with_versions_as_managed`. if interpreter.is_managed() { (PythonSource::Managed, interpreter) } else { (source, interpreter) } })) } else { Either::Right(interpreters) } } /// Lazily convert Python executables into interpreters. fn python_interpreters_from_executables<'a>( executables: impl Iterator<Item = Result<(PythonSource, PathBuf), Error>> + 'a, cache: &'a Cache, ) -> impl Iterator<Item = Result<(PythonSource, Interpreter), Error>> + 'a { executables.map(|result| match result { Ok((source, path)) => Interpreter::query(&path, cache) .map(|interpreter| (source, interpreter)) .inspect(|(source, interpreter)| { debug!( "Found `{}` at `{}` ({source})", interpreter.key(), path.display() ); })
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/downloads.rs
crates/uv-python/src/downloads.rs
use std::borrow::Cow; use std::collections::HashMap; use std::fmt::Display; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::str::FromStr; use std::task::{Context, Poll}; use std::{env, io}; use futures::TryStreamExt; use itertools::Itertools; use owo_colors::OwoColorize; use reqwest_retry::RetryError; use reqwest_retry::policies::ExponentialBackoff; use serde::Deserialize; use thiserror::Error; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt, BufWriter, ReadBuf}; use tokio_util::compat::FuturesAsyncReadCompatExt; use tokio_util::either::Either; use tracing::{debug, instrument}; use url::Url; use uv_client::{BaseClient, RetryState, WrappedReqwestError}; use uv_distribution_filename::{ExtensionError, SourceDistExtension}; use uv_extract::hash::Hasher; use uv_fs::{Simplified, rename_with_retry}; use uv_platform::{self as platform, Arch, Libc, Os, Platform}; use uv_pypi_types::{HashAlgorithm, HashDigest}; use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError}; use uv_static::EnvVars; use crate::PythonVariant; use crate::implementation::{ Error as ImplementationError, ImplementationName, LenientImplementationName, }; use crate::installation::PythonInstallationKey; use crate::managed::ManagedPythonInstallation; use crate::python_version::{BuildVersionError, python_build_version_from_env}; use crate::{Interpreter, PythonRequest, PythonVersion, VersionRequest}; #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] ImplementationError(#[from] ImplementationError), #[error("Expected download URL (`{0}`) to end in a supported file extension: {1}")] MissingExtension(String, ExtensionError), #[error("Invalid Python version: {0}")] InvalidPythonVersion(String), #[error("Invalid request key (empty request)")] EmptyRequest, #[error("Invalid request key (too many parts): {0}")] TooManyParts(String), #[error("Failed to download {0}")] NetworkError(DisplaySafeUrl, #[source] WrappedReqwestError), #[error("Request failed after {retries} {subject}", subject = if *retries > 1 { "retries" } else { "retry" })] NetworkErrorWithRetries { #[source] err: Box<Error>, retries: u32, }, #[error("Failed to download {0}")] NetworkMiddlewareError(DisplaySafeUrl, #[source] anyhow::Error), #[error("Failed to extract archive: {0}")] ExtractError(String, #[source] uv_extract::Error), #[error("Failed to hash installation")] HashExhaustion(#[source] io::Error), #[error("Hash mismatch for `{installation}`\n\nExpected:\n{expected}\n\nComputed:\n{actual}")] HashMismatch { installation: String, expected: String, actual: String, }, #[error("Invalid download URL")] InvalidUrl(#[from] DisplaySafeUrlError), #[error("Invalid download URL: {0}")] InvalidUrlFormat(DisplaySafeUrl), #[error("Invalid path in file URL: `{0}`")] InvalidFileUrl(String), #[error("Failed to create download directory")] DownloadDirError(#[source] io::Error), #[error("Failed to copy to: {0}", to.user_display())] CopyError { to: PathBuf, #[source] err: io::Error, }, #[error("Failed to read managed Python installation directory: {0}", dir.user_display())] ReadError { dir: PathBuf, #[source] err: io::Error, }, #[error("Failed to parse request part")] InvalidRequestPlatform(#[from] platform::Error), #[error("No download found for request: {}", _0.green())] NoDownloadFound(PythonDownloadRequest), #[error("A mirror was provided via `{0}`, but the URL does not match the expected format: {0}")] Mirror(&'static str, String), #[error("Failed to determine the libc used on the current platform")] LibcDetection(#[from] platform::LibcDetectionError), #[error("Unable to parse the JSON Python download list at {0}")] InvalidPythonDownloadsJSON(String, #[source] serde_json::Error), #[error("This version of uv is too old to support the JSON Python download list at {0}")] UnsupportedPythonDownloadsJSON(String), #[error("Error while fetching remote python downloads json from '{0}'")] FetchingPythonDownloadsJSONError(String, #[source] Box<Error>), #[error("An offline Python installation was requested, but {file} (from {url}) is missing in {}", python_builds_dir.user_display())] OfflinePythonMissing { file: Box<PythonInstallationKey>, url: Box<DisplaySafeUrl>, python_builds_dir: PathBuf, }, #[error(transparent)] BuildVersion(#[from] BuildVersionError), } impl Error { // Return the number of retries that were made to complete this request before this error was // returned. // // Note that e.g. 3 retries equates to 4 attempts. fn retries(&self) -> u32 { // Unfortunately different variants of `Error` track retry counts in different ways. We // could consider unifying the variants we handle here in `Error::from_reqwest_middleware` // instead, but both approaches will be fragile as new variants get added over time. if let Self::NetworkErrorWithRetries { retries, .. } = self { return *retries; } if let Self::NetworkMiddlewareError(_, anyhow_error) = self && let Some(RetryError::WithRetries { retries, .. }) = anyhow_error.downcast_ref::<RetryError>() { return *retries; } 0 } } #[derive(Debug, PartialEq, Eq, Clone, Hash)] pub struct ManagedPythonDownload { key: PythonInstallationKey, url: Cow<'static, str>, sha256: Option<Cow<'static, str>>, build: Option<&'static str>, } #[derive(Debug, Clone, Default, Eq, PartialEq, Hash)] pub struct PythonDownloadRequest { pub(crate) version: Option<VersionRequest>, pub(crate) implementation: Option<ImplementationName>, pub(crate) arch: Option<ArchRequest>, pub(crate) os: Option<Os>, pub(crate) libc: Option<Libc>, pub(crate) build: Option<String>, /// Whether to allow pre-releases or not. If not set, defaults to true if [`Self::version`] is /// not None, and false otherwise. pub(crate) prereleases: Option<bool>, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ArchRequest { Explicit(Arch), Environment(Arch), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct PlatformRequest { pub(crate) os: Option<Os>, pub(crate) arch: Option<ArchRequest>, pub(crate) libc: Option<Libc>, } impl PlatformRequest { /// Check if this platform request is satisfied by a platform. pub fn matches(&self, platform: &Platform) -> bool { if let Some(os) = self.os { if !platform.os.supports(os) { return false; } } if let Some(arch) = self.arch { if !arch.satisfied_by(platform) { return false; } } if let Some(libc) = self.libc { if platform.libc != libc { return false; } } true } } impl Display for PlatformRequest { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut parts = Vec::new(); if let Some(os) = &self.os { parts.push(os.to_string()); } if let Some(arch) = &self.arch { parts.push(arch.to_string()); } if let Some(libc) = &self.libc { parts.push(libc.to_string()); } write!(f, "{}", parts.join("-")) } } impl Display for ArchRequest { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Explicit(arch) | Self::Environment(arch) => write!(f, "{arch}"), } } } impl ArchRequest { pub(crate) fn satisfied_by(self, platform: &Platform) -> bool { match self { Self::Explicit(request) => request == platform.arch, Self::Environment(env) => { // Check if the environment's platform can run the target platform let env_platform = Platform::new(platform.os, env, platform.libc); env_platform.supports(platform) } } } pub fn inner(&self) -> Arch { match self { Self::Explicit(arch) | Self::Environment(arch) => *arch, } } } impl PythonDownloadRequest { pub fn new( version: Option<VersionRequest>, implementation: Option<ImplementationName>, arch: Option<ArchRequest>, os: Option<Os>, libc: Option<Libc>, prereleases: Option<bool>, ) -> Self { Self { version, implementation, arch, os, libc, build: None, prereleases, } } #[must_use] pub fn with_implementation(mut self, implementation: ImplementationName) -> Self { match implementation { // Pyodide is actually CPython with an Emscripten OS, we paper over that for usability ImplementationName::Pyodide => { self = self.with_os(Os::new(target_lexicon::OperatingSystem::Emscripten)); self = self.with_arch(Arch::new(target_lexicon::Architecture::Wasm32, None)); self = self.with_libc(Libc::Some(target_lexicon::Environment::Musl)); } _ => { self.implementation = Some(implementation); } } self } #[must_use] pub fn with_version(mut self, version: VersionRequest) -> Self { self.version = Some(version); self } #[must_use] pub fn with_arch(mut self, arch: Arch) -> Self { self.arch = Some(ArchRequest::Explicit(arch)); self } #[must_use] pub fn with_any_arch(mut self) -> Self { self.arch = None; self } #[must_use] pub fn with_os(mut self, os: Os) -> Self { self.os = Some(os); self } #[must_use] pub fn with_libc(mut self, libc: Libc) -> Self { self.libc = Some(libc); self } #[must_use] pub fn with_prereleases(mut self, prereleases: bool) -> Self { self.prereleases = Some(prereleases); self } #[must_use] pub fn with_build(mut self, build: String) -> Self { self.build = Some(build); self } /// Construct a new [`PythonDownloadRequest`] from a [`PythonRequest`] if possible. /// /// Returns [`None`] if the request kind is not compatible with a download, e.g., it is /// a request for a specific directory or executable name. pub fn from_request(request: &PythonRequest) -> Option<Self> { match request { PythonRequest::Version(version) => Some(Self::default().with_version(version.clone())), PythonRequest::Implementation(implementation) => { Some(Self::default().with_implementation(*implementation)) } PythonRequest::ImplementationVersion(implementation, version) => Some( Self::default() .with_implementation(*implementation) .with_version(version.clone()), ), PythonRequest::Key(request) => Some(request.clone()), PythonRequest::Any => Some(Self { prereleases: Some(true), // Explicitly allow pre-releases for PythonRequest::Any ..Self::default() }), PythonRequest::Default => Some(Self::default()), // We can't download a managed installation for these request kinds PythonRequest::Directory(_) | PythonRequest::ExecutableName(_) | PythonRequest::File(_) => None, } } /// Fill empty entries with default values. /// /// Platform information is pulled from the environment. pub fn fill_platform(mut self) -> Result<Self, Error> { let platform = Platform::from_env()?; if self.arch.is_none() { self.arch = Some(ArchRequest::Environment(platform.arch)); } if self.os.is_none() { self.os = Some(platform.os); } if self.libc.is_none() { self.libc = Some(platform.libc); } Ok(self) } /// Fill the build field from the environment variable relevant for the [`ImplementationName`]. pub fn fill_build_from_env(mut self) -> Result<Self, Error> { if self.build.is_some() { return Ok(self); } let Some(implementation) = self.implementation else { return Ok(self); }; self.build = python_build_version_from_env(implementation)?; Ok(self) } pub fn fill(mut self) -> Result<Self, Error> { if self.implementation.is_none() { self.implementation = Some(ImplementationName::CPython); } self = self.fill_platform()?; self = self.fill_build_from_env()?; Ok(self) } pub fn implementation(&self) -> Option<&ImplementationName> { self.implementation.as_ref() } pub fn version(&self) -> Option<&VersionRequest> { self.version.as_ref() } pub fn arch(&self) -> Option<&ArchRequest> { self.arch.as_ref() } pub fn os(&self) -> Option<&Os> { self.os.as_ref() } pub fn libc(&self) -> Option<&Libc> { self.libc.as_ref() } pub fn take_version(&mut self) -> Option<VersionRequest> { self.version.take() } /// Remove default implementation and platform details so the request only contains /// explicitly user-specified segments. #[must_use] pub fn unset_defaults(self) -> Self { let request = self.unset_non_platform_defaults(); if let Ok(host) = Platform::from_env() { request.unset_platform_defaults(&host) } else { request } } fn unset_non_platform_defaults(mut self) -> Self { self.implementation = self .implementation .filter(|implementation_name| *implementation_name != ImplementationName::default()); self.version = self .version .filter(|version| !matches!(version, VersionRequest::Any | VersionRequest::Default)); // Drop implicit architecture derived from environment so only user overrides remain. self.arch = self .arch .filter(|arch| !matches!(arch, ArchRequest::Environment(_))); self } #[cfg(test)] pub(crate) fn unset_defaults_for_host(self, host: &Platform) -> Self { self.unset_non_platform_defaults() .unset_platform_defaults(host) } pub(crate) fn unset_platform_defaults(mut self, host: &Platform) -> Self { self.os = self.os.filter(|os| *os != host.os); self.libc = self.libc.filter(|libc| *libc != host.libc); self.arch = self .arch .filter(|arch| !matches!(arch, ArchRequest::Explicit(explicit_arch) if *explicit_arch == host.arch)); self } /// Drop patch and prerelease information so the request can be re-used for upgrades. #[must_use] pub fn without_patch(mut self) -> Self { self.version = self.version.take().map(VersionRequest::only_minor); self.prereleases = None; self.build = None; self } /// Return a compact string representation suitable for user-facing display. /// /// The resulting string only includes explicitly-set pieces of the request and returns /// [`None`] when no segments are explicitly set. pub fn simplified_display(self) -> Option<String> { let parts = [ self.implementation .map(|implementation| implementation.to_string()), self.version.map(|version| version.to_string()), self.os.map(|os| os.to_string()), self.arch.map(|arch| arch.to_string()), self.libc.map(|libc| libc.to_string()), ]; let joined = parts.into_iter().flatten().collect::<Vec<_>>().join("-"); if joined.is_empty() { None } else { Some(joined) } } /// Whether this request is satisfied by an installation key. pub fn satisfied_by_key(&self, key: &PythonInstallationKey) -> bool { // Check platform requirements let request = PlatformRequest { os: self.os, arch: self.arch, libc: self.libc, }; if !request.matches(key.platform()) { return false; } if let Some(implementation) = &self.implementation { if key.implementation != LenientImplementationName::from(*implementation) { return false; } } // If we don't allow pre-releases, don't match a key with a pre-release tag if !self.allows_prereleases() && key.prerelease.is_some() { return false; } if let Some(version) = &self.version { if !version.matches_major_minor_patch_prerelease( key.major, key.minor, key.patch, key.prerelease, ) { return false; } if let Some(variant) = version.variant() { if variant != key.variant { return false; } } } true } /// Whether this request is satisfied by a Python download. pub fn satisfied_by_download(&self, download: &ManagedPythonDownload) -> bool { // First check the key if !self.satisfied_by_key(download.key()) { return false; } // Then check the build if specified if let Some(ref requested_build) = self.build { let Some(download_build) = download.build() else { debug!( "Skipping download `{}`: a build version was requested but is not available for this download", download ); return false; }; if download_build != requested_build { debug!( "Skipping download `{}`: requested build version `{}` does not match download build version `{}`", download, requested_build, download_build ); return false; } } true } /// Whether this download request opts-in to pre-release Python versions. pub fn allows_prereleases(&self) -> bool { self.prereleases.unwrap_or_else(|| { self.version .as_ref() .is_some_and(VersionRequest::allows_prereleases) }) } /// Whether this download request opts-in to a debug Python version. pub fn allows_debug(&self) -> bool { self.version.as_ref().is_some_and(VersionRequest::is_debug) } /// Whether this download request opts-in to alternative Python implementations. pub fn allows_alternative_implementations(&self) -> bool { self.implementation .is_some_and(|implementation| !matches!(implementation, ImplementationName::CPython)) || self.os.is_some_and(|os| os.is_emscripten()) } pub fn satisfied_by_interpreter(&self, interpreter: &Interpreter) -> bool { let executable = interpreter.sys_executable().display(); if let Some(version) = self.version() { if !version.matches_interpreter(interpreter) { let interpreter_version = interpreter.python_version(); debug!( "Skipping interpreter at `{executable}`: version `{interpreter_version}` does not match request `{version}`" ); return false; } } let platform = self.platform(); let interpreter_platform = Platform::from(interpreter.platform()); if !platform.matches(&interpreter_platform) { debug!( "Skipping interpreter at `{executable}`: platform `{interpreter_platform}` does not match request `{platform}`", ); return false; } if let Some(implementation) = self.implementation() { if !implementation.matches_interpreter(interpreter) { debug!( "Skipping interpreter at `{executable}`: implementation `{}` does not match request `{implementation}`", interpreter.implementation_name(), ); return false; } } true } /// Extract the platform components of this request. pub fn platform(&self) -> PlatformRequest { PlatformRequest { os: self.os, arch: self.arch, libc: self.libc, } } } impl TryFrom<&PythonInstallationKey> for PythonDownloadRequest { type Error = LenientImplementationName; fn try_from(key: &PythonInstallationKey) -> Result<Self, Self::Error> { let implementation = match key.implementation().into_owned() { LenientImplementationName::Known(name) => name, unknown @ LenientImplementationName::Unknown(_) => return Err(unknown), }; Ok(Self::new( Some(VersionRequest::MajorMinor( key.major(), key.minor(), *key.variant(), )), Some(implementation), Some(ArchRequest::Explicit(*key.arch())), Some(*key.os()), Some(*key.libc()), Some(key.prerelease().is_some()), )) } } impl From<&ManagedPythonInstallation> for PythonDownloadRequest { fn from(installation: &ManagedPythonInstallation) -> Self { let key = installation.key(); Self::new( Some(VersionRequest::from(&key.version())), match &key.implementation { LenientImplementationName::Known(implementation) => Some(*implementation), LenientImplementationName::Unknown(name) => unreachable!( "Managed Python installations are expected to always have known implementation names, found {name}" ), }, Some(ArchRequest::Explicit(*key.arch())), Some(*key.os()), Some(*key.libc()), Some(key.prerelease.is_some()), ) } } impl Display for PythonDownloadRequest { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut parts = Vec::new(); if let Some(implementation) = self.implementation { parts.push(implementation.to_string()); } else { parts.push("any".to_string()); } if let Some(version) = &self.version { parts.push(version.to_string()); } else { parts.push("any".to_string()); } if let Some(os) = &self.os { parts.push(os.to_string()); } else { parts.push("any".to_string()); } if let Some(arch) = self.arch { parts.push(arch.to_string()); } else { parts.push("any".to_string()); } if let Some(libc) = self.libc { parts.push(libc.to_string()); } else { parts.push("any".to_string()); } write!(f, "{}", parts.join("-")) } } impl FromStr for PythonDownloadRequest { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { #[derive(Debug, Clone)] enum Position { Start, Implementation, Version, Os, Arch, Libc, End, } impl Position { pub(crate) fn next(&self) -> Self { match self { Self::Start => Self::Implementation, Self::Implementation => Self::Version, Self::Version => Self::Os, Self::Os => Self::Arch, Self::Arch => Self::Libc, Self::Libc => Self::End, Self::End => Self::End, } } } #[derive(Debug)] struct State<'a, P: Iterator<Item = &'a str>> { parts: P, part: Option<&'a str>, position: Position, error: Option<Error>, count: usize, } impl<'a, P: Iterator<Item = &'a str>> State<'a, P> { fn new(parts: P) -> Self { Self { parts, part: None, position: Position::Start, error: None, count: 0, } } fn next_part(&mut self) { self.next_position(); self.part = self.parts.next(); self.count += 1; self.error.take(); } fn next_position(&mut self) { self.position = self.position.next(); } fn record_err(&mut self, err: Error) { // For now, we only record the first error encountered. We could record all of the // errors for a given part, then pick the most appropriate one later. self.error.get_or_insert(err); } } if s.is_empty() { return Err(Error::EmptyRequest); } let mut parts = s.split('-'); let mut implementation = None; let mut version = None; let mut os = None; let mut arch = None; let mut libc = None; let mut state = State::new(parts.by_ref()); state.next_part(); loop { let Some(part) = state.part else { break }; match state.position { Position::Start => unreachable!("We start before the loop"), Position::Implementation => { if part.eq_ignore_ascii_case("any") { state.next_part(); continue; } match ImplementationName::from_str(part) { Ok(val) => { implementation = Some(val); state.next_part(); } Err(err) => { state.next_position(); state.record_err(err.into()); } } } Position::Version => { if part.eq_ignore_ascii_case("any") { state.next_part(); continue; } match VersionRequest::from_str(part) .map_err(|_| Error::InvalidPythonVersion(part.to_string())) { // Err(err) if !first_part => return Err(err), Ok(val) => { version = Some(val); state.next_part(); } Err(err) => { state.next_position(); state.record_err(err); } } } Position::Os => { if part.eq_ignore_ascii_case("any") { state.next_part(); continue; } match Os::from_str(part) { Ok(val) => { os = Some(val); state.next_part(); } Err(err) => { state.next_position(); state.record_err(err.into()); } } } Position::Arch => { if part.eq_ignore_ascii_case("any") { state.next_part(); continue; } match Arch::from_str(part) { Ok(val) => { arch = Some(ArchRequest::Explicit(val)); state.next_part(); } Err(err) => { state.next_position(); state.record_err(err.into()); } } } Position::Libc => { if part.eq_ignore_ascii_case("any") { state.next_part(); continue; } match Libc::from_str(part) { Ok(val) => { libc = Some(val); state.next_part(); } Err(err) => { state.next_position(); state.record_err(err.into()); } } } Position::End => { if state.count > 5 { return Err(Error::TooManyParts(s.to_string())); } // Throw the first error for the current part // // TODO(zanieb): It's plausible another error variant is a better match but it // sounds hard to explain how? We could peek at the next item in the parts, and // see if that informs the type of this one, or we could use some sort of // similarity or common error matching, but this sounds harder. if let Some(err) = state.error { return Err(err); } state.next_part(); } } } Ok(Self::new(version, implementation, arch, os, libc, None)) } } const BUILTIN_PYTHON_DOWNLOADS_JSON: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/download-metadata-minified.json")); pub struct ManagedPythonDownloadList { downloads: Vec<ManagedPythonDownload>, } #[derive(Debug, Deserialize, Clone)] struct JsonPythonDownload { name: String, arch: JsonArch, os: String, libc: String, major: u8, minor: u8, patch: u8, prerelease: Option<String>, url: String, sha256: Option<String>, variant: Option<String>, build: Option<String>, } #[derive(Debug, Deserialize, Clone)] struct JsonArch { family: String, variant: Option<String>, } #[derive(Debug, Clone)] pub enum DownloadResult { AlreadyAvailable(PathBuf), Fetched(PathBuf), } /// A wrapper type to display a `ManagedPythonDownload` with its build information. pub struct ManagedPythonDownloadWithBuild<'a>(&'a ManagedPythonDownload); impl Display for ManagedPythonDownloadWithBuild<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { if let Some(build) = self.0.build { write!(f, "{}+{}", self.0.key, build) } else { write!(f, "{}", self.0.key) } } } impl ManagedPythonDownloadList { /// Iterate over all [`ManagedPythonDownload`]s. fn iter_all(&self) -> impl Iterator<Item = &ManagedPythonDownload> { self.downloads.iter() } /// Iterate over all [`ManagedPythonDownload`]s that match the request. pub fn iter_matching( &self, request: &PythonDownloadRequest, ) -> impl Iterator<Item = &ManagedPythonDownload> { self.iter_all() .filter(move |download| request.satisfied_by_download(download)) } /// Return the first [`ManagedPythonDownload`] matching a request, if any. /// /// If there is no stable version matching the request, a compatible pre-release version will /// be searched for — even if a pre-release was not explicitly requested. pub fn find(&self, request: &PythonDownloadRequest) -> Result<&ManagedPythonDownload, Error> { if let Some(download) = self.iter_matching(request).next() { return Ok(download); } if !request.allows_prereleases() { if let Some(download) = self .iter_matching(&request.clone().with_prereleases(true)) .next()
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/lib.rs
crates/uv-python/src/lib.rs
//! Find requested Python interpreters and query interpreters for information. use owo_colors::OwoColorize; use thiserror::Error; #[cfg(test)] use uv_static::EnvVars; pub use crate::discovery::{ EnvironmentPreference, Error as DiscoveryError, PythonDownloads, PythonNotFound, PythonPreference, PythonRequest, PythonSource, PythonVariant, VersionRequest, find_python_installations, satisfies_python_preference, }; pub use crate::downloads::PlatformRequest; pub use crate::environment::{InvalidEnvironmentKind, PythonEnvironment}; pub use crate::implementation::{ImplementationName, LenientImplementationName}; pub use crate::installation::{ PythonInstallation, PythonInstallationKey, PythonInstallationMinorVersionKey, }; pub use crate::interpreter::{ BrokenSymlink, Error as InterpreterError, Interpreter, canonicalize_executable, }; pub use crate::pointer_size::PointerSize; pub use crate::prefix::Prefix; pub use crate::python_version::{BuildVersionError, PythonVersion}; pub use crate::target::Target; pub use crate::version_files::{ DiscoveryOptions as VersionFileDiscoveryOptions, FilePreference as VersionFilePreference, PYTHON_VERSION_FILENAME, PYTHON_VERSIONS_FILENAME, PythonVersionFile, }; pub use crate::virtualenv::{Error as VirtualEnvError, PyVenvConfiguration, VirtualEnvironment}; mod discovery; pub mod downloads; mod environment; mod implementation; mod installation; mod interpreter; pub mod macos_dylib; pub mod managed; #[cfg(windows)] mod microsoft_store; mod pointer_size; mod prefix; mod python_version; mod sysconfig; mod target; mod version_files; mod virtualenv; #[cfg(windows)] pub mod windows_registry; #[cfg(windows)] pub(crate) const COMPANY_KEY: &str = "Astral"; #[cfg(windows)] pub(crate) const COMPANY_DISPLAY_NAME: &str = "Astral Software Inc."; #[cfg(not(test))] pub(crate) fn current_dir() -> Result<std::path::PathBuf, std::io::Error> { std::env::current_dir() } #[cfg(test)] pub(crate) fn current_dir() -> Result<std::path::PathBuf, std::io::Error> { std::env::var_os(EnvVars::PWD) .map(std::path::PathBuf::from) .map(Ok) .unwrap_or(std::env::current_dir()) } #[derive(Debug, Error)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[error(transparent)] VirtualEnv(#[from] virtualenv::Error), #[error(transparent)] Query(#[from] interpreter::Error), #[error(transparent)] Discovery(#[from] discovery::Error), #[error(transparent)] ManagedPython(#[from] managed::Error), #[error(transparent)] Download(#[from] downloads::Error), // TODO(zanieb) We might want to ensure this is always wrapped in another type #[error(transparent)] KeyError(#[from] installation::PythonInstallationKeyError), #[error("{}{}", .0, if let Some(hint) = .1 { format!("\n\n{}{} {hint}", "hint".bold().cyan(), ":".bold()) } else { String::new() })] MissingPython(PythonNotFound, Option<String>), #[error(transparent)] MissingEnvironment(#[from] environment::EnvironmentNotFound), #[error(transparent)] InvalidEnvironment(#[from] environment::InvalidEnvironment), #[error(transparent)] RetryParsing(#[from] uv_client::RetryParsingError), } impl Error { pub(crate) fn with_missing_python_hint(self, hint: String) -> Self { match self { Self::MissingPython(err, _) => Self::MissingPython(err, Some(hint)), _ => self, } } } impl From<PythonNotFound> for Error { fn from(err: PythonNotFound) -> Self { Self::MissingPython(err, None) } } // The mock interpreters are not valid on Windows so we don't have unit test coverage there // TODO(zanieb): We should write a mock interpreter script that works on Windows #[cfg(all(test, unix))] mod tests { use std::{ env, ffi::{OsStr, OsString}, path::{Path, PathBuf}, str::FromStr, }; use anyhow::Result; use assert_fs::{TempDir, fixture::ChildPath, prelude::*}; use indoc::{formatdoc, indoc}; use temp_env::with_vars; use test_log::test; use uv_preview::Preview; use uv_static::EnvVars; use uv_cache::Cache; use crate::{ PythonNotFound, PythonRequest, PythonSource, PythonVersion, implementation::ImplementationName, installation::PythonInstallation, managed::ManagedPythonInstallations, virtualenv::virtualenv_python_executable, }; use crate::{ PythonPreference, discovery::{ self, EnvironmentPreference, find_best_python_installation, find_python_installation, }, }; struct TestContext { tempdir: TempDir, cache: Cache, installations: ManagedPythonInstallations, search_path: Option<Vec<PathBuf>>, workdir: ChildPath, } impl TestContext { fn new() -> Result<Self> { let tempdir = TempDir::new()?; let workdir = tempdir.child("workdir"); workdir.create_dir_all()?; Ok(Self { tempdir, cache: Cache::temp()?, installations: ManagedPythonInstallations::temp()?, search_path: None, workdir, }) } /// Clear the search path. fn reset_search_path(&mut self) { self.search_path = None; } /// Add a directory to the search path. fn add_to_search_path(&mut self, path: PathBuf) { match self.search_path.as_mut() { Some(paths) => paths.push(path), None => self.search_path = Some(vec![path]), } } /// Create a new directory and add it to the search path. fn new_search_path_directory(&mut self, name: impl AsRef<Path>) -> Result<ChildPath> { let child = self.tempdir.child(name); child.create_dir_all()?; self.add_to_search_path(child.to_path_buf()); Ok(child) } fn run<F, R>(&self, closure: F) -> R where F: FnOnce() -> R, { self.run_with_vars(&[], closure) } fn run_with_vars<F, R>(&self, vars: &[(&str, Option<&OsStr>)], closure: F) -> R where F: FnOnce() -> R, { let path = self .search_path .as_ref() .map(|paths| env::join_paths(paths).unwrap()); let mut run_vars = vec![ // Ensure `PATH` is used (EnvVars::UV_TEST_PYTHON_PATH, None), // Ignore active virtual environments (i.e. that the dev is using) (EnvVars::VIRTUAL_ENV, None), (EnvVars::PATH, path.as_deref()), // Use the temporary python directory ( EnvVars::UV_PYTHON_INSTALL_DIR, Some(self.installations.root().as_os_str()), ), // Set a working directory (EnvVars::PWD, Some(self.workdir.path().as_os_str())), ]; for (key, value) in vars { run_vars.push((key, *value)); } with_vars(&run_vars, closure) } /// Create a fake Python interpreter executable which returns fixed metadata mocking our interpreter /// query script output. fn create_mock_interpreter( path: &Path, version: &PythonVersion, implementation: ImplementationName, system: bool, free_threaded: bool, ) -> Result<()> { let json = indoc! {r##" { "result": "success", "platform": { "os": { "name": "manylinux", "major": 2, "minor": 38 }, "arch": "x86_64" }, "manylinux_compatible": true, "standalone": true, "markers": { "implementation_name": "{IMPLEMENTATION}", "implementation_version": "{FULL_VERSION}", "os_name": "posix", "platform_machine": "x86_64", "platform_python_implementation": "{IMPLEMENTATION}", "platform_release": "6.5.0-13-generic", "platform_system": "Linux", "platform_version": "#13-Ubuntu SMP PREEMPT_DYNAMIC Fri Nov 3 12:16:05 UTC 2023", "python_full_version": "{FULL_VERSION}", "python_version": "{VERSION}", "sys_platform": "linux" }, "sys_base_exec_prefix": "/home/ferris/.pyenv/versions/{FULL_VERSION}", "sys_base_prefix": "/home/ferris/.pyenv/versions/{FULL_VERSION}", "sys_prefix": "{PREFIX}", "sys_executable": "{PATH}", "sys_path": [ "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/lib/python{VERSION}", "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages" ], "site_packages": [ "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages" ], "stdlib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}", "scheme": { "data": "/home/ferris/.pyenv/versions/{FULL_VERSION}", "include": "/home/ferris/.pyenv/versions/{FULL_VERSION}/include", "platlib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages", "purelib": "/home/ferris/.pyenv/versions/{FULL_VERSION}/lib/python{VERSION}/site-packages", "scripts": "/home/ferris/.pyenv/versions/{FULL_VERSION}/bin" }, "virtualenv": { "data": "", "include": "include", "platlib": "lib/python{VERSION}/site-packages", "purelib": "lib/python{VERSION}/site-packages", "scripts": "bin" }, "pointer_size": "64", "gil_disabled": {FREE_THREADED}, "debug_enabled": false } "##}; let json = if system { json.replace("{PREFIX}", "/home/ferris/.pyenv/versions/{FULL_VERSION}") } else { json.replace("{PREFIX}", "/home/ferris/projects/uv/.venv") }; let json = json .replace( "{PATH}", path.to_str().expect("Path can be represented as string"), ) .replace("{FULL_VERSION}", &version.to_string()) .replace("{VERSION}", &version.without_patch().to_string()) .replace("{FREE_THREADED}", &free_threaded.to_string()) .replace("{IMPLEMENTATION}", (&implementation).into()); fs_err::create_dir_all(path.parent().unwrap())?; fs_err::write( path, formatdoc! {r" #!/bin/sh echo '{json}' "}, )?; fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?; Ok(()) } fn create_mock_pyodide_interpreter(path: &Path, version: &PythonVersion) -> Result<()> { let json = indoc! {r##" { "result": "success", "platform": { "os": { "name": "pyodide", "major": 2025, "minor": 0 }, "arch": "wasm32" }, "manylinux_compatible": false, "standalone": false, "markers": { "implementation_name": "cpython", "implementation_version": "{FULL_VERSION}", "os_name": "posix", "platform_machine": "wasm32", "platform_python_implementation": "CPython", "platform_release": "4.0.9", "platform_system": "Emscripten", "platform_version": "#1", "python_full_version": "{FULL_VERSION}", "python_version": "{VERSION}", "sys_platform": "emscripten" }, "sys_base_exec_prefix": "/", "sys_base_prefix": "/", "sys_prefix": "/", "sys_executable": "{PATH}", "sys_path": [ "", "/lib/python313.zip", "/lib/python{VERSION}", "/lib/python{VERSION}/lib-dynload", "/lib/python{VERSION}/site-packages" ], "site_packages": [ "/lib/python{VERSION}/site-packages" ], "stdlib": "//lib/python{VERSION}", "scheme": { "platlib": "//lib/python{VERSION}/site-packages", "purelib": "//lib/python{VERSION}/site-packages", "include": "//include/python{VERSION}", "scripts": "//bin", "data": "/" }, "virtualenv": { "purelib": "lib/python{VERSION}/site-packages", "platlib": "lib/python{VERSION}/site-packages", "include": "include/site/python{VERSION}", "scripts": "bin", "data": "" }, "pointer_size": "32", "gil_disabled": false, "debug_enabled": false } "##}; let json = json .replace( "{PATH}", path.to_str().expect("Path can be represented as string"), ) .replace("{FULL_VERSION}", &version.to_string()) .replace("{VERSION}", &version.without_patch().to_string()); fs_err::create_dir_all(path.parent().unwrap())?; fs_err::write( path, formatdoc! {r" #!/bin/sh echo '{json}' "}, )?; fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?; Ok(()) } /// Create a mock Python 2 interpreter executable which returns a fixed error message mocking /// invocation of Python 2 with the `-I` flag as done by our query script. fn create_mock_python2_interpreter(path: &Path) -> Result<()> { let output = indoc! { r" Unknown option: -I usage: /usr/bin/python [option] ... [-c cmd | -m mod | file | -] [arg] ... Try `python -h` for more information. "}; fs_err::write( path, formatdoc! {r" #!/bin/sh echo '{output}' 1>&2 "}, )?; fs_err::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o770))?; Ok(()) } /// Create child directories in a temporary directory. fn new_search_path_directories( &mut self, names: &[impl AsRef<Path>], ) -> Result<Vec<ChildPath>> { let paths = names .iter() .map(|name| self.new_search_path_directory(name)) .collect::<Result<Vec<_>>>()?; Ok(paths) } /// Create fake Python interpreters the given Python versions. /// /// Adds them to the test context search path. fn add_python_to_workdir(&self, name: &str, version: &str) -> Result<()> { Self::create_mock_interpreter( self.workdir.child(name).as_ref(), &PythonVersion::from_str(version).expect("Test uses valid version"), ImplementationName::default(), true, false, ) } fn add_pyodide_version(&mut self, version: &'static str) -> Result<()> { let path = self.new_search_path_directory(format!("pyodide-{version}"))?; let python = format!("pyodide{}", env::consts::EXE_SUFFIX); Self::create_mock_pyodide_interpreter( &path.join(python), &PythonVersion::from_str(version).unwrap(), )?; Ok(()) } /// Create fake Python interpreters the given Python versions. /// /// Adds them to the test context search path. fn add_python_versions(&mut self, versions: &[&'static str]) -> Result<()> { let interpreters: Vec<_> = versions .iter() .map(|version| (true, ImplementationName::default(), "python", *version)) .collect(); self.add_python_interpreters(interpreters.as_slice()) } /// Create fake Python interpreters the given Python implementations and versions. /// /// Adds them to the test context search path. fn add_python_interpreters( &mut self, kinds: &[(bool, ImplementationName, &'static str, &'static str)], ) -> Result<()> { // Generate a "unique" folder name for each interpreter let names: Vec<OsString> = kinds .iter() .map(|(system, implementation, name, version)| { OsString::from_str(&format!("{system}-{implementation}-{name}-{version}")) .unwrap() }) .collect(); let paths = self.new_search_path_directories(names.as_slice())?; for (path, (system, implementation, executable, version)) in itertools::zip_eq(&paths, kinds) { let python = format!("{executable}{}", env::consts::EXE_SUFFIX); Self::create_mock_interpreter( &path.join(python), &PythonVersion::from_str(version).unwrap(), *implementation, *system, false, )?; } Ok(()) } /// Create a mock virtual environment at the given directory fn mock_venv(path: impl AsRef<Path>, version: &'static str) -> Result<()> { let executable = virtualenv_python_executable(path.as_ref()); fs_err::create_dir_all( executable .parent() .expect("A Python executable path should always have a parent"), )?; Self::create_mock_interpreter( &executable, &PythonVersion::from_str(version) .expect("A valid Python version is used for tests"), ImplementationName::default(), false, false, )?; ChildPath::new(path.as_ref().join("pyvenv.cfg")).touch()?; Ok(()) } /// Create a mock conda prefix at the given directory. /// /// These are like virtual environments but they look like system interpreters because `prefix` and `base_prefix` are equal. fn mock_conda_prefix(path: impl AsRef<Path>, version: &'static str) -> Result<()> { let executable = virtualenv_python_executable(&path); fs_err::create_dir_all( executable .parent() .expect("A Python executable path should always have a parent"), )?; Self::create_mock_interpreter( &executable, &PythonVersion::from_str(version) .expect("A valid Python version is used for tests"), ImplementationName::default(), true, false, )?; ChildPath::new(path.as_ref().join("pyvenv.cfg")).touch()?; Ok(()) } } #[test] fn find_python_empty_path() -> Result<()> { let mut context = TestContext::new()?; context.search_path = Some(vec![]); let result = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) }); assert!( matches!(result, Ok(Err(PythonNotFound { .. }))), "With an empty path, no Python installation should be detected got {result:?}" ); context.search_path = None; let result = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) }); assert!( matches!(result, Ok(Err(PythonNotFound { .. }))), "With an unset path, no Python installation should be detected got {result:?}" ); Ok(()) } #[test] fn find_python_unexecutable_file() -> Result<()> { let mut context = TestContext::new()?; context .new_search_path_directory("path")? .child(format!("python{}", env::consts::EXE_SUFFIX)) .touch()?; let result = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) }); assert!( matches!(result, Ok(Err(PythonNotFound { .. }))), "With an non-executable Python, no Python installation should be detected; got {result:?}" ); Ok(()) } #[test] fn find_python_valid_executable() -> Result<()> { let mut context = TestContext::new()?; context.add_python_versions(&["3.12.1"])?; let interpreter = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) })??; assert!( matches!( interpreter, PythonInstallation { source: PythonSource::SearchPathFirst, interpreter: _ } ), "We should find the valid executable; got {interpreter:?}" ); Ok(()) } #[test] fn find_python_valid_executable_after_invalid() -> Result<()> { let mut context = TestContext::new()?; let children = context.new_search_path_directories(&[ "query-parse-error", "not-executable", "empty", "good", ])?; // An executable file with a bad response #[cfg(unix)] fs_err::write( children[0].join(format!("python{}", env::consts::EXE_SUFFIX)), formatdoc! {r" #!/bin/sh echo 'foo' "}, )?; fs_err::set_permissions( children[0].join(format!("python{}", env::consts::EXE_SUFFIX)), std::os::unix::fs::PermissionsExt::from_mode(0o770), )?; // A non-executable file ChildPath::new(children[1].join(format!("python{}", env::consts::EXE_SUFFIX))).touch()?; // An empty directory at `children[2]` // An good interpreter! let python_path = children[3].join(format!("python{}", env::consts::EXE_SUFFIX)); TestContext::create_mock_interpreter( &python_path, &PythonVersion::from_str("3.12.1").unwrap(), ImplementationName::default(), true, false, )?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) })??; assert!( matches!( python, PythonInstallation { source: PythonSource::SearchPath, interpreter: _ } ), "We should skip the bad executables in favor of the good one; got {python:?}" ); assert_eq!(python.interpreter().sys_executable(), python_path); Ok(()) } #[test] fn find_python_only_python2_executable() -> Result<()> { let mut context = TestContext::new()?; let python = context .new_search_path_directory("python2")? .child(format!("python{}", env::consts::EXE_SUFFIX)); TestContext::create_mock_python2_interpreter(&python)?; let result = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) }); assert!( matches!(result, Err(discovery::Error::Query(..))), "If only Python 2 is available, we should report the interpreter query error; got {result:?}" ); Ok(()) } #[test] fn find_python_skip_python2_executable() -> Result<()> { let mut context = TestContext::new()?; let python2 = context .new_search_path_directory("python2")? .child(format!("python{}", env::consts::EXE_SUFFIX)); TestContext::create_mock_python2_interpreter(&python2)?; let python3 = context .new_search_path_directory("python3")? .child(format!("python{}", env::consts::EXE_SUFFIX)); TestContext::create_mock_interpreter( &python3, &PythonVersion::from_str("3.12.1").unwrap(), ImplementationName::default(), true, false, )?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::default(), &context.cache, Preview::default(), ) })??; assert!( matches!( python, PythonInstallation { source: PythonSource::SearchPath, interpreter: _ } ), "We should skip the Python 2 installation and find the Python 3 interpreter; got {python:?}" ); assert_eq!(python.interpreter().sys_executable(), python3.path()); Ok(()) } #[test] fn find_python_system_python_allowed() -> Result<()> { let mut context = TestContext::new()?; context.add_python_interpreters(&[ (false, ImplementationName::CPython, "python", "3.10.0"), (true, ImplementationName::CPython, "python", "3.10.1"), ])?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::Any, PythonPreference::OnlySystem, &context.cache, Preview::default(), ) })??; assert_eq!( python.interpreter().python_full_version().to_string(), "3.10.0", "Should find the first interpreter regardless of system" ); // Reverse the order of the virtual environment and system context.reset_search_path(); context.add_python_interpreters(&[ (true, ImplementationName::CPython, "python", "3.10.1"), (false, ImplementationName::CPython, "python", "3.10.0"), ])?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::Any, PythonPreference::OnlySystem, &context.cache, Preview::default(), ) })??; assert_eq!( python.interpreter().python_full_version().to_string(), "3.10.1", "Should find the first interpreter regardless of system" ); Ok(()) } #[test] fn find_python_system_python_required() -> Result<()> { let mut context = TestContext::new()?; context.add_python_interpreters(&[ (false, ImplementationName::CPython, "python", "3.10.0"), (true, ImplementationName::CPython, "python", "3.10.1"), ])?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::OnlySystem, PythonPreference::OnlySystem, &context.cache, Preview::default(), ) })??; assert_eq!( python.interpreter().python_full_version().to_string(), "3.10.1", "Should skip the virtual environment" ); Ok(()) } #[test] fn find_python_system_python_disallowed() -> Result<()> { let mut context = TestContext::new()?; context.add_python_interpreters(&[ (true, ImplementationName::CPython, "python", "3.10.0"), (false, ImplementationName::CPython, "python", "3.10.1"), ])?; let python = context.run(|| { find_python_installation( &PythonRequest::Default, EnvironmentPreference::Any, PythonPreference::OnlySystem, &context.cache, Preview::default(), ) })??; assert_eq!( python.interpreter().python_full_version().to_string(), "3.10.0", "Should skip the system Python" ); Ok(()) } #[test] fn find_python_version_minor() -> Result<()> { let mut context = TestContext::new()?; context.add_python_versions(&["3.10.1", "3.11.2", "3.12.3"])?; let python = context.run(|| { find_python_installation( &PythonRequest::parse("3.11"), EnvironmentPreference::Any, PythonPreference::OnlySystem, &context.cache, Preview::default(), ) })??; assert!( matches!( python, PythonInstallation { source: PythonSource::SearchPath, interpreter: _ } ), "We should find a python; got {python:?}" ); assert_eq!( &python.interpreter().python_full_version().to_string(), "3.11.2", "We should find the correct interpreter for the request" ); Ok(()) } #[test] fn find_python_version_patch() -> Result<()> { let mut context = TestContext::new()?; context.add_python_versions(&["3.10.1", "3.11.3", "3.11.2", "3.12.3"])?; let python = context.run(|| { find_python_installation( &PythonRequest::parse("3.11.2"), EnvironmentPreference::Any, PythonPreference::OnlySystem, &context.cache,
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/implementation.rs
crates/uv-python/src/implementation.rs
use std::{ fmt::{self, Display}, str::FromStr, }; use thiserror::Error; use crate::Interpreter; #[derive(Error, Debug)] pub enum Error { #[error("Unknown Python implementation `{0}`")] UnknownImplementation(String), } #[derive(Debug, Eq, PartialEq, Clone, Copy, Default, PartialOrd, Ord, Hash)] pub enum ImplementationName { Pyodide, GraalPy, PyPy, #[default] CPython, } #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] pub enum LenientImplementationName { Unknown(String), Known(ImplementationName), } impl ImplementationName { pub(crate) fn short_names() -> impl Iterator<Item = &'static str> { ["cp", "pp", "gp"].into_iter() } pub(crate) fn long_names() -> impl Iterator<Item = &'static str> { ["cpython", "pypy", "graalpy", "pyodide"].into_iter() } pub(crate) fn iter_all() -> impl Iterator<Item = Self> { [Self::CPython, Self::PyPy, Self::GraalPy, Self::Pyodide].into_iter() } pub fn pretty(self) -> &'static str { match self { Self::CPython => "CPython", Self::PyPy => "PyPy", Self::GraalPy => "GraalPy", Self::Pyodide => "Pyodide", } } pub fn executable_name(self) -> &'static str { match self { Self::CPython | Self::Pyodide => "python", Self::PyPy | Self::GraalPy => self.into(), } } pub fn matches_interpreter(self, interpreter: &Interpreter) -> bool { match self { Self::Pyodide => interpreter.os().is_emscripten(), _ => interpreter .implementation_name() .eq_ignore_ascii_case(self.into()), } } } impl LenientImplementationName { pub fn pretty(&self) -> &str { match self { Self::Known(implementation) => implementation.pretty(), Self::Unknown(name) => name, } } pub fn executable_name(&self) -> &str { match self { Self::Known(implementation) => implementation.executable_name(), Self::Unknown(name) => name, } } } impl From<&ImplementationName> for &'static str { fn from(value: &ImplementationName) -> &'static str { match value { ImplementationName::CPython => "cpython", ImplementationName::PyPy => "pypy", ImplementationName::GraalPy => "graalpy", ImplementationName::Pyodide => "pyodide", } } } impl From<ImplementationName> for &'static str { fn from(value: ImplementationName) -> &'static str { (&value).into() } } impl<'a> From<&'a LenientImplementationName> for &'a str { fn from(value: &'a LenientImplementationName) -> &'a str { match value { LenientImplementationName::Known(implementation) => implementation.into(), LenientImplementationName::Unknown(name) => name, } } } impl FromStr for ImplementationName { type Err = Error; /// Parse a Python implementation name from a string. /// /// Supports the full name and the platform compatibility tag style name. fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_ascii_lowercase().as_str() { "cpython" | "cp" => Ok(Self::CPython), "pypy" | "pp" => Ok(Self::PyPy), "graalpy" | "gp" => Ok(Self::GraalPy), "pyodide" => Ok(Self::Pyodide), _ => Err(Error::UnknownImplementation(s.to_string())), } } } impl Display for ImplementationName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.into()) } } impl From<&str> for LenientImplementationName { fn from(s: &str) -> Self { match ImplementationName::from_str(s) { Ok(implementation) => Self::Known(implementation), Err(_) => Self::Unknown(s.to_string()), } } } impl From<ImplementationName> for LenientImplementationName { fn from(implementation: ImplementationName) -> Self { Self::Known(implementation) } } impl Display for LenientImplementationName { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Known(implementation) => implementation.fmt(f), Self::Unknown(name) => f.write_str(&name.to_ascii_lowercase()), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/pointer_size.rs
crates/uv-python/src/pointer_size.rs
use serde::{Deserialize, Serialize}; #[derive(Debug, Copy, Clone, Serialize, Deserialize)] pub enum PointerSize { /// 32-bit architecture. #[serde(rename = "32")] _32, /// 64-bit architecture. #[serde(rename = "64")] _64, } impl PointerSize { pub const fn is_32(self) -> bool { matches!(self, Self::_32) } pub const fn is_64(self) -> bool { matches!(self, Self::_64) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/prefix.rs
crates/uv-python/src/prefix.rs
use std::path::{Path, PathBuf}; use uv_pypi_types::Scheme; /// A `--prefix` directory into which packages can be installed, separate from a virtual environment /// or system Python interpreter. #[derive(Debug, Clone)] pub struct Prefix(PathBuf); impl Prefix { /// Return the [`Scheme`] for the `--prefix` directory. pub fn scheme(&self, virtualenv: &Scheme) -> Scheme { Scheme { purelib: self.0.join(&virtualenv.purelib), platlib: self.0.join(&virtualenv.platlib), scripts: self.0.join(&virtualenv.scripts), data: self.0.join(&virtualenv.data), include: self.0.join(&virtualenv.include), } } /// Return an iterator over the `site-packages` directories inside the environment. pub fn site_packages(&self, virtualenv: &Scheme) -> impl Iterator<Item = PathBuf> { std::iter::once(self.0.join(&virtualenv.purelib)) } /// Initialize the `--prefix` directory. pub fn init(&self, virtualenv: &Scheme) -> std::io::Result<()> { for site_packages in self.site_packages(virtualenv) { fs_err::create_dir_all(site_packages)?; } Ok(()) } /// Return the path to the `--prefix` directory. pub fn root(&self) -> &Path { &self.0 } } impl From<PathBuf> for Prefix { fn from(path: PathBuf) -> Self { Self(path) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/environment.rs
crates/uv-python/src/environment.rs
use std::borrow::Cow; use std::fmt; use std::path::{Path, PathBuf}; use std::sync::Arc; use owo_colors::OwoColorize; use tracing::debug; use uv_cache::Cache; use uv_fs::{LockedFile, LockedFileError, Simplified}; use uv_pep440::Version; use uv_preview::Preview; use crate::discovery::find_python_installation; use crate::installation::PythonInstallation; use crate::virtualenv::{PyVenvConfiguration, virtualenv_python_executable}; use crate::{ EnvironmentPreference, Error, Interpreter, Prefix, PythonNotFound, PythonPreference, PythonRequest, Target, }; /// A Python environment, consisting of a Python [`Interpreter`] and its associated paths. #[derive(Debug, Clone)] pub struct PythonEnvironment(Arc<PythonEnvironmentShared>); #[derive(Debug, Clone)] struct PythonEnvironmentShared { root: PathBuf, interpreter: Interpreter, } /// The result of failed environment discovery. /// /// Generally this is cast from [`PythonNotFound`] by [`PythonEnvironment::find`]. #[derive(Clone, Debug, Error)] pub struct EnvironmentNotFound { request: PythonRequest, preference: EnvironmentPreference, } #[derive(Clone, Debug, Error)] pub struct InvalidEnvironment { path: PathBuf, pub kind: InvalidEnvironmentKind, } #[derive(Debug, Clone)] pub enum InvalidEnvironmentKind { NotDirectory, Empty, MissingExecutable(PathBuf), } impl From<PythonNotFound> for EnvironmentNotFound { fn from(value: PythonNotFound) -> Self { Self { request: value.request, preference: value.environment_preference, } } } impl fmt::Display for EnvironmentNotFound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { #[derive(Debug, Copy, Clone)] enum SearchType { /// Only virtual environments were searched. Virtual, /// Only system installations were searched. System, /// Both virtual and system installations were searched. VirtualOrSystem, } impl fmt::Display for SearchType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Virtual => write!(f, "virtual environment"), Self::System => write!(f, "system Python installation"), Self::VirtualOrSystem => { write!(f, "virtual environment or system Python installation") } } } } let search_type = match self.preference { EnvironmentPreference::Any => SearchType::VirtualOrSystem, EnvironmentPreference::ExplicitSystem => { if self.request.is_explicit_system() { SearchType::VirtualOrSystem } else { SearchType::Virtual } } EnvironmentPreference::OnlySystem => SearchType::System, EnvironmentPreference::OnlyVirtual => SearchType::Virtual, }; if matches!(self.request, PythonRequest::Default | PythonRequest::Any) { write!(f, "No {search_type} found")?; } else { write!(f, "No {search_type} found for {}", self.request)?; } match search_type { // This error message assumes that the relevant API accepts the `--system` flag. This // is true of the callsites today, since the project APIs never surface this error. SearchType::Virtual => write!( f, "; run `{}` to create an environment, or pass `{}` to install into a non-virtual environment", "uv venv".green(), "--system".green() )?, SearchType::VirtualOrSystem => { write!(f, "; run `{}` to create an environment", "uv venv".green())?; } SearchType::System => {} } Ok(()) } } impl fmt::Display for InvalidEnvironment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Invalid environment at `{}`: {}", self.path.user_display(), self.kind ) } } impl fmt::Display for InvalidEnvironmentKind { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::NotDirectory => write!(f, "expected directory but found a file"), Self::MissingExecutable(path) => { write!(f, "missing Python executable at `{}`", path.user_display()) } Self::Empty => write!(f, "directory is empty"), } } } impl PythonEnvironment { /// Find a [`PythonEnvironment`] matching the given request and preference. /// /// If looking for a Python interpreter to create a new environment, use [`PythonInstallation::find`] /// instead. pub fn find( request: &PythonRequest, preference: EnvironmentPreference, python_preference: PythonPreference, cache: &Cache, preview: Preview, ) -> Result<Self, Error> { let installation = match find_python_installation(request, preference, python_preference, cache, preview)? { Ok(installation) => installation, Err(err) => return Err(EnvironmentNotFound::from(err).into()), }; Ok(Self::from_installation(installation)) } /// Create a [`PythonEnvironment`] from the virtual environment at the given root. /// /// N.B. This function also works for system Python environments and users depend on this. pub fn from_root(root: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> { debug!( "Checking for Python environment at: `{}`", root.as_ref().user_display() ); match root.as_ref().try_exists() { Ok(true) => {} Ok(false) => { return Err(Error::MissingEnvironment(EnvironmentNotFound { preference: EnvironmentPreference::Any, request: PythonRequest::Directory(root.as_ref().to_owned()), })); } Err(err) => return Err(Error::Discovery(err.into())), } if root.as_ref().is_file() { return Err(InvalidEnvironment { path: root.as_ref().to_path_buf(), kind: InvalidEnvironmentKind::NotDirectory, } .into()); } if root .as_ref() .read_dir() .is_ok_and(|mut dir| dir.next().is_none()) { return Err(InvalidEnvironment { path: root.as_ref().to_path_buf(), kind: InvalidEnvironmentKind::Empty, } .into()); } // Note we do not canonicalize the root path or the executable path, this is important // because the path the interpreter is invoked at can determine the value of // `sys.executable`. let executable = virtualenv_python_executable(&root); // If we can't find an executable, exit before querying to provide a better error. if !(executable.is_symlink() || executable.is_file()) { return Err(InvalidEnvironment { path: root.as_ref().to_path_buf(), kind: InvalidEnvironmentKind::MissingExecutable(executable.clone()), } .into()); } let interpreter = Interpreter::query(executable, cache)?; Ok(Self(Arc::new(PythonEnvironmentShared { root: interpreter.sys_prefix().to_path_buf(), interpreter, }))) } /// Create a [`PythonEnvironment`] from an existing [`PythonInstallation`]. pub fn from_installation(installation: PythonInstallation) -> Self { Self::from_interpreter(installation.into_interpreter()) } /// Create a [`PythonEnvironment`] from an existing [`Interpreter`]. pub fn from_interpreter(interpreter: Interpreter) -> Self { Self(Arc::new(PythonEnvironmentShared { root: interpreter.sys_prefix().to_path_buf(), interpreter, })) } /// Create a [`PythonEnvironment`] from an existing [`Interpreter`] and `--target` directory. pub fn with_target(self, target: Target) -> std::io::Result<Self> { let inner = Arc::unwrap_or_clone(self.0); Ok(Self(Arc::new(PythonEnvironmentShared { interpreter: inner.interpreter.with_target(target)?, ..inner }))) } /// Create a [`PythonEnvironment`] from an existing [`Interpreter`] and `--prefix` directory. pub fn with_prefix(self, prefix: Prefix) -> std::io::Result<Self> { let inner = Arc::unwrap_or_clone(self.0); Ok(Self(Arc::new(PythonEnvironmentShared { interpreter: inner.interpreter.with_prefix(prefix)?, ..inner }))) } /// Returns the root (i.e., `prefix`) of the Python interpreter. pub fn root(&self) -> &Path { &self.0.root } /// Return the [`Interpreter`] for this virtual environment. /// /// See also [`PythonEnvironment::into_interpreter`]. pub fn interpreter(&self) -> &Interpreter { &self.0.interpreter } /// Return the [`PyVenvConfiguration`] for this environment, as extracted from the /// `pyvenv.cfg` file. pub fn cfg(&self) -> Result<PyVenvConfiguration, Error> { Ok(PyVenvConfiguration::parse(self.0.root.join("pyvenv.cfg"))?) } /// Set a key-value pair in the `pyvenv.cfg` file. pub fn set_pyvenv_cfg(&self, key: &str, value: &str) -> Result<(), Error> { let content = fs_err::read_to_string(self.0.root.join("pyvenv.cfg"))?; fs_err::write( self.0.root.join("pyvenv.cfg"), PyVenvConfiguration::set(&content, key, value), )?; Ok(()) } /// Returns `true` if the environment is "relocatable". pub fn relocatable(&self) -> bool { self.cfg().is_ok_and(|cfg| cfg.is_relocatable()) } /// Returns the location of the Python executable. pub fn python_executable(&self) -> &Path { self.0.interpreter.sys_executable() } /// Returns an iterator over the `site-packages` directories inside the environment. /// /// In most cases, `purelib` and `platlib` will be the same, and so the iterator will contain /// a single element; however, in some distributions, they may be different. /// /// Some distributions also create symbolic links from `purelib` to `platlib`; in such cases, we /// still deduplicate the entries, returning a single path. pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> { self.0.interpreter.site_packages() } /// Returns the path to the `bin` directory inside this environment. pub fn scripts(&self) -> &Path { self.0.interpreter.scripts() } /// Grab a file lock for the environment to prevent concurrent writes across processes. pub async fn lock(&self) -> Result<LockedFile, LockedFileError> { self.0.interpreter.lock().await } /// Return the [`Interpreter`] for this environment. /// /// See also [`PythonEnvironment::interpreter`]. pub fn into_interpreter(self) -> Interpreter { Arc::unwrap_or_clone(self.0).interpreter } /// Returns `true` if the [`PythonEnvironment`] uses the same underlying [`Interpreter`]. pub fn uses(&self, interpreter: &Interpreter) -> bool { // TODO(zanieb): Consider using `sysconfig.get_path("stdlib")` instead, which // should be generally robust. if cfg!(windows) { // On Windows, we can't canonicalize an interpreter based on its executable path // because the executables are separate shim files (not links). Instead, we // compare the `sys.base_prefix`. let old_base_prefix = self.interpreter().sys_base_prefix(); let selected_base_prefix = interpreter.sys_base_prefix(); old_base_prefix == selected_base_prefix } else { // On Unix, we can see if the canonicalized executable is the same file. self.interpreter().sys_executable() == interpreter.sys_executable() || same_file::is_same_file( self.interpreter().sys_executable(), interpreter.sys_executable(), ) .unwrap_or(false) } } /// Check if the `pyvenv.cfg` version is the same as the interpreter's Python version. /// /// Returns [`None`] if the versions are the consistent or there is no `pyvenv.cfg`. If the /// versions do not match, returns a tuple of the `pyvenv.cfg` and interpreter's Python versions /// for display. pub fn get_pyvenv_version_conflict(&self) -> Option<(Version, Version)> { let cfg = self.cfg().ok()?; let cfg_version = cfg.version?.into_version(); // Determine if we should be checking for patch or pre-release equality let exe_version = if cfg_version.release().get(2).is_none() { self.interpreter().python_minor_version() } else if cfg_version.pre().is_none() { self.interpreter().python_patch_version() } else { self.interpreter().python_version().clone() }; (cfg_version != exe_version).then_some((cfg_version, exe_version)) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/python_version.rs
crates/uv-python/src/python_version.rs
#[cfg(feature = "schemars")] use std::borrow::Cow; use std::collections::BTreeMap; use std::env; use std::ffi::OsString; use std::fmt::{Display, Formatter}; use std::ops::Deref; use std::str::FromStr; use thiserror::Error; use uv_pep440::Version; use uv_pep508::{MarkerEnvironment, StringVersion}; use uv_static::EnvVars; use crate::implementation::ImplementationName; #[derive(Error, Debug)] pub enum BuildVersionError { #[error("`{0}` is not valid unicode: {1:?}")] NotUnicode(&'static str, OsString), } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PythonVersion(StringVersion); impl From<StringVersion> for PythonVersion { fn from(version: StringVersion) -> Self { Self(version) } } impl Deref for PythonVersion { type Target = StringVersion; fn deref(&self) -> &Self::Target { &self.0 } } impl FromStr for PythonVersion { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let version = StringVersion::from_str(s) .map_err(|err| format!("Python version `{s}` could not be parsed: {err}"))?; if version.is_dev() { return Err(format!("Python version `{s}` is a development release")); } if version.is_local() { return Err(format!("Python version `{s}` is a local version")); } if version.epoch() != 0 { return Err(format!("Python version `{s}` has a non-zero epoch")); } if let Some(major) = version.release().first() { if u8::try_from(*major).is_err() { return Err(format!( "Python version `{s}` has an invalid major version ({major})" )); } } if let Some(minor) = version.release().get(1) { if u8::try_from(*minor).is_err() { return Err(format!( "Python version `{s}` has an invalid minor version ({minor})" )); } } if let Some(patch) = version.release().get(2) { if u8::try_from(*patch).is_err() { return Err(format!( "Python version `{s}` has an invalid patch version ({patch})" )); } } Ok(Self(version)) } } #[cfg(feature = "schemars")] impl schemars::JsonSchema for PythonVersion { fn schema_name() -> Cow<'static, str> { Cow::Borrowed("PythonVersion") } fn json_schema(_generator: &mut schemars::generate::SchemaGenerator) -> schemars::Schema { schemars::json_schema!({ "type": "string", "pattern": r"^3\.\d+(\.\d+)?$", "description": "A Python version specifier, e.g. `3.11` or `3.12.4`." }) } } impl<'de> serde::Deserialize<'de> for PythonVersion { fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { struct Visitor; impl serde::de::Visitor<'_> for Visitor { type Value = PythonVersion; fn expecting(&self, f: &mut Formatter) -> std::fmt::Result { f.write_str("a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { PythonVersion::from_str(v).map_err(serde::de::Error::custom) } } deserializer.deserialize_str(Visitor) } } impl Display for PythonVersion { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { Display::fmt(&self.0, f) } } impl PythonVersion { /// Return a [`MarkerEnvironment`] compatible with the given [`PythonVersion`], based on /// a base [`MarkerEnvironment`]. /// /// The returned [`MarkerEnvironment`] will preserve the base environment's platform markers, /// but override its Python version markers. pub fn markers(&self, base: &MarkerEnvironment) -> MarkerEnvironment { let mut markers = base.clone(); // Ex) `implementation_version == "3.12.0"` if markers.implementation_name() == "cpython" { let python_full_version = self.python_full_version(); markers = markers.with_implementation_version(StringVersion { // Retain the verbatim representation, provided by the user. string: self.0.to_string(), version: python_full_version, }); } // Ex) `python_full_version == "3.12.0"` let python_full_version = self.python_full_version(); markers = markers.with_python_full_version(StringVersion { // Retain the verbatim representation, provided by the user. string: self.0.to_string(), version: python_full_version, }); // Ex) `python_version == "3.12"` let python_version = self.python_version(); markers = markers.with_python_version(StringVersion { string: python_version.to_string(), version: python_version, }); markers } /// Return the `python_version` marker corresponding to this Python version. /// /// This should include exactly a major and minor version, but no patch version. /// /// Ex) `python_version == "3.12"` pub fn python_version(&self) -> Version { let major = self.release().first().copied().unwrap_or(0); let minor = self.release().get(1).copied().unwrap_or(0); Version::new([major, minor]) } /// Return the `python_full_version` marker corresponding to this Python version. /// /// This should include exactly a major, minor, and patch version (even if it's zero), along /// with any pre-release or post-release information. /// /// Ex) `python_full_version == "3.12.0b1"` pub fn python_full_version(&self) -> Version { let major = self.release().first().copied().unwrap_or(0); let minor = self.release().get(1).copied().unwrap_or(0); let patch = self.release().get(2).copied().unwrap_or(0); Version::new([major, minor, patch]) .with_pre(self.0.pre()) .with_post(self.0.post()) } /// Return the full parsed Python version. pub fn version(&self) -> &Version { &self.0.version } /// Return the full parsed Python version. pub fn into_version(self) -> Version { self.0.version } /// Return the major version of this Python version. pub fn major(&self) -> u8 { u8::try_from(self.0.release().first().copied().unwrap_or(0)).expect("invalid major version") } /// Return the minor version of this Python version. pub fn minor(&self) -> u8 { u8::try_from(self.0.release().get(1).copied().unwrap_or(0)).expect("invalid minor version") } /// Return the patch version of this Python version, if set. pub fn patch(&self) -> Option<u8> { self.0 .release() .get(2) .copied() .map(|patch| u8::try_from(patch).expect("invalid patch version")) } /// Returns a copy of the Python version without the patch version #[must_use] pub fn without_patch(&self) -> Self { Self::from_str(format!("{}.{}", self.major(), self.minor()).as_str()) .expect("dropping a patch should always be valid") } } /// Get the environment variable name for the build constraint for a given implementation. pub(crate) fn python_build_version_variable(implementation: ImplementationName) -> &'static str { match implementation { ImplementationName::CPython => EnvVars::UV_PYTHON_CPYTHON_BUILD, ImplementationName::PyPy => EnvVars::UV_PYTHON_PYPY_BUILD, ImplementationName::GraalPy => EnvVars::UV_PYTHON_GRAALPY_BUILD, ImplementationName::Pyodide => EnvVars::UV_PYTHON_PYODIDE_BUILD, } } /// Get the build version number from the environment variable for a given implementation. pub(crate) fn python_build_version_from_env( implementation: ImplementationName, ) -> Result<Option<String>, BuildVersionError> { let variable = python_build_version_variable(implementation); let Some(build_os) = env::var_os(variable) else { return Ok(None); }; let build = build_os .into_string() .map_err(|raw| BuildVersionError::NotUnicode(variable, raw))?; let trimmed = build.trim(); if trimmed.is_empty() { return Ok(None); } Ok(Some(trimmed.to_string())) } /// Get the build version numbers for all Python implementations. pub(crate) fn python_build_versions_from_env() -> Result<BTreeMap<ImplementationName, String>, BuildVersionError> { let mut versions = BTreeMap::new(); for implementation in ImplementationName::iter_all() { let Some(build) = python_build_version_from_env(implementation)? else { continue; }; versions.insert(implementation, build); } Ok(versions) } #[cfg(test)] mod tests { use std::str::FromStr; use uv_pep440::{Prerelease, PrereleaseKind, Version}; use crate::PythonVersion; #[test] fn python_markers() { let version = PythonVersion::from_str("3.11.0").expect("valid python version"); assert_eq!(version.python_version(), Version::new([3, 11])); assert_eq!(version.python_version().to_string(), "3.11"); assert_eq!(version.python_full_version(), Version::new([3, 11, 0])); assert_eq!(version.python_full_version().to_string(), "3.11.0"); let version = PythonVersion::from_str("3.11").expect("valid python version"); assert_eq!(version.python_version(), Version::new([3, 11])); assert_eq!(version.python_version().to_string(), "3.11"); assert_eq!(version.python_full_version(), Version::new([3, 11, 0])); assert_eq!(version.python_full_version().to_string(), "3.11.0"); let version = PythonVersion::from_str("3.11.8a1").expect("valid python version"); assert_eq!(version.python_version(), Version::new([3, 11])); assert_eq!(version.python_version().to_string(), "3.11"); assert_eq!( version.python_full_version(), Version::new([3, 11, 8]).with_pre(Some(Prerelease { kind: PrereleaseKind::Alpha, number: 1 })) ); assert_eq!(version.python_full_version().to_string(), "3.11.8a1"); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/installation.rs
crates/uv-python/src/installation.rs
use std::borrow::Cow; use std::fmt; use std::hash::{Hash, Hasher}; use std::str::FromStr; use indexmap::IndexMap; use ref_cast::RefCast; use reqwest_retry::policies::ExponentialBackoff; use tracing::{debug, info}; use uv_warnings::warn_user; use uv_cache::Cache; use uv_client::{BaseClient, BaseClientBuilder}; use uv_pep440::{Prerelease, Version}; use uv_platform::{Arch, Libc, Os, Platform}; use uv_preview::Preview; use crate::discovery::{ EnvironmentPreference, PythonRequest, find_best_python_installation, find_python_installation, }; use crate::downloads::{ DownloadResult, ManagedPythonDownload, ManagedPythonDownloadList, PythonDownloadRequest, Reporter, }; use crate::implementation::LenientImplementationName; use crate::managed::{ManagedPythonInstallation, ManagedPythonInstallations}; use crate::{ Error, ImplementationName, Interpreter, PythonDownloads, PythonPreference, PythonSource, PythonVariant, PythonVersion, downloads, }; /// A Python interpreter and accompanying tools. #[derive(Clone, Debug)] pub struct PythonInstallation { // Public in the crate for test assertions pub(crate) source: PythonSource, pub(crate) interpreter: Interpreter, } impl PythonInstallation { /// Create a new [`PythonInstallation`] from a source, interpreter tuple. pub(crate) fn from_tuple(tuple: (PythonSource, Interpreter)) -> Self { let (source, interpreter) = tuple; Self { source, interpreter, } } /// Find an installed [`PythonInstallation`]. /// /// This is the standard interface for discovering a Python installation for creating /// an environment. If interested in finding an existing environment, see /// [`PythonEnvironment::find`] instead. /// /// Note we still require an [`EnvironmentPreference`] as this can either bypass virtual environments /// or prefer them. In most cases, this should be [`EnvironmentPreference::OnlySystem`] /// but if you want to allow an interpreter from a virtual environment if it satisfies the request, /// then use [`EnvironmentPreference::Any`]. /// /// See [`find_installation`] for implementation details. pub fn find( request: &PythonRequest, environments: EnvironmentPreference, preference: PythonPreference, download_list: &ManagedPythonDownloadList, cache: &Cache, preview: Preview, ) -> Result<Self, Error> { let installation = find_python_installation(request, environments, preference, cache, preview)??; installation.warn_if_outdated_prerelease(request, download_list); Ok(installation) } /// Find an installed [`PythonInstallation`] that satisfies a requested version, if the request cannot /// be satisfied, fallback to the best available Python installation. pub fn find_best( request: &PythonRequest, environments: EnvironmentPreference, preference: PythonPreference, download_list: &ManagedPythonDownloadList, cache: &Cache, preview: Preview, ) -> Result<Self, Error> { let installation = find_best_python_installation(request, environments, preference, cache, preview)??; installation.warn_if_outdated_prerelease(request, download_list); Ok(installation) } /// Find or fetch a [`PythonInstallation`]. /// /// Unlike [`PythonInstallation::find`], if the required Python is not installed it will be installed automatically. pub async fn find_or_download( request: Option<&PythonRequest>, environments: EnvironmentPreference, preference: PythonPreference, python_downloads: PythonDownloads, client_builder: &BaseClientBuilder<'_>, cache: &Cache, reporter: Option<&dyn Reporter>, python_install_mirror: Option<&str>, pypy_install_mirror: Option<&str>, python_downloads_json_url: Option<&str>, preview: Preview, ) -> Result<Self, Error> { let request = request.unwrap_or(&PythonRequest::Default); // Python downloads are performing their own retries to catch stream errors, disable the // default retries to avoid the middleware performing uncontrolled retries. let retry_policy = client_builder.retry_policy(); let client = client_builder.clone().retries(0).build(); let download_list = ManagedPythonDownloadList::new(&client, python_downloads_json_url).await?; // Search for the installation let err = match Self::find( request, environments, preference, &download_list, cache, preview, ) { Ok(installation) => return Ok(installation), Err(err) => err, }; match err { // If Python is missing, we should attempt a download Error::MissingPython(..) => {} // If we raised a non-critical error, we should attempt a download Error::Discovery(ref err) if !err.is_critical() => {} // Otherwise, this is fatal _ => return Err(err), } // If we can't convert the request to a download, throw the original error let Some(download_request) = PythonDownloadRequest::from_request(request) else { return Err(err); }; let downloads_enabled = preference.allows_managed() && python_downloads.is_automatic() && client_builder.connectivity.is_online(); let download = download_request .clone() .fill() .map(|request| download_list.find(&request)); // Regardless of whether downloads are enabled, we want to determine if the download is // available to power error messages. However, if downloads aren't enabled, we don't want to // report any errors related to them. let download = match download { Ok(Ok(download)) => Some(download), // If the download cannot be found, return the _original_ discovery error Ok(Err(downloads::Error::NoDownloadFound(_))) => { if downloads_enabled { debug!("No downloads are available for {request}"); return Err(err); } None } Err(err) | Ok(Err(err)) => { if downloads_enabled { // We failed to determine the platform information return Err(err.into()); } None } }; let Some(download) = download else { // N.B. We should only be in this case when downloads are disabled; when downloads are // enabled, we should fail eagerly when something goes wrong with the download. debug_assert!(!downloads_enabled); return Err(err); }; // If the download is available, but not usable, we attach a hint to the original error. if !downloads_enabled { let for_request = match request { PythonRequest::Default | PythonRequest::Any => String::new(), _ => format!(" for {request}"), }; match python_downloads { PythonDownloads::Automatic => {} PythonDownloads::Manual => { return Err(err.with_missing_python_hint(format!( "A managed Python download is available{for_request}, but Python downloads are set to 'manual', use `uv python install {}` to install the required version", request.to_canonical_string(), ))); } PythonDownloads::Never => { return Err(err.with_missing_python_hint(format!( "A managed Python download is available{for_request}, but Python downloads are set to 'never'" ))); } } match preference { PythonPreference::OnlySystem => { return Err(err.with_missing_python_hint(format!( "A managed Python download is available{for_request}, but the Python preference is set to 'only system'" ))); } PythonPreference::Managed | PythonPreference::OnlyManaged | PythonPreference::System => {} } if !client_builder.connectivity.is_online() { return Err(err.with_missing_python_hint(format!( "A managed Python download is available{for_request}, but uv is set to offline mode" ))); } return Err(err); } let installation = Self::fetch( download, &client, &retry_policy, cache, reporter, python_install_mirror, pypy_install_mirror, preview, ) .await?; installation.warn_if_outdated_prerelease(request, &download_list); Ok(installation) } /// Download and install the requested installation. pub async fn fetch( download: &ManagedPythonDownload, client: &BaseClient, retry_policy: &ExponentialBackoff, cache: &Cache, reporter: Option<&dyn Reporter>, python_install_mirror: Option<&str>, pypy_install_mirror: Option<&str>, preview: Preview, ) -> Result<Self, Error> { let installations = ManagedPythonInstallations::from_settings(None)?.init()?; let installations_dir = installations.root(); let scratch_dir = installations.scratch(); let _lock = installations.lock().await?; info!("Fetching requested Python..."); let result = download .fetch_with_retry( client, retry_policy, installations_dir, &scratch_dir, false, python_install_mirror, pypy_install_mirror, reporter, ) .await?; let path = match result { DownloadResult::AlreadyAvailable(path) => path, DownloadResult::Fetched(path) => path, }; let installed = ManagedPythonInstallation::new(path, download); installed.ensure_externally_managed()?; installed.ensure_sysconfig_patched()?; installed.ensure_canonical_executables()?; installed.ensure_build_file()?; let minor_version = installed.minor_version_key(); let highest_patch = installations .find_all()? .filter(|installation| installation.minor_version_key() == minor_version) .filter_map(|installation| installation.version().patch()) .fold(0, std::cmp::max); if installed .version() .patch() .is_some_and(|p| p >= highest_patch) { installed.ensure_minor_version_link(preview)?; } if let Err(e) = installed.ensure_dylib_patched() { e.warn_user(&installed); } Ok(Self { source: PythonSource::Managed, interpreter: Interpreter::query(installed.executable(false), cache)?, }) } /// Create a [`PythonInstallation`] from an existing [`Interpreter`]. pub fn from_interpreter(interpreter: Interpreter) -> Self { Self { source: PythonSource::ProvidedPath, interpreter, } } /// Return the [`PythonSource`] of the Python installation, indicating where it was found. pub fn source(&self) -> &PythonSource { &self.source } pub fn key(&self) -> PythonInstallationKey { self.interpreter.key() } /// Return the Python [`Version`] of the Python installation as reported by its interpreter. pub fn python_version(&self) -> &Version { self.interpreter.python_version() } /// Return the [`LenientImplementationName`] of the Python installation as reported by its interpreter. pub fn implementation(&self) -> LenientImplementationName { LenientImplementationName::from(self.interpreter.implementation_name()) } /// Whether this is a CPython installation. /// /// Returns false if it is an alternative implementation, e.g., PyPy. pub(crate) fn is_alternative_implementation(&self) -> bool { !matches!( self.implementation(), LenientImplementationName::Known(ImplementationName::CPython) ) || self.os().is_emscripten() } /// Return the [`Arch`] of the Python installation as reported by its interpreter. pub fn arch(&self) -> Arch { self.interpreter.arch() } /// Return the [`Libc`] of the Python installation as reported by its interpreter. pub fn libc(&self) -> Libc { self.interpreter.libc() } /// Return the [`Os`] of the Python installation as reported by its interpreter. pub fn os(&self) -> Os { self.interpreter.os() } /// Return the [`Interpreter`] for the Python installation. pub fn interpreter(&self) -> &Interpreter { &self.interpreter } /// Consume the [`PythonInstallation`] and return the [`Interpreter`]. pub fn into_interpreter(self) -> Interpreter { self.interpreter } /// Emit a warning when the interpreter is a managed prerelease and a matching stable /// build can be installed via `uv python upgrade`. pub(crate) fn warn_if_outdated_prerelease( &self, request: &PythonRequest, download_list: &ManagedPythonDownloadList, ) { if request.allows_prereleases() { return; } let interpreter = self.interpreter(); let version = interpreter.python_version(); if version.pre().is_none() { return; } if !interpreter.is_managed() { return; } // Transparent upgrades only exist for CPython, so skip the warning for other // managed implementations. // // See: https://github.com/astral-sh/uv/issues/16675 if !interpreter .implementation_name() .eq_ignore_ascii_case("cpython") { return; } let release = version.only_release(); let Ok(download_request) = PythonDownloadRequest::try_from(&interpreter.key()) else { return; }; let download_request = download_request.with_prereleases(false); let has_stable_download = { let mut downloads = download_list.iter_matching(&download_request); downloads.any(|download| { let download_version = download.key().version().into_version(); download_version.pre().is_none() && download_version.only_release() >= release }) }; if !has_stable_download { return; } if let Some(upgrade_request) = download_request .unset_defaults() .without_patch() .simplified_display() { warn_user!( "You're using a pre-release version of Python ({}) but a stable version is available. Use `uv python upgrade {}` to upgrade.", version, upgrade_request ); } else { warn_user!( "You're using a pre-release version of Python ({}) but a stable version is available. Run `uv python upgrade` to update your managed interpreters.", version, ); } } } #[derive(Error, Debug)] pub enum PythonInstallationKeyError { #[error("Failed to parse Python installation key `{0}`: {1}")] ParseError(String, String), } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PythonInstallationKey { pub(crate) implementation: LenientImplementationName, pub(crate) major: u8, pub(crate) minor: u8, pub(crate) patch: u8, pub(crate) prerelease: Option<Prerelease>, pub(crate) platform: Platform, pub(crate) variant: PythonVariant, } impl PythonInstallationKey { pub fn new( implementation: LenientImplementationName, major: u8, minor: u8, patch: u8, prerelease: Option<Prerelease>, platform: Platform, variant: PythonVariant, ) -> Self { Self { implementation, major, minor, patch, prerelease, platform, variant, } } pub fn new_from_version( implementation: LenientImplementationName, version: &PythonVersion, platform: Platform, variant: PythonVariant, ) -> Self { Self { implementation, major: version.major(), minor: version.minor(), patch: version.patch().unwrap_or_default(), prerelease: version.pre(), platform, variant, } } pub fn implementation(&self) -> Cow<'_, LenientImplementationName> { if self.os().is_emscripten() { Cow::Owned(LenientImplementationName::from(ImplementationName::Pyodide)) } else { Cow::Borrowed(&self.implementation) } } pub fn version(&self) -> PythonVersion { PythonVersion::from_str(&format!( "{}.{}.{}{}", self.major, self.minor, self.patch, self.prerelease .map(|pre| pre.to_string()) .unwrap_or_default() )) .expect("Python installation keys must have valid Python versions") } /// The version in `x.y.z` format. pub fn sys_version(&self) -> String { format!("{}.{}.{}", self.major, self.minor, self.patch) } pub fn major(&self) -> u8 { self.major } pub fn minor(&self) -> u8 { self.minor } pub fn prerelease(&self) -> Option<Prerelease> { self.prerelease } pub fn platform(&self) -> &Platform { &self.platform } pub fn arch(&self) -> &Arch { &self.platform.arch } pub fn os(&self) -> &Os { &self.platform.os } pub fn libc(&self) -> &Libc { &self.platform.libc } pub fn variant(&self) -> &PythonVariant { &self.variant } /// Return a canonical name for a minor versioned executable. pub fn executable_name_minor(&self) -> String { format!( "python{maj}.{min}{var}{exe}", maj = self.major, min = self.minor, var = self.variant.executable_suffix(), exe = std::env::consts::EXE_SUFFIX ) } /// Return a canonical name for a major versioned executable. pub fn executable_name_major(&self) -> String { format!( "python{maj}{var}{exe}", maj = self.major, var = self.variant.executable_suffix(), exe = std::env::consts::EXE_SUFFIX ) } /// Return a canonical name for an un-versioned executable. pub fn executable_name(&self) -> String { format!( "python{var}{exe}", var = self.variant.executable_suffix(), exe = std::env::consts::EXE_SUFFIX ) } } impl fmt::Display for PythonInstallationKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let variant = match self.variant { PythonVariant::Default => String::new(), _ => format!("+{}", self.variant), }; write!( f, "{}-{}.{}.{}{}{}-{}", self.implementation(), self.major, self.minor, self.patch, self.prerelease .map(|pre| pre.to_string()) .unwrap_or_default(), variant, self.platform ) } } impl FromStr for PythonInstallationKey { type Err = PythonInstallationKeyError; fn from_str(key: &str) -> Result<Self, Self::Err> { let parts = key.split('-').collect::<Vec<_>>(); // We need exactly implementation-version-os-arch-libc if parts.len() != 5 { return Err(PythonInstallationKeyError::ParseError( key.to_string(), format!( "expected exactly 5 `-`-separated values, got {}", parts.len() ), )); } let [implementation_str, version_str, os, arch, libc] = parts.as_slice() else { unreachable!() }; let implementation = LenientImplementationName::from(*implementation_str); let (version, variant) = match version_str.split_once('+') { Some((version, variant)) => { let variant = PythonVariant::from_str(variant).map_err(|()| { PythonInstallationKeyError::ParseError( key.to_string(), format!("invalid Python variant: {variant}"), ) })?; (version, variant) } None => (*version_str, PythonVariant::Default), }; let version = PythonVersion::from_str(version).map_err(|err| { PythonInstallationKeyError::ParseError( key.to_string(), format!("invalid Python version: {err}"), ) })?; let platform = Platform::from_parts(os, arch, libc).map_err(|err| { PythonInstallationKeyError::ParseError( key.to_string(), format!("invalid platform: {err}"), ) })?; Ok(Self { implementation, major: version.major(), minor: version.minor(), patch: version.patch().unwrap_or_default(), prerelease: version.pre(), platform, variant, }) } } impl PartialOrd for PythonInstallationKey { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(other)) } } impl Ord for PythonInstallationKey { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.implementation .cmp(&other.implementation) .then_with(|| self.version().cmp(&other.version())) // Platforms are sorted in preferred order for the target .then_with(|| self.platform.cmp(&other.platform).reverse()) // Python variants are sorted in preferred order, with `Default` first .then_with(|| self.variant.cmp(&other.variant).reverse()) } } /// A view into a [`PythonInstallationKey`] that excludes the patch and prerelease versions. #[derive(Clone, Eq, Ord, PartialOrd, RefCast)] #[repr(transparent)] pub struct PythonInstallationMinorVersionKey(PythonInstallationKey); impl PythonInstallationMinorVersionKey { /// Cast a `&PythonInstallationKey` to a `&PythonInstallationMinorVersionKey` using ref-cast. #[inline] pub fn ref_cast(key: &PythonInstallationKey) -> &Self { RefCast::ref_cast(key) } /// Takes an [`IntoIterator`] of [`ManagedPythonInstallation`]s and returns an [`FxHashMap`] from /// [`PythonInstallationMinorVersionKey`] to the installation with highest [`PythonInstallationKey`] /// for that minor version key. #[inline] pub fn highest_installations_by_minor_version_key<'a, I>( installations: I, ) -> IndexMap<Self, ManagedPythonInstallation> where I: IntoIterator<Item = &'a ManagedPythonInstallation>, { let mut minor_versions = IndexMap::default(); for installation in installations { minor_versions .entry(installation.minor_version_key().clone()) .and_modify(|high_installation: &mut ManagedPythonInstallation| { if installation.key() >= high_installation.key() { *high_installation = installation.clone(); } }) .or_insert_with(|| installation.clone()); } minor_versions } } impl fmt::Display for PythonInstallationMinorVersionKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Display every field on the wrapped key except the patch // and prerelease (with special formatting for the variant). let variant = match self.0.variant { PythonVariant::Default => String::new(), _ => format!("+{}", self.0.variant), }; write!( f, "{}-{}.{}{}-{}", self.0.implementation, self.0.major, self.0.minor, variant, self.0.platform, ) } } impl fmt::Debug for PythonInstallationMinorVersionKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // Display every field on the wrapped key except the patch // and prerelease. f.debug_struct("PythonInstallationMinorVersionKey") .field("implementation", &self.0.implementation) .field("major", &self.0.major) .field("minor", &self.0.minor) .field("variant", &self.0.variant) .field("os", &self.0.platform.os) .field("arch", &self.0.platform.arch) .field("libc", &self.0.platform.libc) .finish() } } impl PartialEq for PythonInstallationMinorVersionKey { fn eq(&self, other: &Self) -> bool { // Compare every field on the wrapped key except the patch // and prerelease. self.0.implementation == other.0.implementation && self.0.major == other.0.major && self.0.minor == other.0.minor && self.0.platform == other.0.platform && self.0.variant == other.0.variant } } impl Hash for PythonInstallationMinorVersionKey { fn hash<H: Hasher>(&self, state: &mut H) { // Hash every field on the wrapped key except the patch // and prerelease. self.0.implementation.hash(state); self.0.major.hash(state); self.0.minor.hash(state); self.0.platform.hash(state); self.0.variant.hash(state); } } impl From<PythonInstallationKey> for PythonInstallationMinorVersionKey { fn from(key: PythonInstallationKey) -> Self { Self(key) } } #[cfg(test)] mod tests { use super::*; use uv_platform::ArchVariant; #[test] fn test_python_installation_key_from_str() { // Test basic parsing let key = PythonInstallationKey::from_str("cpython-3.12.0-linux-x86_64-gnu").unwrap(); assert_eq!( key.implementation, LenientImplementationName::Known(ImplementationName::CPython) ); assert_eq!(key.major, 3); assert_eq!(key.minor, 12); assert_eq!(key.patch, 0); assert_eq!( key.platform.os, Os::new(target_lexicon::OperatingSystem::Linux) ); assert_eq!( key.platform.arch, Arch::new(target_lexicon::Architecture::X86_64, None) ); assert_eq!( key.platform.libc, Libc::Some(target_lexicon::Environment::Gnu) ); // Test with architecture variant let key = PythonInstallationKey::from_str("cpython-3.11.2-linux-x86_64_v3-musl").unwrap(); assert_eq!( key.implementation, LenientImplementationName::Known(ImplementationName::CPython) ); assert_eq!(key.major, 3); assert_eq!(key.minor, 11); assert_eq!(key.patch, 2); assert_eq!( key.platform.os, Os::new(target_lexicon::OperatingSystem::Linux) ); assert_eq!( key.platform.arch, Arch::new(target_lexicon::Architecture::X86_64, Some(ArchVariant::V3)) ); assert_eq!( key.platform.libc, Libc::Some(target_lexicon::Environment::Musl) ); // Test with Python variant (freethreaded) let key = PythonInstallationKey::from_str("cpython-3.13.0+freethreaded-macos-aarch64-none") .unwrap(); assert_eq!( key.implementation, LenientImplementationName::Known(ImplementationName::CPython) ); assert_eq!(key.major, 3); assert_eq!(key.minor, 13); assert_eq!(key.patch, 0); assert_eq!(key.variant, PythonVariant::Freethreaded); assert_eq!( key.platform.os, Os::new(target_lexicon::OperatingSystem::Darwin(None)) ); assert_eq!( key.platform.arch, Arch::new( target_lexicon::Architecture::Aarch64(target_lexicon::Aarch64Architecture::Aarch64), None ) ); assert_eq!(key.platform.libc, Libc::None); // Test error cases assert!(PythonInstallationKey::from_str("cpython-3.12.0-linux-x86_64").is_err()); assert!(PythonInstallationKey::from_str("cpython-3.12.0").is_err()); assert!(PythonInstallationKey::from_str("cpython").is_err()); } #[test] fn test_python_installation_key_display() { let key = PythonInstallationKey { implementation: LenientImplementationName::from("cpython"), major: 3, minor: 12, patch: 0, prerelease: None, platform: Platform::from_str("linux-x86_64-gnu").unwrap(), variant: PythonVariant::Default, }; assert_eq!(key.to_string(), "cpython-3.12.0-linux-x86_64-gnu"); let key_with_variant = PythonInstallationKey { implementation: LenientImplementationName::from("cpython"), major: 3, minor: 13, patch: 0, prerelease: None, platform: Platform::from_str("macos-aarch64-none").unwrap(), variant: PythonVariant::Freethreaded, }; assert_eq!( key_with_variant.to_string(), "cpython-3.13.0+freethreaded-macos-aarch64-none" ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/target.rs
crates/uv-python/src/target.rs
use std::path::{Path, PathBuf}; use uv_pypi_types::Scheme; /// A `--target` directory into which packages can be installed, separate from a virtual environment /// or system Python interpreter. #[derive(Debug, Clone)] pub struct Target(PathBuf); impl Target { /// Return the [`Scheme`] for the `--target` directory. pub fn scheme(&self) -> Scheme { Scheme { purelib: self.0.clone(), platlib: self.0.clone(), scripts: self.0.join("bin"), data: self.0.clone(), include: self.0.join("include"), } } /// Return an iterator over the `site-packages` directories inside the environment. pub fn site_packages(&self) -> impl Iterator<Item = &Path> { std::iter::once(self.0.as_path()) } /// Initialize the `--target` directory. pub fn init(&self) -> std::io::Result<()> { fs_err::create_dir_all(&self.0)?; Ok(()) } /// Return the path to the `--target` directory. pub fn root(&self) -> &Path { &self.0 } } impl From<PathBuf> for Target { fn from(path: PathBuf) -> Self { Self(path) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/version_files.rs
crates/uv-python/src/version_files.rs
use std::ops::Add; use std::path::{Path, PathBuf}; use fs_err as fs; use itertools::Itertools; use tracing::debug; use uv_dirs::user_uv_config_dir; use uv_fs::Simplified; use uv_warnings::warn_user_once; use crate::PythonRequest; /// The file name for Python version pins. pub static PYTHON_VERSION_FILENAME: &str = ".python-version"; /// The file name for multiple Python version declarations. pub static PYTHON_VERSIONS_FILENAME: &str = ".python-versions"; /// A `.python-version` or `.python-versions` file. #[derive(Debug, Clone)] pub struct PythonVersionFile { /// The path to the version file. path: PathBuf, /// The Python version requests declared in the file. versions: Vec<PythonRequest>, } /// Whether to prefer the `.python-version` or `.python-versions` file. #[derive(Debug, Clone, Copy, Default)] pub enum FilePreference { #[default] Version, Versions, } #[derive(Debug, Default, Clone)] pub struct DiscoveryOptions<'a> { /// The path to stop discovery at. stop_discovery_at: Option<&'a Path>, /// Ignore Python version files. /// /// Discovery will still run in order to display a log about the ignored file. no_config: bool, /// Whether `.python-version` or `.python-versions` should be preferred. preference: FilePreference, /// Whether to ignore local version files, and only search for a global one. no_local: bool, } impl<'a> DiscoveryOptions<'a> { #[must_use] pub fn with_no_config(self, no_config: bool) -> Self { Self { no_config, ..self } } #[must_use] pub fn with_preference(self, preference: FilePreference) -> Self { Self { preference, ..self } } #[must_use] pub fn with_stop_discovery_at(self, stop_discovery_at: Option<&'a Path>) -> Self { Self { stop_discovery_at, ..self } } #[must_use] pub fn with_no_local(self, no_local: bool) -> Self { Self { no_local, ..self } } } impl PythonVersionFile { /// Find a Python version file in the given directory or any of its parents. pub async fn discover( working_directory: impl AsRef<Path>, options: &DiscoveryOptions<'_>, ) -> Result<Option<Self>, std::io::Error> { let allow_local = !options.no_local; let Some(path) = allow_local.then(|| { // First, try to find a local version file. let local = Self::find_nearest(&working_directory, options); if local.is_none() { // Log where we searched for the file, if not found if let Some(stop_discovery_at) = options.stop_discovery_at { if stop_discovery_at == working_directory.as_ref() { debug!( "No Python version file found in workspace: {}", working_directory.as_ref().display() ); } else { debug!( "No Python version file found between working directory `{}` and workspace root `{}`", working_directory.as_ref().display(), stop_discovery_at.display() ); } } else { debug!( "No Python version file found in ancestors of working directory: {}", working_directory.as_ref().display() ); } } local }).flatten().or_else(|| { // Search for a global config Self::find_global(options) }) else { return Ok(None); }; if options.no_config { debug!( "Ignoring Python version file at `{}` due to `--no-config`", path.user_display() ); return Ok(None); } // Uses `try_from_path` instead of `from_path` to avoid TOCTOU failures. Self::try_from_path(path).await } fn find_global(options: &DiscoveryOptions<'_>) -> Option<PathBuf> { let user_config_dir = user_uv_config_dir()?; Self::find_in_directory(&user_config_dir, options) } fn find_nearest(path: impl AsRef<Path>, options: &DiscoveryOptions<'_>) -> Option<PathBuf> { path.as_ref() .ancestors() .take_while(|path| { // Only walk up the given directory, if any. options .stop_discovery_at .and_then(Path::parent) .map(|stop_discovery_at| stop_discovery_at != *path) .unwrap_or(true) }) .find_map(|path| Self::find_in_directory(path, options)) } fn find_in_directory(path: &Path, options: &DiscoveryOptions<'_>) -> Option<PathBuf> { let version_path = path.join(PYTHON_VERSION_FILENAME); let versions_path = path.join(PYTHON_VERSIONS_FILENAME); let paths = match options.preference { FilePreference::Versions => [versions_path, version_path], FilePreference::Version => [version_path, versions_path], }; paths.into_iter().find(|path| path.is_file()) } /// Try to read a Python version file at the given path. /// /// If the file does not exist, `Ok(None)` is returned. pub async fn try_from_path(path: PathBuf) -> Result<Option<Self>, std::io::Error> { match fs::tokio::read_to_string(&path).await { Ok(content) => { debug!( "Reading Python requests from version file at `{}`", path.display() ); let versions = content .lines() .filter(|line| { // Skip comments and empty lines. let trimmed = line.trim(); !(trimmed.is_empty() || trimmed.starts_with('#')) }) .map(ToString::to_string) .map(|version| PythonRequest::parse(&version)) .filter(|request| { if let PythonRequest::ExecutableName(name) = request { warn_user_once!( "Ignoring unsupported Python request `{name}` in version file: {}", path.display() ); false } else { true } }) .collect(); Ok(Some(Self { path, versions })) } Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(err) => Err(err), } } /// Read a Python version file at the given path. /// /// If the file does not exist, an error is returned. pub async fn from_path(path: PathBuf) -> Result<Self, std::io::Error> { let Some(result) = Self::try_from_path(path).await? else { return Err(std::io::Error::new( std::io::ErrorKind::NotFound, "Version file not found".to_string(), )); }; Ok(result) } /// Create a new representation of a version file at the given path. /// /// The file will not any include versions; see [`PythonVersionFile::with_versions`]. /// The file will not be created; see [`PythonVersionFile::write`]. pub fn new(path: PathBuf) -> Self { Self { path, versions: vec![], } } /// Create a new representation of a global Python version file. /// /// Returns [`None`] if the user configuration directory cannot be determined. pub fn global() -> Option<Self> { let path = user_uv_config_dir()?.join(PYTHON_VERSION_FILENAME); Some(Self::new(path)) } /// Returns `true` if the version file is a global version file. pub fn is_global(&self) -> bool { Self::global().is_some_and(|global| self.path() == global.path()) } /// Return the first request declared in the file, if any. pub fn version(&self) -> Option<&PythonRequest> { self.versions.first() } /// Iterate of all versions declared in the file. pub fn versions(&self) -> impl Iterator<Item = &PythonRequest> { self.versions.iter() } /// Cast to a list of all versions declared in the file. pub fn into_versions(self) -> Vec<PythonRequest> { self.versions } /// Cast to the first version declared in the file, if any. pub fn into_version(self) -> Option<PythonRequest> { self.versions.into_iter().next() } /// Return the path to the version file. pub fn path(&self) -> &Path { &self.path } /// Return the file name of the version file (guaranteed to be one of `.python-version` or /// `.python-versions`). pub fn file_name(&self) -> &str { self.path.file_name().unwrap().to_str().unwrap() } /// Set the versions for the file. #[must_use] pub fn with_versions(self, versions: Vec<PythonRequest>) -> Self { Self { path: self.path, versions, } } /// Update the version file on the file system. pub async fn write(&self) -> Result<(), std::io::Error> { debug!("Writing Python versions to `{}`", self.path.display()); if let Some(parent) = self.path.parent() { fs_err::tokio::create_dir_all(parent).await?; } fs::tokio::write( &self.path, self.versions .iter() .map(PythonRequest::to_canonical_string) .join("\n") .add("\n") .as_bytes(), ) .await } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/windows_registry.rs
crates/uv-python/src/windows_registry.rs
//! PEP 514 interactions with the Windows registry. use crate::managed::ManagedPythonInstallation; use crate::{COMPANY_DISPLAY_NAME, COMPANY_KEY, PythonInstallationKey, PythonVersion}; use anyhow::anyhow; use std::cmp::Ordering; use std::collections::HashSet; use std::path::PathBuf; use std::str::FromStr; use target_lexicon::PointerWidth; use thiserror::Error; use tracing::debug; use uv_platform::Arch; use uv_warnings::{warn_user, warn_user_once}; use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_KEY_DELETED}; use windows::Win32::System::Registry::{KEY_WOW64_32KEY, KEY_WOW64_64KEY}; use windows::core::HRESULT; use windows_registry::{CURRENT_USER, HSTRING, Key, LOCAL_MACHINE, Value}; /// A Python interpreter found in the Windows registry through PEP 514 or from a known Microsoft /// Store path. /// /// There are a lot more (optional) fields defined in PEP 514, but we only care about path and /// version here, for everything else we probe with a Python script. #[derive(Debug, Clone)] pub(crate) struct WindowsPython { pub(crate) path: PathBuf, pub(crate) version: Option<PythonVersion>, } /// Find all Pythons registered in the Windows registry following PEP 514. pub(crate) fn registry_pythons() -> Result<Vec<WindowsPython>, windows::core::Error> { let mut registry_pythons = Vec::new(); // Prefer `HKEY_CURRENT_USER` over `HKEY_LOCAL_MACHINE`. // By default, a 64-bit program does not see a 32-bit global (HKLM) installation of Python in // the registry (https://github.com/astral-sh/uv/issues/11217). To work around this, we manually // request both 32-bit and 64-bit access. The flags have no effect on 32-bit // (https://stackoverflow.com/a/12796797/3549270). for (root_key, access_modifier) in [ (CURRENT_USER, None), (LOCAL_MACHINE, Some(KEY_WOW64_64KEY)), (LOCAL_MACHINE, Some(KEY_WOW64_32KEY)), ] { let mut open_options = root_key.options(); open_options.read(); if let Some(access_modifier) = access_modifier { open_options.access(access_modifier.0); } let Ok(key_python) = open_options.open(r"Software\Python") else { continue; }; for company in key_python.keys()? { // Reserved name according to the PEP. if company == "PyLauncher" { continue; } let Ok(company_key) = key_python.open(&company) else { // Ignore invalid entries continue; }; for tag in company_key.keys()? { let tag_key = company_key.open(&tag)?; if let Some(registry_python) = read_registry_entry(&company, &tag, &tag_key) { registry_pythons.push(registry_python); } } } } // The registry has no natural ordering, so we're processing the latest version first. registry_pythons.sort_by(|a, b| { match (&a.version, &b.version) { // Place entries with a version before those without a version. (Some(_), None) => Ordering::Greater, (None, Some(_)) => Ordering::Less, // We want the highest version on top, which is the inverse from the regular order. The // path is an arbitrary but stable tie-breaker. (Some(version_a), Some(version_b)) => { version_a.cmp(version_b).reverse().then(a.path.cmp(&b.path)) } // Sort the entries without a version arbitrarily, but stable (by path). (None, None) => a.path.cmp(&b.path), } }); Ok(registry_pythons) } fn read_registry_entry(company: &str, tag: &str, tag_key: &Key) -> Option<WindowsPython> { // `ExecutablePath` is mandatory for executable Pythons. let Ok(executable_path) = tag_key .open("InstallPath") .and_then(|install_path| install_path.get_value("ExecutablePath")) .and_then(String::try_from) else { debug!( r"Python interpreter in the registry is not executable: `Software\Python\{}\{}", company, tag ); return None; }; // `SysVersion` is optional. let version = tag_key .get_value("SysVersion") .and_then(String::try_from) .ok() .and_then(|s| match PythonVersion::from_str(&s) { Ok(version) => Some(version), Err(err) => { debug!( "Skipping Python interpreter ({executable_path}) \ with invalid registry version {s}: {err}", ); None } }); Some(WindowsPython { path: PathBuf::from(executable_path), version, }) } #[derive(Debug, Error)] pub enum ManagedPep514Error { #[error("Windows has an unknown pointer width for arch: `{_0}`")] InvalidPointerSize(Arch), #[error("Failed to write registry entry: {0}")] WriteError(#[from] windows::core::Error), } /// Register a managed Python installation in the Windows registry following PEP 514. pub fn create_registry_entry( installation: &ManagedPythonInstallation, ) -> Result<(), ManagedPep514Error> { let pointer_width = match installation.key().arch().family().pointer_width() { Ok(PointerWidth::U32) => 32, Ok(PointerWidth::U64) => 64, _ => { return Err(ManagedPep514Error::InvalidPointerSize( *installation.key().arch(), )); } }; write_registry_entry(installation, pointer_width)?; Ok(()) } fn write_registry_entry( installation: &ManagedPythonInstallation, pointer_width: i32, ) -> windows_registry::Result<()> { // We currently just overwrite all known keys, without removing prior entries first // Similar to using the bin directory in HOME on Unix, we only install for the current user // on Windows. let company = CURRENT_USER.create(format!("Software\\Python\\{COMPANY_KEY}"))?; company.set_string("DisplayName", COMPANY_DISPLAY_NAME)?; company.set_string("SupportUrl", "https://github.com/astral-sh/uv")?; // Ex) CPython3.13.1 let tag = company.create(registry_python_tag(installation.key()))?; let display_name = format!( "{} {} ({}-bit)", installation.key().implementation().pretty(), installation.key().version(), pointer_width ); tag.set_string("DisplayName", &display_name)?; tag.set_string("SupportUrl", "https://github.com/astral-sh/uv")?; tag.set_string("Version", installation.key().version().to_string())?; tag.set_string("SysVersion", installation.key().sys_version())?; tag.set_string("SysArchitecture", format!("{pointer_width}bit"))?; // Store `python-build-standalone` release if let Some(url) = installation.url() { tag.set_string("DownloadUrl", url)?; } if let Some(sha256) = installation.sha256() { tag.set_string("DownloadSha256", sha256)?; } let install_path = tag.create("InstallPath")?; install_path.set_value( "", &Value::from(&HSTRING::from(installation.path().as_os_str())), )?; install_path.set_value( "ExecutablePath", &Value::from(&HSTRING::from(installation.executable(false).as_os_str())), )?; install_path.set_value( "WindowedExecutablePath", &Value::from(&HSTRING::from(installation.executable(true).as_os_str())), )?; Ok(()) } fn registry_python_tag(key: &PythonInstallationKey) -> String { format!("{}{}", key.implementation().pretty(), key.version()) } /// Remove requested Python entries from the Windows Registry (PEP 514). pub fn remove_registry_entry<'a>( installations: impl IntoIterator<Item = &'a ManagedPythonInstallation>, all: bool, errors: &mut Vec<(PythonInstallationKey, anyhow::Error)>, ) { let astral_key = format!("Software\\Python\\{COMPANY_KEY}"); if all { debug!("Removing registry key HKCU:\\{}", astral_key); if let Err(err) = CURRENT_USER.remove_tree(&astral_key) { if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) || err.code() == HRESULT::from(ERROR_KEY_DELETED) { debug!("No registry entries to remove, no registry key {astral_key}"); } else { warn_user!("Failed to clear registry entries under {astral_key}: {err}"); } } return; } for installation in installations { let python_tag = registry_python_tag(installation.key()); let python_entry = format!("{astral_key}\\{python_tag}"); debug!("Removing registry key HKCU:\\{}", python_entry); if let Err(err) = CURRENT_USER.remove_tree(&python_entry) { if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) || err.code() == HRESULT::from(ERROR_KEY_DELETED) { debug!( "No registry entries to remove for {}, no registry key {}", installation.key(), python_entry ); } else { errors.push(( installation.key().clone(), anyhow!("Failed to clear registry entries under HKCU:\\{python_entry}: {err}"), )); } } } } /// Remove Python entries from the Windows Registry (PEP 514) that are not matching any /// installation. pub fn remove_orphan_registry_entries(installations: &[ManagedPythonInstallation]) { let keep: HashSet<_> = installations .iter() .map(|installation| registry_python_tag(installation.key())) .collect(); let astral_key = format!("Software\\Python\\{COMPANY_KEY}"); let key = match CURRENT_USER.open(&astral_key) { Ok(subkeys) => subkeys, Err(err) if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) || err.code() == HRESULT::from(ERROR_KEY_DELETED) => { return; } Err(err) => { // TODO(konsti): We don't have an installation key here. warn_user_once!("Failed to open HKCU:\\{astral_key}: {err}"); return; } }; // Separate assignment since `keys()` creates a borrow. let subkeys = match key.keys() { Ok(subkeys) => subkeys, Err(err) if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) || err.code() == HRESULT::from(ERROR_KEY_DELETED) => { return; } Err(err) => { // TODO(konsti): We don't have an installation key here. warn_user_once!("Failed to list subkeys of HKCU:\\{astral_key}: {err}"); return; } }; for subkey in subkeys { if keep.contains(&subkey) { continue; } let python_entry = format!("{astral_key}\\{subkey}"); debug!("Removing orphan registry key HKCU:\\{}", python_entry); if let Err(err) = CURRENT_USER.remove_tree(&python_entry) { if err.code() == HRESULT::from(ERROR_FILE_NOT_FOUND) || err.code() == HRESULT::from(ERROR_KEY_DELETED) { continue; } // TODO(konsti): We don't have an installation key here. warn_user_once!("Failed to remove orphan registry key HKCU:\\{python_entry}: {err}"); } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/interpreter.rs
crates/uv-python/src/interpreter.rs
use std::borrow::Cow; use std::env::consts::ARCH; use std::fmt::{Display, Formatter}; use std::path::{Path, PathBuf}; use std::process::{Command, ExitStatus}; use std::str::FromStr; use std::sync::OnceLock; use std::{env, io}; use configparser::ini::Ini; use fs_err as fs; use owo_colors::OwoColorize; use same_file::is_same_file; use serde::{Deserialize, Serialize}; use thiserror::Error; use tracing::{debug, trace, warn}; use uv_cache::{Cache, CacheBucket, CachedByTimestamp, Freshness}; use uv_cache_info::Timestamp; use uv_cache_key::cache_digest; use uv_fs::{ LockedFile, LockedFileError, LockedFileMode, PythonExt, Simplified, write_atomic_sync, }; use uv_install_wheel::Layout; use uv_pep440::Version; use uv_pep508::{MarkerEnvironment, StringVersion}; use uv_platform::{Arch, Libc, Os}; use uv_platform_tags::{Platform, Tags, TagsError}; use uv_pypi_types::{ResolverMarkerEnvironment, Scheme}; use crate::implementation::LenientImplementationName; use crate::managed::ManagedPythonInstallations; use crate::pointer_size::PointerSize; use crate::{ Prefix, PythonInstallationKey, PythonVariant, PythonVersion, Target, VersionRequest, VirtualEnvironment, }; #[cfg(windows)] use windows::Win32::Foundation::{APPMODEL_ERROR_NO_PACKAGE, ERROR_CANT_ACCESS_FILE, WIN32_ERROR}; /// A Python executable and its associated platform markers. #[allow(clippy::struct_excessive_bools)] #[derive(Debug, Clone)] pub struct Interpreter { platform: Platform, markers: Box<MarkerEnvironment>, scheme: Scheme, virtualenv: Scheme, manylinux_compatible: bool, sys_prefix: PathBuf, sys_base_exec_prefix: PathBuf, sys_base_prefix: PathBuf, sys_base_executable: Option<PathBuf>, sys_executable: PathBuf, sys_path: Vec<PathBuf>, site_packages: Vec<PathBuf>, stdlib: PathBuf, standalone: bool, tags: OnceLock<Tags>, target: Option<Target>, prefix: Option<Prefix>, pointer_size: PointerSize, gil_disabled: bool, real_executable: PathBuf, debug_enabled: bool, } impl Interpreter { /// Detect the interpreter info for the given Python executable. pub fn query(executable: impl AsRef<Path>, cache: &Cache) -> Result<Self, Error> { let info = InterpreterInfo::query_cached(executable.as_ref(), cache)?; debug_assert!( info.sys_executable.is_absolute(), "`sys.executable` is not an absolute Python; Python installation is broken: {}", info.sys_executable.display() ); Ok(Self { platform: info.platform, markers: Box::new(info.markers), scheme: info.scheme, virtualenv: info.virtualenv, manylinux_compatible: info.manylinux_compatible, sys_prefix: info.sys_prefix, sys_base_exec_prefix: info.sys_base_exec_prefix, pointer_size: info.pointer_size, gil_disabled: info.gil_disabled, debug_enabled: info.debug_enabled, sys_base_prefix: info.sys_base_prefix, sys_base_executable: info.sys_base_executable, sys_executable: info.sys_executable, sys_path: info.sys_path, site_packages: info.site_packages, stdlib: info.stdlib, standalone: info.standalone, tags: OnceLock::new(), target: None, prefix: None, real_executable: executable.as_ref().to_path_buf(), }) } /// Return a new [`Interpreter`] with the given virtual environment root. #[must_use] pub fn with_virtualenv(self, virtualenv: VirtualEnvironment) -> Self { Self { scheme: virtualenv.scheme, sys_base_executable: Some(virtualenv.base_executable), sys_executable: virtualenv.executable, sys_prefix: virtualenv.root, target: None, prefix: None, site_packages: vec![], ..self } } /// Return a new [`Interpreter`] to install into the given `--target` directory. pub fn with_target(self, target: Target) -> io::Result<Self> { target.init()?; Ok(Self { target: Some(target), ..self }) } /// Return a new [`Interpreter`] to install into the given `--prefix` directory. pub fn with_prefix(self, prefix: Prefix) -> io::Result<Self> { prefix.init(self.virtualenv())?; Ok(Self { prefix: Some(prefix), ..self }) } /// Return the base Python executable; that is, the Python executable that should be /// considered the "base" for the virtual environment. This is typically the Python executable /// from the [`Interpreter`]; however, if the interpreter is a virtual environment itself, then /// the base Python executable is the Python executable of the interpreter's base interpreter. /// /// This routine relies on `sys._base_executable`, falling back to `sys.executable` if unset. /// Broadly, this routine should be used when attempting to determine the "base Python /// executable" in a way that is consistent with the CPython standard library, such as when /// determining the `home` key for a virtual environment. pub fn to_base_python(&self) -> Result<PathBuf, io::Error> { let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable()); let base_python = std::path::absolute(base_executable)?; Ok(base_python) } /// Determine the base Python executable; that is, the Python executable that should be /// considered the "base" for the virtual environment. This is typically the Python executable /// from the [`Interpreter`]; however, if the interpreter is a virtual environment itself, then /// the base Python executable is the Python executable of the interpreter's base interpreter. /// /// This routine mimics the CPython `getpath.py` logic in order to make a more robust assessment /// of the appropriate base Python executable. Broadly, this routine should be used when /// attempting to determine the "true" base executable for a Python interpreter by resolving /// symlinks until a valid Python installation is found. In particular, we tend to use this /// routine for our own managed (or standalone) Python installations. pub fn find_base_python(&self) -> Result<PathBuf, io::Error> { let base_executable = self.sys_base_executable().unwrap_or(self.sys_executable()); // In `python-build-standalone`, a symlinked interpreter will return its own executable path // as `sys._base_executable`. Using the symlinked path as the base Python executable can be // incorrect, since it could cause `home` to point to something that is _not_ a Python // installation. Specifically, if the interpreter _itself_ is symlinked to an arbitrary // location, we need to fully resolve it to the actual Python executable; however, if the // entire standalone interpreter is symlinked, then we can use the symlinked path. // // We emulate CPython's `getpath.py` to ensure that the base executable results in a valid // Python prefix when converted into the `home` key for `pyvenv.cfg`. let base_python = match find_base_python( base_executable, self.python_major(), self.python_minor(), self.variant().executable_suffix(), ) { Ok(path) => path, Err(err) => { warn!("Failed to find base Python executable: {err}"); canonicalize_executable(base_executable)? } }; Ok(base_python) } /// Returns the path to the Python virtual environment. #[inline] pub fn platform(&self) -> &Platform { &self.platform } /// Returns the [`MarkerEnvironment`] for this Python executable. #[inline] pub const fn markers(&self) -> &MarkerEnvironment { &self.markers } /// Return the [`ResolverMarkerEnvironment`] for this Python executable. pub fn resolver_marker_environment(&self) -> ResolverMarkerEnvironment { ResolverMarkerEnvironment::from(self.markers().clone()) } /// Returns the [`PythonInstallationKey`] for this interpreter. pub fn key(&self) -> PythonInstallationKey { PythonInstallationKey::new( LenientImplementationName::from(self.implementation_name()), self.python_major(), self.python_minor(), self.python_patch(), self.python_version().pre(), uv_platform::Platform::new(self.os(), self.arch(), self.libc()), self.variant(), ) } pub fn variant(&self) -> PythonVariant { if self.gil_disabled() { if self.debug_enabled() { PythonVariant::FreethreadedDebug } else { PythonVariant::Freethreaded } } else if self.debug_enabled() { PythonVariant::Debug } else { PythonVariant::default() } } /// Return the [`Arch`] reported by the interpreter platform tags. pub fn arch(&self) -> Arch { Arch::from(&self.platform().arch()) } /// Return the [`Libc`] reported by the interpreter platform tags. pub fn libc(&self) -> Libc { Libc::from(self.platform().os()) } /// Return the [`Os`] reported by the interpreter platform tags. pub fn os(&self) -> Os { Os::from(self.platform().os()) } /// Returns the [`Tags`] for this Python executable. pub fn tags(&self) -> Result<&Tags, TagsError> { if self.tags.get().is_none() { let tags = Tags::from_env( self.platform(), self.python_tuple(), self.implementation_name(), self.implementation_tuple(), self.manylinux_compatible, self.gil_disabled, false, )?; self.tags.set(tags).expect("tags should not be set"); } Ok(self.tags.get().expect("tags should be set")) } /// Returns `true` if the environment is a PEP 405-compliant virtual environment. /// /// See: <https://github.com/pypa/pip/blob/0ad4c94be74cc24874c6feb5bb3c2152c398a18e/src/pip/_internal/utils/virtualenv.py#L14> pub fn is_virtualenv(&self) -> bool { // Maybe this should return `false` if it's a target? self.sys_prefix != self.sys_base_prefix } /// Returns `true` if the environment is a `--target` environment. pub fn is_target(&self) -> bool { self.target.is_some() } /// Returns `true` if the environment is a `--prefix` environment. pub fn is_prefix(&self) -> bool { self.prefix.is_some() } /// Returns `true` if this interpreter is managed by uv. /// /// Returns `false` if we cannot determine the path of the uv managed Python interpreters. pub fn is_managed(&self) -> bool { if let Ok(test_managed) = std::env::var(uv_static::EnvVars::UV_INTERNAL__TEST_PYTHON_MANAGED) { // During testing, we collect interpreters into an artificial search path and need to // be able to mock whether an interpreter is managed or not. return test_managed.split_ascii_whitespace().any(|item| { let version = <PythonVersion as std::str::FromStr>::from_str(item).expect( "`UV_INTERNAL__TEST_PYTHON_MANAGED` items should be valid Python versions", ); if version.patch().is_some() { version.version() == self.python_version() } else { (version.major(), version.minor()) == self.python_tuple() } }); } let Ok(installations) = ManagedPythonInstallations::from_settings(None) else { return false; }; let Ok(suffix) = self.sys_base_prefix.strip_prefix(installations.root()) else { return false; }; let Some(first_component) = suffix.components().next() else { return false; }; let Some(name) = first_component.as_os_str().to_str() else { return false; }; PythonInstallationKey::from_str(name).is_ok() } /// Returns `Some` if the environment is externally managed, optionally including an error /// message from the `EXTERNALLY-MANAGED` file. /// /// See: <https://packaging.python.org/en/latest/specifications/externally-managed-environments/> pub fn is_externally_managed(&self) -> Option<ExternallyManaged> { // Per the spec, a virtual environment is never externally managed. if self.is_virtualenv() { return None; } // If we're installing into a target or prefix directory, it's never externally managed. if self.is_target() || self.is_prefix() { return None; } let Ok(contents) = fs::read_to_string(self.stdlib.join("EXTERNALLY-MANAGED")) else { return None; }; let mut ini = Ini::new_cs(); ini.set_multiline(true); let Ok(mut sections) = ini.read(contents) else { // If a file exists but is not a valid INI file, we assume the environment is // externally managed. return Some(ExternallyManaged::default()); }; let Some(section) = sections.get_mut("externally-managed") else { // If the file exists but does not contain an "externally-managed" section, we assume // the environment is externally managed. return Some(ExternallyManaged::default()); }; let Some(error) = section.remove("Error") else { // If the file exists but does not contain an "Error" key, we assume the environment is // externally managed. return Some(ExternallyManaged::default()); }; Some(ExternallyManaged { error }) } /// Returns the `python_full_version` marker corresponding to this Python version. #[inline] pub fn python_full_version(&self) -> &StringVersion { self.markers.python_full_version() } /// Returns the full Python version. #[inline] pub fn python_version(&self) -> &Version { &self.markers.python_full_version().version } /// Returns the Python version up to the minor component. #[inline] pub fn python_minor_version(&self) -> Version { Version::new(self.python_version().release().iter().take(2).copied()) } /// Returns the Python version up to the patch component. #[inline] pub fn python_patch_version(&self) -> Version { Version::new(self.python_version().release().iter().take(3).copied()) } /// Return the major version component of this Python version. pub fn python_major(&self) -> u8 { let major = self.markers.python_full_version().version.release()[0]; u8::try_from(major).expect("invalid major version") } /// Return the minor version component of this Python version. pub fn python_minor(&self) -> u8 { let minor = self.markers.python_full_version().version.release()[1]; u8::try_from(minor).expect("invalid minor version") } /// Return the patch version component of this Python version. pub fn python_patch(&self) -> u8 { let minor = self.markers.python_full_version().version.release()[2]; u8::try_from(minor).expect("invalid patch version") } /// Returns the Python version as a simple tuple, e.g., `(3, 12)`. pub fn python_tuple(&self) -> (u8, u8) { (self.python_major(), self.python_minor()) } /// Return the major version of the implementation (e.g., `CPython` or `PyPy`). pub fn implementation_major(&self) -> u8 { let major = self.markers.implementation_version().version.release()[0]; u8::try_from(major).expect("invalid major version") } /// Return the minor version of the implementation (e.g., `CPython` or `PyPy`). pub fn implementation_minor(&self) -> u8 { let minor = self.markers.implementation_version().version.release()[1]; u8::try_from(minor).expect("invalid minor version") } /// Returns the implementation version as a simple tuple. pub fn implementation_tuple(&self) -> (u8, u8) { (self.implementation_major(), self.implementation_minor()) } /// Returns the implementation name (e.g., `CPython` or `PyPy`). pub fn implementation_name(&self) -> &str { self.markers.implementation_name() } /// Return the `sys.base_exec_prefix` path for this Python interpreter. pub fn sys_base_exec_prefix(&self) -> &Path { &self.sys_base_exec_prefix } /// Return the `sys.base_prefix` path for this Python interpreter. pub fn sys_base_prefix(&self) -> &Path { &self.sys_base_prefix } /// Return the `sys.prefix` path for this Python interpreter. pub fn sys_prefix(&self) -> &Path { &self.sys_prefix } /// Return the `sys._base_executable` path for this Python interpreter. Some platforms do not /// have this attribute, so it may be `None`. pub fn sys_base_executable(&self) -> Option<&Path> { self.sys_base_executable.as_deref() } /// Return the `sys.executable` path for this Python interpreter. pub fn sys_executable(&self) -> &Path { &self.sys_executable } /// Return the "real" queried executable path for this Python interpreter. pub fn real_executable(&self) -> &Path { &self.real_executable } /// Return the `sys.path` for this Python interpreter. pub fn sys_path(&self) -> &[PathBuf] { &self.sys_path } /// Return the `site.getsitepackages` for this Python interpreter. /// /// These are the paths Python will search for packages in at runtime. We use this for /// environment layering, but not for checking for installed packages. We could use these paths /// to check for installed packages, but it introduces a lot of complexity, so instead we use a /// simplified version that does not respect customized site-packages. See /// [`Interpreter::site_packages`]. pub fn runtime_site_packages(&self) -> &[PathBuf] { &self.site_packages } /// Return the `stdlib` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn stdlib(&self) -> &Path { &self.stdlib } /// Return the `purelib` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn purelib(&self) -> &Path { &self.scheme.purelib } /// Return the `platlib` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn platlib(&self) -> &Path { &self.scheme.platlib } /// Return the `scripts` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn scripts(&self) -> &Path { &self.scheme.scripts } /// Return the `data` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn data(&self) -> &Path { &self.scheme.data } /// Return the `include` path for this Python interpreter, as returned by `sysconfig.get_paths()`. pub fn include(&self) -> &Path { &self.scheme.include } /// Return the [`Scheme`] for a virtual environment created by this [`Interpreter`]. pub fn virtualenv(&self) -> &Scheme { &self.virtualenv } /// Return whether this interpreter is `manylinux` compatible. pub fn manylinux_compatible(&self) -> bool { self.manylinux_compatible } /// Return the [`PointerSize`] of the Python interpreter (i.e., 32- vs. 64-bit). pub fn pointer_size(&self) -> PointerSize { self.pointer_size } /// Return whether this is a Python 3.13+ freethreading Python, as specified by the sysconfig var /// `Py_GIL_DISABLED`. /// /// freethreading Python is incompatible with earlier native modules, re-introducing /// abiflags with a `t` flag. <https://peps.python.org/pep-0703/#build-configuration-changes> pub fn gil_disabled(&self) -> bool { self.gil_disabled } /// Return whether this is a debug build of Python, as specified by the sysconfig var /// `Py_DEBUG`. pub fn debug_enabled(&self) -> bool { self.debug_enabled } /// Return the `--target` directory for this interpreter, if any. pub fn target(&self) -> Option<&Target> { self.target.as_ref() } /// Return the `--prefix` directory for this interpreter, if any. pub fn prefix(&self) -> Option<&Prefix> { self.prefix.as_ref() } /// Returns `true` if an [`Interpreter`] may be a `python-build-standalone` interpreter. /// /// This method may return false positives, but it should not return false negatives. In other /// words, if this method returns `true`, the interpreter _may_ be from /// `python-build-standalone`; if it returns `false`, the interpreter is definitely _not_ from /// `python-build-standalone`. /// /// See: <https://github.com/astral-sh/python-build-standalone/issues/382> #[cfg(unix)] pub fn is_standalone(&self) -> bool { self.standalone } /// Returns `true` if an [`Interpreter`] may be a `python-build-standalone` interpreter. // TODO(john): Replace this approach with patching sysconfig on Windows to // set `PYTHON_BUILD_STANDALONE=1`.` #[cfg(windows)] pub fn is_standalone(&self) -> bool { self.standalone || (self.is_managed() && self.markers().implementation_name() == "cpython") } /// Return the [`Layout`] environment used to install wheels into this interpreter. pub fn layout(&self) -> Layout { Layout { python_version: self.python_tuple(), sys_executable: self.sys_executable().to_path_buf(), os_name: self.markers.os_name().to_string(), scheme: if let Some(target) = self.target.as_ref() { target.scheme() } else if let Some(prefix) = self.prefix.as_ref() { prefix.scheme(&self.virtualenv) } else { Scheme { purelib: self.purelib().to_path_buf(), platlib: self.platlib().to_path_buf(), scripts: self.scripts().to_path_buf(), data: self.data().to_path_buf(), include: if self.is_virtualenv() { // If the interpreter is a venv, then the `include` directory has a different structure. // See: https://github.com/pypa/pip/blob/0ad4c94be74cc24874c6feb5bb3c2152c398a18e/src/pip/_internal/locations/_sysconfig.py#L172 self.sys_prefix.join("include").join("site").join(format!( "python{}.{}", self.python_major(), self.python_minor() )) } else { self.include().to_path_buf() }, } }, } } /// Returns an iterator over the `site-packages` directories inside the environment. /// /// In most cases, `purelib` and `platlib` will be the same, and so the iterator will contain /// a single element; however, in some distributions, they may be different. /// /// Some distributions also create symbolic links from `purelib` to `platlib`; in such cases, we /// still deduplicate the entries, returning a single path. /// /// Note this does not include all runtime site-packages directories if the interpreter has been /// customized. See [`Interpreter::runtime_site_packages`]. pub fn site_packages(&self) -> impl Iterator<Item = Cow<'_, Path>> { let target = self.target().map(Target::site_packages); let prefix = self .prefix() .map(|prefix| prefix.site_packages(self.virtualenv())); let interpreter = if target.is_none() && prefix.is_none() { let purelib = self.purelib(); let platlib = self.platlib(); Some(std::iter::once(purelib).chain( if purelib == platlib || is_same_file(purelib, platlib).unwrap_or(false) { None } else { Some(platlib) }, )) } else { None }; target .into_iter() .flatten() .map(Cow::Borrowed) .chain(prefix.into_iter().flatten().map(Cow::Owned)) .chain(interpreter.into_iter().flatten().map(Cow::Borrowed)) } /// Check if the interpreter matches the given Python version. /// /// If a patch version is present, we will require an exact match. /// Otherwise, just the major and minor version numbers need to match. pub fn satisfies(&self, version: &PythonVersion) -> bool { if version.patch().is_some() { version.version() == self.python_version() } else { (version.major(), version.minor()) == self.python_tuple() } } /// Whether or not this Python interpreter is from a default Python executable name, like /// `python`, `python3`, or `python.exe`. pub(crate) fn has_default_executable_name(&self) -> bool { let Some(file_name) = self.sys_executable().file_name() else { return false; }; let Some(name) = file_name.to_str() else { return false; }; VersionRequest::Default .executable_names(None) .into_iter() .any(|default_name| name == default_name.to_string()) } /// Grab a file lock for the environment to prevent concurrent writes across processes. pub async fn lock(&self) -> Result<LockedFile, LockedFileError> { if let Some(target) = self.target() { // If we're installing into a `--target`, use a target-specific lockfile. LockedFile::acquire( target.root().join(".lock"), LockedFileMode::Exclusive, target.root().user_display(), ) .await } else if let Some(prefix) = self.prefix() { // Likewise, if we're installing into a `--prefix`, use a prefix-specific lockfile. LockedFile::acquire( prefix.root().join(".lock"), LockedFileMode::Exclusive, prefix.root().user_display(), ) .await } else if self.is_virtualenv() { // If the environment a virtualenv, use a virtualenv-specific lockfile. LockedFile::acquire( self.sys_prefix.join(".lock"), LockedFileMode::Exclusive, self.sys_prefix.user_display(), ) .await } else { // Otherwise, use a global lockfile. LockedFile::acquire( env::temp_dir().join(format!("uv-{}.lock", cache_digest(&self.sys_executable))), LockedFileMode::Exclusive, self.sys_prefix.user_display(), ) .await } } } /// Calls `fs_err::canonicalize` on Unix. On Windows, avoids attempting to resolve symlinks /// but will resolve junctions if they are part of a trampoline target. pub fn canonicalize_executable(path: impl AsRef<Path>) -> std::io::Result<PathBuf> { let path = path.as_ref(); debug_assert!( path.is_absolute(), "path must be absolute: {}", path.display() ); #[cfg(windows)] { if let Ok(Some(launcher)) = uv_trampoline_builder::Launcher::try_from_path(path) { Ok(dunce::canonicalize(launcher.python_path)?) } else { Ok(path.to_path_buf()) } } #[cfg(unix)] fs_err::canonicalize(path) } /// The `EXTERNALLY-MANAGED` file in a Python installation. /// /// See: <https://packaging.python.org/en/latest/specifications/externally-managed-environments/> #[derive(Debug, Default, Clone)] pub struct ExternallyManaged { error: Option<String>, } impl ExternallyManaged { /// Return the `EXTERNALLY-MANAGED` error message, if any. pub fn into_error(self) -> Option<String> { self.error } } #[derive(Debug, Error)] pub struct UnexpectedResponseError { #[source] pub(super) err: serde_json::Error, pub(super) stdout: String, pub(super) stderr: String, pub(super) path: PathBuf, } impl Display for UnexpectedResponseError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Querying Python at `{}` returned an invalid response: {}", self.path.display(), self.err )?; let mut non_empty = false; if !self.stdout.trim().is_empty() { write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?; non_empty = true; } if !self.stderr.trim().is_empty() { write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?; non_empty = true; } if non_empty { writeln!(f)?; } Ok(()) } } #[derive(Debug, Error)] pub struct StatusCodeError { pub(super) code: ExitStatus, pub(super) stdout: String, pub(super) stderr: String, pub(super) path: PathBuf, } impl Display for StatusCodeError { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Querying Python at `{}` failed with exit status {}", self.path.display(), self.code )?; let mut non_empty = false; if !self.stdout.trim().is_empty() { write!(f, "\n\n{}\n{}", "[stdout]".red(), self.stdout)?; non_empty = true; } if !self.stderr.trim().is_empty() { write!(f, "\n\n{}\n{}", "[stderr]".red(), self.stderr)?; non_empty = true; } if non_empty { writeln!(f)?; } Ok(()) } } #[derive(Debug, Error)] pub enum Error { #[error("Failed to query Python interpreter")] Io(#[from] io::Error), #[error(transparent)] BrokenSymlink(BrokenSymlink), #[error("Python interpreter not found at `{0}`")] NotFound(PathBuf), #[error("Failed to query Python interpreter at `{path}`")] SpawnFailed { path: PathBuf, #[source] err: io::Error, }, #[cfg(windows)] #[error("Failed to query Python interpreter at `{path}`")] CorruptWindowsPackage { path: PathBuf, #[source] err: io::Error, }, #[error("Failed to query Python interpreter at `{path}`")] PermissionDenied { path: PathBuf, #[source] err: io::Error, }, #[error("{0}")] UnexpectedResponse(UnexpectedResponseError), #[error("{0}")] StatusCode(StatusCodeError), #[error("Can't use Python at `{path}`")] QueryScript { #[source] err: InterpreterInfoError, path: PathBuf, }, #[error("Failed to write to cache")] Encode(#[from] rmp_serde::encode::Error), } #[derive(Debug, Error)] pub struct BrokenSymlink { pub path: PathBuf, /// Whether the interpreter path looks like a virtual environment. pub venv: bool, } impl Display for BrokenSymlink { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!( f, "Broken symlink at `{}`, was the underlying Python interpreter removed?", self.path.user_display() )?; if self.venv { write!( f, "\n\n{}{} Consider recreating the environment (e.g., with `{}`)", "hint".bold().cyan(), ":".bold(), "uv venv".green() )?; } Ok(()) } } #[derive(Debug, Deserialize, Serialize)] #[serde(tag = "result", rename_all = "lowercase")] enum InterpreterInfoResult { Error(InterpreterInfoError), Success(Box<InterpreterInfo>), } #[derive(Debug, Error, Deserialize, Serialize)] #[serde(tag = "kind", rename_all = "snake_case")] pub enum InterpreterInfoError { #[error("Could not detect a glibc or a musl libc (while running on Linux)")] LibcNotFound, #[error(
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/microsoft_store.rs
crates/uv-python/src/microsoft_store.rs
//! Microsoft Store Pythons don't register themselves in the registry, so we have to look for them //! in known locations. //! //! Effectively a port of <https://github.com/python/cpython/blob/58ce131037ecb34d506a613f21993cde2056f628/PC/launcher2.c#L1744> use crate::PythonVersion; use crate::windows_registry::WindowsPython; use itertools::Either; use std::env; use std::path::PathBuf; use std::str::FromStr; use tracing::debug; use uv_static::EnvVars; #[derive(Debug)] struct MicrosoftStorePython { family_name: &'static str, version: &'static str, } /// List of known Microsoft Store Pythons. /// /// Copied from <https://github.com/python/cpython/blob/58ce131037ecb34d506a613f21993cde2056f628/PC/launcher2.c#L1963-L1985>, /// please update when upstream changes. const MICROSOFT_STORE_PYTHONS: &[MicrosoftStorePython] = &[ // Releases made through the Store MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.13_qbz5n2kfra8p0", version: "3.13", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0", version: "3.12", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0", version: "3.11", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0", version: "3.10", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0", version: "3.9", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0", version: "3.8", }, // Side-loadable releases MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.13_3847v3x7pw1km", version: "3.13", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.12_3847v3x7pw1km", version: "3.12", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.11_3847v3x7pw1km", version: "3.11", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.11_hd69rhyc2wevp", version: "3.11", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.10_3847v3x7pw1km", version: "3.10", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.10_hd69rhyc2wevp", version: "3.10", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.9_3847v3x7pw1km", version: "3.9", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.9_hd69rhyc2wevp", version: "3.9", }, MicrosoftStorePython { family_name: "PythonSoftwareFoundation.Python.3.8_hd69rhyc2wevp", version: "3.8", }, ]; /// Microsoft Store Pythons don't register themselves in the registry, so we have to look for them /// in known locations. /// /// Effectively a port of <https://github.com/python/cpython/blob/58ce131037ecb34d506a613f21993cde2056f628/PC/launcher2.c#L1744> pub(crate) fn find_microsoft_store_pythons() -> impl Iterator<Item = WindowsPython> { let Ok(local_app_data) = env::var(EnvVars::LOCALAPPDATA) else { debug!("`LOCALAPPDATA` not set, ignoring Microsoft store Pythons"); return Either::Left(std::iter::empty()); }; let windows_apps = PathBuf::from(local_app_data) .join("Microsoft") .join("WindowsApps"); Either::Right( MICROSOFT_STORE_PYTHONS .iter() .map(move |store_python| { let path = windows_apps .join(store_python.family_name) .join("python.exe"); WindowsPython { path, // All versions are constants, we know they are valid. version: Some(PythonVersion::from_str(store_python.version).unwrap()), } }) .filter(|windows_python| windows_python.path.is_file()), ) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/managed.rs
crates/uv-python/src/managed.rs
use core::fmt; use std::borrow::Cow; use std::cmp::Reverse; use std::ffi::OsStr; use std::io::{self, Write}; #[cfg(windows)] use std::os::windows::fs::MetadataExt; use std::path::{Path, PathBuf}; use std::str::FromStr; use fs_err as fs; use itertools::Itertools; use thiserror::Error; use tracing::{debug, warn}; use uv_preview::{Preview, PreviewFeatures}; #[cfg(windows)] use windows::Win32::Storage::FileSystem::FILE_ATTRIBUTE_REPARSE_POINT; use uv_fs::{ LockedFile, LockedFileError, LockedFileMode, Simplified, replace_symlink, symlink_or_copy_file, }; use uv_platform::{Error as PlatformError, Os}; use uv_platform::{LibcDetectionError, Platform}; use uv_state::{StateBucket, StateStore}; use uv_static::EnvVars; use uv_trampoline_builder::{Launcher, LauncherKind}; use crate::downloads::{Error as DownloadError, ManagedPythonDownload}; use crate::implementation::{ Error as ImplementationError, ImplementationName, LenientImplementationName, }; use crate::installation::{self, PythonInstallationKey}; use crate::python_version::PythonVersion; use crate::{ PythonInstallationMinorVersionKey, PythonRequest, PythonVariant, macos_dylib, sysconfig, }; #[derive(Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), #[error(transparent)] LockedFile(#[from] LockedFileError), #[error(transparent)] Download(#[from] DownloadError), #[error(transparent)] PlatformError(#[from] PlatformError), #[error(transparent)] ImplementationError(#[from] ImplementationError), #[error("Invalid python version: {0}")] InvalidPythonVersion(String), #[error(transparent)] ExtractError(#[from] uv_extract::Error), #[error(transparent)] SysconfigError(#[from] sysconfig::Error), #[error("Failed to copy to: {0}", to.user_display())] CopyError { to: PathBuf, #[source] err: io::Error, }, #[error("Missing expected Python executable at {}", _0.user_display())] MissingExecutable(PathBuf), #[error("Missing expected target directory for Python minor version link at {}", _0.user_display())] MissingPythonMinorVersionLinkTargetDirectory(PathBuf), #[error("Failed to create canonical Python executable at {} from {}", to.user_display(), from.user_display())] CanonicalizeExecutable { from: PathBuf, to: PathBuf, #[source] err: io::Error, }, #[error("Failed to create Python executable link at {} from {}", to.user_display(), from.user_display())] LinkExecutable { from: PathBuf, to: PathBuf, #[source] err: io::Error, }, #[error("Failed to create Python minor version link directory at {} from {}", to.user_display(), from.user_display())] PythonMinorVersionLinkDirectory { from: PathBuf, to: PathBuf, #[source] err: io::Error, }, #[error("Failed to create directory for Python executable link at {}", to.user_display())] ExecutableDirectory { to: PathBuf, #[source] err: io::Error, }, #[error("Failed to read Python installation directory: {0}", dir.user_display())] ReadError { dir: PathBuf, #[source] err: io::Error, }, #[error("Failed to find a directory to install executables into")] NoExecutableDirectory, #[error(transparent)] LauncherError(#[from] uv_trampoline_builder::Error), #[error("Failed to read managed Python directory name: {0}")] NameError(String), #[error("Failed to construct absolute path to managed Python directory: {}", _0.user_display())] AbsolutePath(PathBuf, #[source] io::Error), #[error(transparent)] NameParseError(#[from] installation::PythonInstallationKeyError), #[error("Failed to determine the libc used on the current platform")] LibcDetection(#[from] LibcDetectionError), #[error(transparent)] MacOsDylib(#[from] macos_dylib::Error), } /// A collection of uv-managed Python installations installed on the current system. #[derive(Debug, Clone, Eq, PartialEq)] pub struct ManagedPythonInstallations { /// The path to the top-level directory of the installed Python versions. root: PathBuf, } impl ManagedPythonInstallations { /// A directory for Python installations at `root`. fn from_path(root: impl Into<PathBuf>) -> Self { Self { root: root.into() } } /// Grab a file lock for the managed Python distribution directory to prevent concurrent access /// across processes. pub async fn lock(&self) -> Result<LockedFile, Error> { Ok(LockedFile::acquire( self.root.join(".lock"), LockedFileMode::Exclusive, self.root.user_display(), ) .await?) } /// Prefer, in order: /// /// 1. The specific Python directory passed via the `install_dir` argument. /// 2. The specific Python directory specified with the `UV_PYTHON_INSTALL_DIR` environment variable. /// 3. A directory in the system-appropriate user-level data directory, e.g., `~/.local/uv/python`. /// 4. A directory in the local data directory, e.g., `./.uv/python`. pub fn from_settings(install_dir: Option<PathBuf>) -> Result<Self, Error> { if let Some(install_dir) = install_dir { Ok(Self::from_path(install_dir)) } else if let Some(install_dir) = std::env::var_os(EnvVars::UV_PYTHON_INSTALL_DIR).filter(|s| !s.is_empty()) { Ok(Self::from_path(install_dir)) } else { Ok(Self::from_path( StateStore::from_settings(None)?.bucket(StateBucket::ManagedPython), )) } } /// Create a temporary Python installation directory. pub fn temp() -> Result<Self, Error> { Ok(Self::from_path( StateStore::temp()?.bucket(StateBucket::ManagedPython), )) } /// Return the location of the scratch directory for managed Python installations. pub fn scratch(&self) -> PathBuf { self.root.join(".temp") } /// Initialize the Python installation directory. /// /// Ensures the directory is created. pub fn init(self) -> Result<Self, Error> { let root = &self.root; // Support `toolchains` -> `python` migration transparently. if !root.exists() && root .parent() .is_some_and(|parent| parent.join("toolchains").exists()) { let deprecated = root.parent().unwrap().join("toolchains"); // Move the deprecated directory to the new location. fs::rename(&deprecated, root)?; // Create a link or junction to at the old location uv_fs::replace_symlink(root, &deprecated)?; } else { fs::create_dir_all(root)?; } // Create the directory, if it doesn't exist. fs::create_dir_all(root)?; // Create the scratch directory, if it doesn't exist. let scratch = self.scratch(); fs::create_dir_all(&scratch)?; // Add a .gitignore. match fs::OpenOptions::new() .write(true) .create_new(true) .open(root.join(".gitignore")) { Ok(mut file) => file.write_all(b"*")?, Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (), Err(err) => return Err(err.into()), } Ok(self) } /// Iterate over each Python installation in this directory. /// /// Pythons are sorted by [`PythonInstallationKey`], for the same implementation name, the newest versions come first. /// This ensures a consistent ordering across all platforms. pub fn find_all( &self, ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> { let dirs = match fs_err::read_dir(&self.root) { Ok(installation_dirs) => { // Collect sorted directory paths; `read_dir` is not stable across platforms let directories: Vec<_> = installation_dirs .filter_map(|read_dir| match read_dir { Ok(entry) => match entry.file_type() { Ok(file_type) => file_type.is_dir().then_some(Ok(entry.path())), Err(err) => Some(Err(err)), }, Err(err) => Some(Err(err)), }) .collect::<Result<_, io::Error>>() .map_err(|err| Error::ReadError { dir: self.root.clone(), err, })?; directories } Err(err) if err.kind() == io::ErrorKind::NotFound => vec![], Err(err) => { return Err(Error::ReadError { dir: self.root.clone(), err, }); } }; let scratch = self.scratch(); Ok(dirs .into_iter() // Ignore the scratch directory .filter(|path| *path != scratch) // Ignore any `.` prefixed directories .filter(|path| { path.file_name() .and_then(OsStr::to_str) .map(|name| !name.starts_with('.')) .unwrap_or(true) }) .filter_map(|path| { ManagedPythonInstallation::from_path(path) .inspect_err(|err| { warn!("Ignoring malformed managed Python entry:\n {err}"); }) .ok() }) .sorted_unstable_by_key(|installation| Reverse(installation.key().clone()))) } /// Iterate over Python installations that support the current platform. pub fn find_matching_current_platform( &self, ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + use<>, Error> { let platform = Platform::from_env()?; let iter = Self::from_settings(None)? .find_all()? .filter(move |installation| { if !platform.supports(installation.platform()) { debug!("Skipping managed installation `{installation}`: not supported by current platform `{platform}`"); return false; } true }); Ok(iter) } /// Iterate over managed Python installations that satisfy the requested version on this platform. /// /// ## Errors /// /// - The platform metadata cannot be read /// - A directory for the installation cannot be read pub fn find_version<'a>( &'a self, version: &'a PythonVersion, ) -> Result<impl DoubleEndedIterator<Item = ManagedPythonInstallation> + 'a, Error> { Ok(self .find_matching_current_platform()? .filter(move |installation| { installation .path .file_name() .map(OsStr::to_string_lossy) .is_some_and(|filename| filename.starts_with(&format!("cpython-{version}"))) })) } pub fn root(&self) -> &Path { &self.root } } static EXTERNALLY_MANAGED: &str = "[externally-managed] Error=This Python installation is managed by uv and should not be modified. "; /// A uv-managed Python installation on the current system. #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct ManagedPythonInstallation { /// The path to the top-level directory of the installed Python. path: PathBuf, /// An install key for the Python version. key: PythonInstallationKey, /// The URL with the Python archive. /// /// Empty when self was constructed from a path. url: Option<Cow<'static, str>>, /// The SHA256 of the Python archive at the URL. /// /// Empty when self was constructed from a path. sha256: Option<Cow<'static, str>>, /// The build version of the Python installation. /// /// Empty when self was constructed from a path without a BUILD file. build: Option<Cow<'static, str>>, } impl ManagedPythonInstallation { pub fn new(path: PathBuf, download: &ManagedPythonDownload) -> Self { Self { path, key: download.key().clone(), url: Some(download.url().clone()), sha256: download.sha256().cloned(), build: download.build().map(Cow::Borrowed), } } pub(crate) fn from_path(path: PathBuf) -> Result<Self, Error> { let key = PythonInstallationKey::from_str( path.file_name() .ok_or(Error::NameError("name is empty".to_string()))? .to_str() .ok_or(Error::NameError("not a valid string".to_string()))?, )?; let path = std::path::absolute(&path).map_err(|err| Error::AbsolutePath(path, err))?; // Try to read the BUILD file if it exists let build = match fs::read_to_string(path.join("BUILD")) { Ok(content) => Some(Cow::Owned(content.trim().to_string())), Err(err) if err.kind() == io::ErrorKind::NotFound => None, Err(err) => return Err(err.into()), }; Ok(Self { path, key, url: None, sha256: None, build, }) } /// The path to this managed installation's Python executable. /// /// If the installation has multiple executables i.e., `python`, `python3`, etc., this will /// return the _canonical_ executable name which the other names link to. On Unix, this is /// `python{major}.{minor}{variant}` and on Windows, this is `python{exe}`. /// /// If windowed is true, `pythonw.exe` is selected over `python.exe` on windows, with no changes /// on non-windows. pub fn executable(&self, windowed: bool) -> PathBuf { let version = match self.implementation() { ImplementationName::CPython => { if cfg!(unix) { format!("{}.{}", self.key.major, self.key.minor) } else { String::new() } } // PyPy uses a full version number, even on Windows. ImplementationName::PyPy => format!("{}.{}", self.key.major, self.key.minor), // Pyodide and GraalPy do not have a version suffix. ImplementationName::Pyodide => String::new(), ImplementationName::GraalPy => String::new(), }; // On Windows, the executable is just `python.exe` even for alternative variants // GraalPy always uses `graalpy.exe` as the main executable let variant = if self.implementation() == ImplementationName::GraalPy { "" } else if cfg!(unix) { self.key.variant.executable_suffix() } else if cfg!(windows) && windowed { // Use windowed Python that doesn't open a terminal. "w" } else { "" }; let name = format!( "{implementation}{version}{variant}{exe}", implementation = self.implementation().executable_name(), exe = std::env::consts::EXE_SUFFIX ); let executable = executable_path_from_base( self.python_dir().as_path(), &name, &LenientImplementationName::from(self.implementation()), *self.key.os(), ); // Workaround for python-build-standalone v20241016 which is missing the standard // `python.exe` executable in free-threaded distributions on Windows. // // See https://github.com/astral-sh/uv/issues/8298 if cfg!(windows) && matches!(self.key.variant, PythonVariant::Freethreaded) && !executable.exists() { // This is the alternative executable name for the freethreaded variant return self.python_dir().join(format!( "python{}.{}t{}", self.key.major, self.key.minor, std::env::consts::EXE_SUFFIX )); } executable } fn python_dir(&self) -> PathBuf { let install = self.path.join("install"); if install.is_dir() { install } else { self.path.clone() } } /// The [`PythonVersion`] of the toolchain. pub fn version(&self) -> PythonVersion { self.key.version() } pub fn implementation(&self) -> ImplementationName { match self.key.implementation().into_owned() { LenientImplementationName::Known(implementation) => implementation, LenientImplementationName::Unknown(_) => { panic!("Managed Python installations should have a known implementation") } } } pub fn path(&self) -> &Path { &self.path } pub fn key(&self) -> &PythonInstallationKey { &self.key } pub fn platform(&self) -> &Platform { self.key.platform() } /// The build version of this installation, if available. pub fn build(&self) -> Option<&str> { self.build.as_deref() } pub fn minor_version_key(&self) -> &PythonInstallationMinorVersionKey { PythonInstallationMinorVersionKey::ref_cast(&self.key) } pub fn satisfies(&self, request: &PythonRequest) -> bool { match request { PythonRequest::File(path) => self.executable(false) == *path, PythonRequest::Default | PythonRequest::Any => true, PythonRequest::Directory(path) => self.path() == *path, PythonRequest::ExecutableName(name) => self .executable(false) .file_name() .is_some_and(|filename| filename.to_string_lossy() == *name), PythonRequest::Implementation(implementation) => { *implementation == self.implementation() } PythonRequest::ImplementationVersion(implementation, version) => { *implementation == self.implementation() && version.matches_version(&self.version()) } PythonRequest::Version(version) => version.matches_version(&self.version()), PythonRequest::Key(request) => request.satisfied_by_key(self.key()), } } /// Ensure the environment contains the canonical Python executable names. pub fn ensure_canonical_executables(&self) -> Result<(), Error> { let python = self.executable(false); let canonical_names = &["python"]; for name in canonical_names { let executable = python.with_file_name(format!("{name}{exe}", exe = std::env::consts::EXE_SUFFIX)); // Do not attempt to perform same-file copies — this is fine on Unix but fails on // Windows with a permission error instead of 'already exists' if executable == python { continue; } match symlink_or_copy_file(&python, &executable) { Ok(()) => { debug!( "Created link {} -> {}", executable.user_display(), python.user_display(), ); } Err(err) if err.kind() == io::ErrorKind::NotFound => { return Err(Error::MissingExecutable(python.clone())); } Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} Err(err) => { return Err(Error::CanonicalizeExecutable { from: executable, to: python, err, }); } } } Ok(()) } /// Ensure the environment contains the symlink directory (or junction on Windows) /// pointing to the patch directory for this minor version. pub fn ensure_minor_version_link(&self, preview: Preview) -> Result<(), Error> { if let Some(minor_version_link) = PythonMinorVersionLink::from_installation(self, preview) { minor_version_link.create_directory()?; } Ok(()) } /// If the environment contains a symlink directory (or junction on Windows), /// update it to the latest patch directory for this minor version. /// /// Unlike [`ensure_minor_version_link`], will not create a new symlink directory /// if one doesn't already exist, pub fn update_minor_version_link(&self, preview: Preview) -> Result<(), Error> { if let Some(minor_version_link) = PythonMinorVersionLink::from_installation(self, preview) { if !minor_version_link.exists() { return Ok(()); } minor_version_link.create_directory()?; } Ok(()) } /// Ensure the environment is marked as externally managed with the /// standard `EXTERNALLY-MANAGED` file. pub fn ensure_externally_managed(&self) -> Result<(), Error> { if self.key.os().is_emscripten() { // Emscripten's stdlib is a zip file so we can't put an // EXTERNALLY-MANAGED inside. return Ok(()); } // Construct the path to the `stdlib` directory. let stdlib = if self.key.os().is_windows() { self.python_dir().join("Lib") } else { let lib_suffix = self.key.variant.lib_suffix(); let python = if matches!( self.key.implementation, LenientImplementationName::Known(ImplementationName::PyPy) ) { format!("pypy{}", self.key.version().python_version()) } else { format!("python{}{lib_suffix}", self.key.version().python_version()) }; self.python_dir().join("lib").join(python) }; let file = stdlib.join("EXTERNALLY-MANAGED"); fs_err::write(file, EXTERNALLY_MANAGED)?; Ok(()) } /// Ensure that the `sysconfig` data is patched to match the installation path. pub fn ensure_sysconfig_patched(&self) -> Result<(), Error> { if cfg!(unix) { if self.key.os().is_emscripten() { // Emscripten's stdlib is a zip file so we can't update the // sysconfig directly return Ok(()); } if self.implementation() == ImplementationName::CPython { sysconfig::update_sysconfig( self.path(), self.key.major, self.key.minor, self.key.variant.lib_suffix(), )?; } } Ok(()) } /// On macOS, ensure that the `install_name` for the Python dylib is set /// correctly, rather than pointing at `/install/lib/libpython{version}.dylib`. /// This is necessary to ensure that native extensions written in Rust /// link to the correct location for the Python library. /// /// See <https://github.com/astral-sh/uv/issues/10598> for more information. pub fn ensure_dylib_patched(&self) -> Result<(), macos_dylib::Error> { if cfg!(target_os = "macos") { if self.key().os().is_like_darwin() { if self.implementation() == ImplementationName::CPython { let dylib_path = self.python_dir().join("lib").join(format!( "{}python{}{}{}", std::env::consts::DLL_PREFIX, self.key.version().python_version(), self.key.variant().executable_suffix(), std::env::consts::DLL_SUFFIX )); macos_dylib::patch_dylib_install_name(dylib_path)?; } } } Ok(()) } /// Ensure the build version is written to a BUILD file in the installation directory. pub fn ensure_build_file(&self) -> Result<(), Error> { if let Some(ref build) = self.build { let build_file = self.path.join("BUILD"); fs::write(&build_file, build.as_ref())?; } Ok(()) } /// Returns `true` if the path is a link to this installation's binary, e.g., as created by /// [`create_bin_link`]. pub fn is_bin_link(&self, path: &Path) -> bool { if cfg!(unix) { same_file::is_same_file(path, self.executable(false)).unwrap_or_default() } else if cfg!(windows) { let Some(launcher) = Launcher::try_from_path(path).unwrap_or_default() else { return false; }; if !matches!(launcher.kind, LauncherKind::Python) { return false; } // We canonicalize the target path of the launcher in case it includes a minor version // junction directory. If canonicalization fails, we check against the launcher path // directly. dunce::canonicalize(&launcher.python_path).unwrap_or(launcher.python_path) == self.executable(false) } else { unreachable!("Only Windows and Unix are supported") } } /// Returns `true` if self is a suitable upgrade of other. pub fn is_upgrade_of(&self, other: &Self) -> bool { // Require matching implementation if self.key.implementation != other.key.implementation { return false; } // Require a matching variant if self.key.variant != other.key.variant { return false; } // Require matching minor version if (self.key.major, self.key.minor) != (other.key.major, other.key.minor) { return false; } // If the patch versions are the same, we're handling a pre-release upgrade if self.key.patch == other.key.patch { return match (self.key.prerelease, other.key.prerelease) { // Require a newer pre-release, if present on both (Some(self_pre), Some(other_pre)) => self_pre > other_pre, // Allow upgrade from pre-release to stable (None, Some(_)) => true, // Do not upgrade from pre-release to stable, or for matching versions (_, None) => false, }; } // Require a newer patch version if self.key.patch < other.key.patch { return false; } true } pub fn url(&self) -> Option<&str> { self.url.as_deref() } pub fn sha256(&self) -> Option<&str> { self.sha256.as_deref() } } /// A representation of a minor version symlink directory (or junction on Windows) /// linking to the home directory of a Python installation. #[derive(Clone, Debug)] pub struct PythonMinorVersionLink { /// The symlink directory (or junction on Windows). pub symlink_directory: PathBuf, /// The full path to the executable including the symlink directory /// (or junction on Windows). pub symlink_executable: PathBuf, /// The target directory for the symlink. This is the home directory for /// a Python installation. pub target_directory: PathBuf, } impl PythonMinorVersionLink { /// Attempt to derive a path from an executable path that substitutes a minor /// version symlink directory (or junction on Windows) for the patch version /// directory. /// /// The implementation is expected to be CPython and, on Unix, the base Python is /// expected to be in `<home>/bin/` on Unix. If either condition isn't true, /// return [`None`]. /// /// # Examples /// /// ## Unix /// For a Python 3.10.8 installation in `/path/to/uv/python/cpython-3.10.8-macos-aarch64-none/bin/python3.10`, /// the symlink directory would be `/path/to/uv/python/cpython-3.10-macos-aarch64-none` and the executable path including the /// symlink directory would be `/path/to/uv/python/cpython-3.10-macos-aarch64-none/bin/python3.10`. /// /// ## Windows /// For a Python 3.10.8 installation in `C:\path\to\uv\python\cpython-3.10.8-windows-x86_64-none\python.exe`, /// the junction would be `C:\path\to\uv\python\cpython-3.10-windows-x86_64-none` and the executable path including the /// junction would be `C:\path\to\uv\python\cpython-3.10-windows-x86_64-none\python.exe`. pub fn from_executable( executable: &Path, key: &PythonInstallationKey, preview: Preview, ) -> Option<Self> { let implementation = key.implementation(); if !matches!( implementation.as_ref(), LenientImplementationName::Known(ImplementationName::CPython) ) { // We don't currently support transparent upgrades for PyPy or GraalPy. return None; } let executable_name = executable .file_name() .expect("Executable file name should exist"); let symlink_directory_name = PythonInstallationMinorVersionKey::ref_cast(key).to_string(); let parent = executable .parent() .expect("Executable should have parent directory"); // The home directory of the Python installation let target_directory = if cfg!(unix) { if parent .components() .next_back() .is_some_and(|c| c.as_os_str() == "bin") { parent.parent()?.to_path_buf() } else { return None; } } else if cfg!(windows) { parent.to_path_buf() } else { unimplemented!("Only Windows and Unix systems are supported.") }; let symlink_directory = target_directory.with_file_name(symlink_directory_name); // If this would create a circular link, return `None`. if target_directory == symlink_directory { return None; } // The full executable path including the symlink directory (or junction). let symlink_executable = executable_path_from_base( symlink_directory.as_path(), &executable_name.to_string_lossy(), &implementation, *key.os(), ); let minor_version_link = Self { symlink_directory, symlink_executable, target_directory, }; // If preview mode is disabled, still return a `MinorVersionSymlink` for // existing symlinks, allowing continued operations without the `--preview` // flag after initial symlink directory installation. if !preview.is_enabled(PreviewFeatures::PYTHON_UPGRADE) && !minor_version_link.exists() { return None; } Some(minor_version_link) } pub fn from_installation( installation: &ManagedPythonInstallation, preview: Preview, ) -> Option<Self> { Self::from_executable( installation.executable(false).as_path(), installation.key(), preview, ) } pub fn create_directory(&self) -> Result<(), Error> { match replace_symlink( self.target_directory.as_path(), self.symlink_directory.as_path(), ) { Ok(()) => { debug!( "Created link {} -> {}", &self.symlink_directory.user_display(), &self.target_directory.user_display(), ); } Err(err) if err.kind() == io::ErrorKind::NotFound => { return Err(Error::MissingPythonMinorVersionLinkTargetDirectory( self.target_directory.clone(), )); } Err(err) if err.kind() == io::ErrorKind::AlreadyExists => {} Err(err) => { return Err(Error::PythonMinorVersionLinkDirectory { from: self.symlink_directory.clone(), to: self.target_directory.clone(), err, }); } } Ok(()) } pub fn exists(&self) -> bool { #[cfg(unix)] { self.symlink_directory .symlink_metadata() .map(|metadata| metadata.file_type().is_symlink()) .unwrap_or(false) } #[cfg(windows)] { self.symlink_directory .symlink_metadata()
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/macos_dylib.rs
crates/uv-python/src/macos_dylib.rs
use std::{io::ErrorKind, path::PathBuf}; use uv_fs::Simplified as _; use uv_warnings::warn_user; use crate::managed::ManagedPythonInstallation; pub fn patch_dylib_install_name(dylib: PathBuf) -> Result<(), Error> { let output = match std::process::Command::new("install_name_tool") .arg("-id") .arg(&dylib) .arg(&dylib) .output() { Ok(output) => output, Err(e) => { let e = if e.kind() == ErrorKind::NotFound { Error::MissingInstallNameTool } else { e.into() }; return Err(e); } }; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); return Err(Error::RenameError { dylib, stderr }); } Ok(()) } #[derive(thiserror::Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[error("`install_name_tool` is not available on this system. This utility is part of macOS Developer Tools. Please ensure that the Xcode Command Line Tools are installed by running: xcode-select --install For more information, see: https://developer.apple.com/xcode/")] MissingInstallNameTool, #[error("Failed to update the install name of the Python dynamic library located at `{}`", dylib.user_display())] RenameError { dylib: PathBuf, stderr: String }, } impl Error { /// Emit a user-friendly warning about the patching failure. pub fn warn_user(&self, installation: &ManagedPythonInstallation) { let error = if tracing::enabled!(tracing::Level::DEBUG) { format!("\nUnderlying error: {self}") } else { String::new() }; warn_user!( "Failed to patch the install name of the dynamic library for {}. This may cause issues when building Python native extensions.{}", installation.executable(false).simplified_display(), error ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/virtualenv.rs
crates/uv-python/src/virtualenv.rs
use std::borrow::Cow; use std::str::FromStr; use std::{ env, io, path::{Path, PathBuf}, }; use fs_err as fs; use thiserror::Error; use uv_pypi_types::Scheme; use uv_static::EnvVars; use crate::PythonVersion; /// The layout of a virtual environment. #[derive(Debug)] pub struct VirtualEnvironment { /// The absolute path to the root of the virtualenv, e.g., `/path/to/.venv`. pub root: PathBuf, /// The path to the Python interpreter inside the virtualenv, e.g., `.venv/bin/python` /// (Unix, Python 3.11). pub executable: PathBuf, /// The path to the base executable for the environment, within the `home` directory. pub base_executable: PathBuf, /// The [`Scheme`] paths for the virtualenv, as returned by (e.g.) `sysconfig.get_paths()`. pub scheme: Scheme, } /// A parsed `pyvenv.cfg` #[derive(Debug, Clone)] pub struct PyVenvConfiguration { /// Was the virtual environment created with the `virtualenv` package? pub(crate) virtualenv: bool, /// Was the virtual environment created with the `uv` package? pub(crate) uv: bool, /// Is the virtual environment relocatable? pub(crate) relocatable: bool, /// Was the virtual environment populated with seed packages? pub(crate) seed: bool, /// Should the virtual environment include system site packages? pub(crate) include_system_site_packages: bool, /// The Python version the virtual environment was created with pub(crate) version: Option<PythonVersion>, } #[derive(Debug, Error)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), #[error("Broken virtual environment `{0}`: `pyvenv.cfg` is missing")] MissingPyVenvCfg(PathBuf), #[error("Broken virtual environment `{0}`: `pyvenv.cfg` could not be parsed")] ParsePyVenvCfg(PathBuf, #[source] io::Error), } /// Locate an active virtual environment by inspecting environment variables. /// /// Supports `VIRTUAL_ENV`. pub(crate) fn virtualenv_from_env() -> Option<PathBuf> { if let Some(dir) = env::var_os(EnvVars::VIRTUAL_ENV).filter(|value| !value.is_empty()) { return Some(PathBuf::from(dir)); } None } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub(crate) enum CondaEnvironmentKind { /// The base Conda environment; treated like a system Python environment. Base, /// Any other Conda environment; treated like a virtual environment. Child, } impl CondaEnvironmentKind { /// Whether the given `CONDA_PREFIX` path is the base Conda environment. /// /// The base environment is typically stored in a location matching the `_CONDA_ROOT` path. /// /// Additionally, when the base environment is active, `CONDA_DEFAULT_ENV` will be set to a /// name, e.g., `base`, which does not match the `CONDA_PREFIX`, e.g., `/usr/local` instead of /// `/usr/local/conda/envs/<name>`. Note the name `CONDA_DEFAULT_ENV` is misleading, it's the /// active environment name, not a constant base environment name. fn from_prefix_path(path: &Path) -> Self { // Pixi never creates true "base" envs and names project envs "default", confusing our // heuristics, so treat Pixi prefixes as child envs outright. if is_pixi_environment(path) { return Self::Child; } // If `_CONDA_ROOT` is set and matches `CONDA_PREFIX`, it's the base environment. if let Ok(conda_root) = env::var(EnvVars::CONDA_ROOT) { if path == Path::new(&conda_root) { return Self::Base; } } // Next, we'll use a heuristic based on `CONDA_DEFAULT_ENV` let Ok(current_env) = env::var(EnvVars::CONDA_DEFAULT_ENV) else { return Self::Child; }; // If the `CONDA_PREFIX` equals the `CONDA_DEFAULT_ENV`, we're in an unnamed environment // which is typical for environments created with `conda create -p /path/to/env`. if path == Path::new(&current_env) { return Self::Child; } // If the environment name is "base" or "root", treat it as a base environment // // These are the expected names for the base environment; and is retained for backwards // compatibility, but in a future breaking release we should remove this special-casing. if current_env == "base" || current_env == "root" { return Self::Base; } // For other environment names, use the path-based logic let Some(name) = path.file_name() else { return Self::Child; }; // If the environment is in a directory matching the name of the environment, it's not // usually a base environment. if name.to_str().is_some_and(|name| name == current_env) { Self::Child } else { Self::Base } } } /// Detect whether the current `CONDA_PREFIX` belongs to a Pixi-managed environment. fn is_pixi_environment(path: &Path) -> bool { path.join("conda-meta").join("pixi").is_file() } /// Locate an active conda environment by inspecting environment variables. /// /// If `base` is true, the active environment must be the base environment or `None` is returned, /// and vice-versa. pub(crate) fn conda_environment_from_env(kind: CondaEnvironmentKind) -> Option<PathBuf> { let dir = env::var_os(EnvVars::CONDA_PREFIX).filter(|value| !value.is_empty())?; let path = PathBuf::from(dir); if kind != CondaEnvironmentKind::from_prefix_path(&path) { return None; } Some(path) } /// Locate a virtual environment by searching the file system. /// /// Searches for a `.venv` directory in the current or any parent directory. If the current /// directory is itself a virtual environment (or a subdirectory of a virtual environment), the /// containing virtual environment is returned. pub(crate) fn virtualenv_from_working_dir() -> Result<Option<PathBuf>, Error> { let current_dir = crate::current_dir()?; for dir in current_dir.ancestors() { // If we're _within_ a virtualenv, return it. if uv_fs::is_virtualenv_base(dir) { return Ok(Some(dir.to_path_buf())); } // Otherwise, search for a `.venv` directory. let dot_venv = dir.join(".venv"); if dot_venv.is_dir() { if !uv_fs::is_virtualenv_base(&dot_venv) { return Err(Error::MissingPyVenvCfg(dot_venv)); } return Ok(Some(dot_venv)); } } Ok(None) } /// Returns the path to the `python` executable inside a virtual environment. pub(crate) fn virtualenv_python_executable(venv: impl AsRef<Path>) -> PathBuf { let venv = venv.as_ref(); if cfg!(windows) { // Search for `python.exe` in the `Scripts` directory. let default_executable = venv.join("Scripts").join("python.exe"); if default_executable.exists() { return default_executable; } // Apparently, Python installed via msys2 on Windows _might_ produce a POSIX-like layout. // See: https://github.com/PyO3/maturin/issues/1108 let executable = venv.join("bin").join("python.exe"); if executable.exists() { return executable; } // Fallback for Conda environments. let executable = venv.join("python.exe"); if executable.exists() { return executable; } // If none of these exist, return the standard location default_executable } else { // Check for both `python3` over `python`, preferring the more specific one let default_executable = venv.join("bin").join("python3"); if default_executable.exists() { return default_executable; } let executable = venv.join("bin").join("python"); if executable.exists() { return executable; } // If none of these exist, return the standard location default_executable } } impl PyVenvConfiguration { /// Parse a `pyvenv.cfg` file into a [`PyVenvConfiguration`]. pub fn parse(cfg: impl AsRef<Path>) -> Result<Self, Error> { let mut virtualenv = false; let mut uv = false; let mut relocatable = false; let mut seed = false; let mut include_system_site_packages = true; let mut version = None; // Per https://snarky.ca/how-virtual-environments-work/, the `pyvenv.cfg` file is not a // valid INI file, and is instead expected to be parsed by partitioning each line on the // first equals sign. let content = fs::read_to_string(&cfg) .map_err(|err| Error::ParsePyVenvCfg(cfg.as_ref().to_path_buf(), err))?; for line in content.lines() { let Some((key, value)) = line.split_once('=') else { continue; }; match key.trim() { "virtualenv" => { virtualenv = true; } "uv" => { uv = true; } "relocatable" => { relocatable = value.trim().to_lowercase() == "true"; } "seed" => { seed = value.trim().to_lowercase() == "true"; } "include-system-site-packages" => { include_system_site_packages = value.trim().to_lowercase() == "true"; } "version" | "version_info" => { version = Some( PythonVersion::from_str(value.trim()) .map_err(|e| io::Error::new(std::io::ErrorKind::InvalidData, e))?, ); } _ => {} } } Ok(Self { virtualenv, uv, relocatable, seed, include_system_site_packages, version, }) } /// Returns true if the virtual environment was created with the `virtualenv` package. pub fn is_virtualenv(&self) -> bool { self.virtualenv } /// Returns true if the virtual environment was created with the uv package. pub fn is_uv(&self) -> bool { self.uv } /// Returns true if the virtual environment is relocatable. pub fn is_relocatable(&self) -> bool { self.relocatable } /// Returns true if the virtual environment was populated with seed packages. pub fn is_seed(&self) -> bool { self.seed } /// Returns true if the virtual environment should include system site packages. pub fn include_system_site_packages(&self) -> bool { self.include_system_site_packages } /// Set the key-value pair in the `pyvenv.cfg` file. pub fn set(content: &str, key: &str, value: &str) -> String { let mut lines = content.lines().map(Cow::Borrowed).collect::<Vec<_>>(); let mut found = false; for line in &mut lines { if let Some((lhs, _)) = line.split_once('=') { if lhs.trim() == key { *line = Cow::Owned(format!("{key} = {value}")); found = true; break; } } } if !found { lines.push(Cow::Owned(format!("{key} = {value}"))); } if lines.is_empty() { String::new() } else { format!("{}\n", lines.join("\n")) } } } #[cfg(test)] mod tests { use std::ffi::OsStr; use indoc::indoc; use temp_env::with_vars; use tempfile::tempdir; use super::*; #[test] fn pixi_environment_is_treated_as_child() { let tempdir = tempdir().unwrap(); let prefix = tempdir.path(); let conda_meta = prefix.join("conda-meta"); fs::create_dir_all(&conda_meta).unwrap(); fs::write(conda_meta.join("pixi"), []).unwrap(); let vars = [ (EnvVars::CONDA_ROOT, None), (EnvVars::CONDA_PREFIX, Some(prefix.as_os_str())), (EnvVars::CONDA_DEFAULT_ENV, Some(OsStr::new("example"))), ]; with_vars(vars, || { assert_eq!( CondaEnvironmentKind::from_prefix_path(prefix), CondaEnvironmentKind::Child ); }); } #[test] fn test_set_existing_key() { let content = indoc! {" home = /path/to/python version = 3.8.0 include-system-site-packages = false "}; let result = PyVenvConfiguration::set(content, "version", "3.9.0"); assert_eq!( result, indoc! {" home = /path/to/python version = 3.9.0 include-system-site-packages = false "} ); } #[test] fn test_set_new_key() { let content = indoc! {" home = /path/to/python version = 3.8.0 "}; let result = PyVenvConfiguration::set(content, "include-system-site-packages", "false"); assert_eq!( result, indoc! {" home = /path/to/python version = 3.8.0 include-system-site-packages = false "} ); } #[test] fn test_set_key_no_spaces() { let content = indoc! {" home=/path/to/python version=3.8.0 "}; let result = PyVenvConfiguration::set(content, "include-system-site-packages", "false"); assert_eq!( result, indoc! {" home=/path/to/python version=3.8.0 include-system-site-packages = false "} ); } #[test] fn test_set_key_prefix() { let content = indoc! {" home = /path/to/python home_dir = /other/path "}; let result = PyVenvConfiguration::set(content, "home", "new/path"); assert_eq!( result, indoc! {" home = new/path home_dir = /other/path "} ); } #[test] fn test_set_empty_content() { let content = ""; let result = PyVenvConfiguration::set(content, "version", "3.9.0"); assert_eq!( result, indoc! {" version = 3.9.0 "} ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/sysconfig/cursor.rs
crates/uv-python/src/sysconfig/cursor.rs
#![allow(dead_code)] use std::str::Chars; pub(super) const EOF_CHAR: char = '\0'; /// A cursor represents a pointer in the source code. /// /// Based on [`rustc`'s `Cursor`](https://github.com/rust-lang/rust/blob/d1b7355d3d7b4ead564dbecb1d240fcc74fff21b/compiler/rustc_lexer/src/cursor.rs) #[derive(Clone, Debug)] pub(super) struct Cursor<'src> { /// An iterator over the [`char`]'s of the source code. chars: Chars<'src>, /// Stores the previous character for debug assertions. #[cfg(debug_assertions)] prev_char: char, } impl<'src> Cursor<'src> { pub(super) fn new(source: &'src str) -> Self { Self { chars: source.chars(), #[cfg(debug_assertions)] prev_char: EOF_CHAR, } } /// Returns the previous character. Useful for debug assertions. #[cfg(debug_assertions)] pub(super) const fn previous(&self) -> char { self.prev_char } /// Peeks the next character from the input stream without consuming it. /// Returns [`EOF_CHAR`] if the position is past the end of the file. pub(super) fn first(&self) -> char { self.chars.clone().next().unwrap_or(EOF_CHAR) } /// Peeks the second character from the input stream without consuming it. /// Returns [`EOF_CHAR`] if the position is past the end of the file. pub(super) fn second(&self) -> char { let mut chars = self.chars.clone(); chars.next(); chars.next().unwrap_or(EOF_CHAR) } /// Returns the remaining text to lex. /// /// Use [`Cursor::text_len`] to get the length of the remaining text. pub(super) fn rest(&self) -> &'src str { self.chars.as_str() } /// Returns `true` if the cursor is at the end of file. pub(super) fn is_eof(&self) -> bool { self.chars.as_str().is_empty() } /// Moves the cursor to the next character, returning the previous character. /// Returns [`None`] if there is no next character. pub(super) fn bump(&mut self) -> Option<char> { let prev = self.chars.next()?; #[cfg(debug_assertions)] { self.prev_char = prev; } Some(prev) } pub(super) fn eat_char(&mut self, c: char) -> bool { if self.first() == c { self.bump(); true } else { false } } pub(super) fn eat_char2(&mut self, c1: char, c2: char) -> bool { let mut chars = self.chars.clone(); if chars.next() == Some(c1) && chars.next() == Some(c2) { self.bump(); self.bump(); true } else { false } } pub(super) fn eat_char3(&mut self, c1: char, c2: char, c3: char) -> bool { let mut chars = self.chars.clone(); if chars.next() == Some(c1) && chars.next() == Some(c2) && chars.next() == Some(c3) { self.bump(); self.bump(); self.bump(); true } else { false } } pub(super) fn eat_if<F>(&mut self, mut predicate: F) -> Option<char> where F: FnMut(char) -> bool, { if predicate(self.first()) && !self.is_eof() { self.bump() } else { None } } /// Eats symbols while predicate returns true or until the end of file is reached. #[inline] pub(super) fn eat_while(&mut self, mut predicate: impl FnMut(char) -> bool) { // It was tried making optimized version of this for eg. line comments, but // LLVM can inline all of this and compile it down to fast iteration over bytes. while predicate(self.first()) && !self.is_eof() { self.bump(); } } /// Skips the next `count` bytes. /// /// ## Panics /// - If `count` is larger than the remaining bytes in the input stream. /// - If `count` indexes into a multi-byte character. pub(super) fn skip_bytes(&mut self, count: usize) { #[cfg(debug_assertions)] { self.prev_char = self.chars.as_str()[..count] .chars() .next_back() .unwrap_or('\0'); } self.chars = self.chars.as_str()[count..].chars(); } /// Skips to the end of the input stream. pub(super) fn skip_to_end(&mut self) { self.chars = "".chars(); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/sysconfig/replacements.rs
crates/uv-python/src/sysconfig/replacements.rs
/// Replacement mode for sysconfig values. #[derive(Debug)] pub(crate) enum ReplacementMode { Partial { from: String }, Full, } /// A replacement entry to patch in sysconfig data. #[derive(Debug)] pub(crate) struct ReplacementEntry { pub(crate) mode: ReplacementMode, pub(crate) to: String, } impl ReplacementEntry { /// Patches a sysconfig value either partially (replacing a specific word) or fully. pub(crate) fn patch(&self, entry: &str) -> String { match &self.mode { ReplacementMode::Partial { from } => entry .split_whitespace() .map(|word| if word == from { &self.to } else { word }) .collect::<Vec<_>>() .join(" "), ReplacementMode::Full => self.to.clone(), } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/sysconfig/parser.rs
crates/uv-python/src/sysconfig/parser.rs
use std::collections::BTreeMap; use std::str::FromStr; use serde::Serialize; use serde_json::ser::PrettyFormatter; use crate::sysconfig::cursor::Cursor; /// A value in the [`SysconfigData`] map. /// /// Values are assumed to be either strings or integers. #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)] #[serde(untagged)] pub(super) enum Value { String(String), Int(i32), } /// The data extracted from a `_sysconfigdata_` file. #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize)] pub(super) struct SysconfigData(BTreeMap<String, Value>); impl SysconfigData { /// Returns an iterator over the key-value pairs in the map. pub(super) fn iter_mut(&mut self) -> std::collections::btree_map::IterMut<'_, String, Value> { self.0.iter_mut() } /// Inserts a key-value pair into the map. pub(super) fn insert(&mut self, key: String, value: Value) -> Option<Value> { self.0.insert(key, value) } /// Formats the `sysconfig` data as a pretty-printed string. pub(super) fn to_string_pretty(&self) -> Result<String, serde_json::Error> { let output = { let mut buf = Vec::new(); let mut serializer = serde_json::Serializer::with_formatter( &mut buf, PrettyFormatter::with_indent(b" "), ); self.0.serialize(&mut serializer)?; String::from_utf8(buf).unwrap() }; Ok(format!( "# system configuration generated and used by the sysconfig module\nbuild_time_vars = {output}\n", )) } } impl std::fmt::Display for SysconfigData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let output = { let mut buf = Vec::new(); let mut serializer = serde_json::Serializer::new(&mut buf); self.0.serialize(&mut serializer).unwrap(); String::from_utf8(buf).unwrap() }; write!(f, "{output}") } } impl FromIterator<(String, Value)> for SysconfigData { fn from_iter<T: IntoIterator<Item = (String, Value)>>(iter: T) -> Self { Self(iter.into_iter().collect()) } } /// Parse the `_sysconfigdata_` file (e.g., `{real_prefix}/lib/python3.12/_sysconfigdata__darwin_darwin.py"` /// on macOS). /// /// `_sysconfigdata_` is structured as follows: /// /// 1. A comment on the first line (e.g., `# system configuration generated and used by the sysconfig module`). /// 2. An assignment to `build_time_vars` (e.g., `build_time_vars = { ... }`). /// /// The right-hand side of the assignment is a JSON object. The keys are strings, and the values /// are strings or numbers. impl FromStr for SysconfigData { type Err = Error; fn from_str(s: &str) -> Result<Self, Self::Err> { // Read the first line of the file. let Some(s) = s.strip_prefix("# system configuration generated and used by the sysconfig module\n") else { return Err(Error::MissingHeader); }; // Read the assignment to `build_time_vars`. let Some(s) = s.strip_prefix("build_time_vars") else { return Err(Error::MissingAssignment); }; let mut cursor = Cursor::new(s); cursor.eat_while(is_python_whitespace); if !cursor.eat_char('=') { return Err(Error::MissingAssignment); } cursor.eat_while(is_python_whitespace); if !cursor.eat_char('{') { return Err(Error::MissingOpenBrace); } let mut map = BTreeMap::new(); loop { let Some(next) = cursor.bump() else { return Err(Error::UnexpectedEof); }; match next { '\'' | '"' => { // Parse key. let key = parse_string(&mut cursor, next)?; cursor.eat_while(is_python_whitespace); cursor.eat_char(':'); cursor.eat_while(is_python_whitespace); // Parse value let value = match cursor.first() { '\'' | '"' => Value::String(parse_concatenated_string(&mut cursor)?), '-' => { cursor.bump(); Value::Int(-parse_int(&mut cursor)?) } c if c.is_ascii_digit() => Value::Int(parse_int(&mut cursor)?), c => return Err(Error::UnexpectedCharacter(c)), }; // Insert into map. map.insert(key, value); // Skip optional comma. cursor.eat_while(is_python_whitespace); cursor.eat_char(','); cursor.eat_while(is_python_whitespace); } // Skip whitespace. ' ' | '\n' | '\r' | '\t' => {} // When we see a closing brace, we're done. '}' => { break; } c => return Err(Error::UnexpectedCharacter(c)), } } Ok(Self(map)) } } /// Parse a Python string literal. /// /// Expects the previous character to be the opening quote character. fn parse_string(cursor: &mut Cursor, quote: char) -> Result<String, Error> { let mut result = String::new(); loop { let Some(c) = cursor.bump() else { return Err(Error::UnexpectedEof); }; match c { '\\' => { // Treat the next character as a literal. // // See: https://github.com/astral-sh/ruff/blob/d47fba1e4aeeb18085900dfbbcd187e90d536913/crates/ruff_python_parser/src/string.rs#L194 let Some(c) = cursor.bump() else { return Err(Error::UnexpectedEof); }; result.push(match c { '\\' => '\\', '\'' => '\'', '\"' => '"', _ => { return Err(Error::UnrecognizedEscape(c)); } }); } // Consume closing quote. c if c == quote => { break; } c => { result.push(c); } } } Ok(result) } /// Parse a Python string, which may be a concatenation of multiple string literals. /// /// Expects the cursor to start at an opening quote character. fn parse_concatenated_string(cursor: &mut Cursor) -> Result<String, Error> { let mut result = String::new(); loop { let Some(c) = cursor.bump() else { return Err(Error::UnexpectedEof); }; match c { '\'' | '"' => { // Parse a new string fragment and append it. result.push_str(&parse_string(cursor, c)?); } c if is_python_whitespace(c) => { // Skip whitespace between fragments } c => return Err(Error::UnexpectedCharacter(c)), } // Lookahead to the end of the string. if matches!(cursor.first(), ',' | '}') { break; } } Ok(result) } /// Parse an integer literal. /// /// Expects the cursor to start at the first digit of the integer. fn parse_int(cursor: &mut Cursor) -> Result<i32, std::num::ParseIntError> { let mut result = String::new(); loop { let c = cursor.first(); if !c.is_ascii_digit() { break; } result.push(c); cursor.bump(); } result.parse() } /// Returns `true` for [whitespace](https://docs.python.org/3/reference/lexical_analysis.html#whitespace-between-tokens) /// characters. const fn is_python_whitespace(c: char) -> bool { matches!( c, // Space, tab, form-feed, newline, or carriage return ' ' | '\t' | '\x0C' | '\n' | '\r' ) } #[derive(thiserror::Error, Debug)] pub enum Error { #[error("Missing opening brace")] MissingOpenBrace, #[error("Unexpected character: {0}")] UnexpectedCharacter(char), #[error("Unexpected end of file")] UnexpectedEof, #[error("Unrecognized escape sequence: {0}")] UnrecognizedEscape(char), #[error("Failed to parse integer")] ParseInt(#[from] std::num::ParseIntError), #[error("`_sysconfigdata_` is missing a header comment")] MissingHeader, #[error("`_sysconfigdata_` is missing an assignment to `build_time_vars`")] MissingAssignment, } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_string() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1", "key2": 42, "key3": "multi-part" " string" } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1", "key2": 42, "key3": "multi-part string" } "###); } #[test] fn test_parse_backslash() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1\"value2\"value3", "key2": "value1\\value2\\value3", "key3": "value1\\\"value2\\\"value3", "key4": "value1\\\\value2\\\\value3", } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1\"value2\"value3", "key2": "value1\\value2\\value3", "key3": "value1\\\"value2\\\"value3", "key4": "value1\\\\value2\\\\value3" } "###); } #[test] fn test_parse_trailing_backslash() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1\\value2\\value3\", } "# ); let result = input.parse::<SysconfigData>(); assert!(matches!(result, Err(Error::UnexpectedEof))); } #[test] fn test_parse_unrecognized_escape() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1\value2", } "# ); let result = input.parse::<SysconfigData>(); assert!(matches!(result, Err(Error::UnrecognizedEscape('v')))); } #[test] fn test_parse_trailing_comma() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1", "key2": 42, "key3": "multi-part" " string", } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value1", "key2": 42, "key3": "multi-part string" } "###); } #[test] fn test_parse_integer_values() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": 12345, "key2": -15 } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": 12345, "key2": -15 } "###); } #[test] fn test_parse_escaped_quotes() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value with \"escaped quotes\"", "key2": 'single-quoted \'escaped\'' } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "value with \"escaped quotes\"", "key2": "single-quoted 'escaped'" } "###); } #[test] fn test_parse_concatenated_strings() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "multi-" "line " "string" } "# ); let result = input.parse::<SysconfigData>().expect("Parsing failed"); let snapshot = result.to_string_pretty().unwrap(); insta::assert_snapshot!(snapshot, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": "multi-line string" } "###); } #[test] fn test_missing_header_error() { let input = indoc::indoc!( r#" build_time_vars = { "key1": "value1" } "# ); let result = input.parse::<SysconfigData>(); assert!(matches!(result, Err(Error::MissingHeader))); } #[test] fn test_missing_assignment_error() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module { "key1": "value1" } "# ); let result = input.parse::<SysconfigData>(); assert!(matches!(result, Err(Error::MissingAssignment))); } #[test] fn test_unexpected_character_error() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": &123 } "# ); let result = input.parse::<SysconfigData>(); assert!( result.is_err(), "Expected parsing to fail due to unexpected character" ); } #[test] fn test_unexpected_eof() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": 123 "# ); let result = input.parse::<SysconfigData>(); assert!( result.is_err(), "Expected parsing to fail due to unexpected character" ); } #[test] fn test_unexpected_comma() { let input = indoc::indoc!( r#" # system configuration generated and used by the sysconfig module build_time_vars = { "key1": 123,, } "# ); let result = input.parse::<SysconfigData>(); assert!( result.is_err(), "Expected parsing to fail due to unexpected character" ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/sysconfig/generated_mappings.rs
crates/uv-python/src/sysconfig/generated_mappings.rs
//! DO NOT EDIT //! //! Generated with `cargo run dev generate-sysconfig-metadata` //! Targets from <https://github.com/astral-sh/python-build-standalone/blob/20251217/cpython-unix/targets.yml> //! #![allow(clippy::all)] #![cfg_attr(any(), rustfmt::skip)] use std::collections::BTreeMap; use std::sync::LazyLock; use crate::sysconfig::replacements::{ReplacementEntry, ReplacementMode}; /// Mapping for sysconfig keys to lookup and replace with the appropriate entry. pub(crate) static DEFAULT_VARIABLE_UPDATES: LazyLock<BTreeMap<String, Vec<ReplacementEntry>>> = LazyLock::new(|| { BTreeMap::from_iter([ ("BLDSHARED".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "musl-clang".to_string() }, to: "cc".to_string() }, ]), ("CC".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "musl-clang".to_string() }, to: "cc".to_string() }, ]), ("CXX".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang++".to_string() }, to: "c++".to_string() }, ]), ("LDCXXSHARED".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-g++".to_string() }, to: "c++".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang++".to_string() }, to: "c++".to_string() }, ]), ("LDSHARED".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "musl-clang".to_string() }, to: "cc".to_string() }, ]), ("LINKCC".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabi-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/arm-linux-gnueabihf-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/loongarch64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mips-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/mipsel-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/powerpc64le-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/riscv64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/s390x-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "/usr/bin/x86_64-linux-gnu-gcc".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "clang".to_string() }, to: "cc".to_string() }, ReplacementEntry { mode: ReplacementMode::Partial { from: "musl-clang".to_string() }, to: "cc".to_string() }, ]), ("AR".to_string(), vec![ ReplacementEntry { mode: ReplacementMode::Full, to: "ar".to_string(), }, ]), ]) });
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-python/src/sysconfig/mod.rs
crates/uv-python/src/sysconfig/mod.rs
//! Patch `sysconfig` data in a Python installation. //! //! Inspired by: <https://github.com/bluss/sysconfigpatcher/blob/c1ebf8ab9274dcde255484d93ce0f1fd1f76a248/src/sysconfigpatcher.py#L137C1-L140C100>, //! available under the MIT license: //! //! ```text //! Copyright 2024 Ulrik Sverdrup "bluss" //! //! Permission is hereby granted, free of charge, to any person obtaining a copy of //! this software and associated documentation files (the "Software"), to deal in //! the Software without restriction, including without limitation the rights to //! use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //! the Software, and to permit persons to whom the Software is furnished to do so, //! subject to the following conditions: //! //! The above copyright notice and this permission notice shall be included in all //! copies or substantial portions of the Software. //! //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS //! FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //! COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER //! IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN //! CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //! ``` use std::borrow::Cow; use std::io::Write; use std::path::{Path, PathBuf}; use std::str::FromStr; use itertools::{Either, Itertools}; use tracing::trace; use crate::sysconfig::generated_mappings::DEFAULT_VARIABLE_UPDATES; use crate::sysconfig::parser::{Error as ParseError, SysconfigData, Value}; mod cursor; mod generated_mappings; mod parser; mod replacements; /// Update the `sysconfig` data in a Python installation. pub(crate) fn update_sysconfig( install_root: &Path, major: u8, minor: u8, suffix: &str, ) -> Result<(), Error> { // Find the `_sysconfigdata_` file in the Python installation. let real_prefix = std::path::absolute(install_root)?; let sysconfigdata = find_sysconfigdata(&real_prefix, major, minor, suffix)?; trace!( "Discovered `sysconfig` data at: {}", sysconfigdata.display() ); // Update the `_sysconfigdata_` file in-memory. let contents = fs_err::read_to_string(&sysconfigdata)?; let data = SysconfigData::from_str(&contents)?; let data = patch_sysconfigdata(data, &real_prefix); let contents = data.to_string_pretty()?; // Write the updated `_sysconfigdata_` file. let mut file = fs_err::OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&sysconfigdata)?; file.write_all(contents.as_bytes())?; file.sync_data()?; // Find the `pkgconfig` files in the Python installation. for pkgconfig in find_pkgconfigs(&real_prefix)? { let pkgconfig = pkgconfig?; trace!("Discovered `pkgconfig` data at: {}", pkgconfig.display()); // Update the `pkgconfig` file in-memory. let contents = fs_err::read_to_string(&pkgconfig)?; if let Some(new_contents) = patch_pkgconfig(&contents) { // Write the updated `pkgconfig` file. let mut file = fs_err::OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&pkgconfig)?; file.write_all(new_contents.as_bytes())?; file.sync_data()?; } } Ok(()) } /// Find the `_sysconfigdata_` file in a Python installation. /// /// For example, on macOS, returns `{real_prefix}/lib/python3.12/_sysconfigdata__darwin_darwin.py"`. fn find_sysconfigdata( real_prefix: &Path, major: u8, minor: u8, suffix: &str, ) -> Result<PathBuf, Error> { // Find the `lib` directory in the Python installation. let lib = real_prefix .join("lib") .join(format!("python{major}.{minor}{suffix}")); if !lib.exists() { return Err(Error::MissingLib(lib)); } // Probe the `lib` directory for `_sysconfigdata_`. for entry in lib.read_dir()? { let entry = entry?; if entry.path().extension().is_none_or(|ext| ext != "py") { continue; } if !entry .path() .file_stem() .and_then(|stem| stem.to_str()) .is_some_and(|stem| stem.starts_with("_sysconfigdata_")) { continue; } let metadata = entry.metadata()?; if metadata.is_symlink() { continue; } if metadata.is_file() { return Ok(entry.path()); } } Err(Error::MissingSysconfigdata) } /// Patch the given `_sysconfigdata_` contents. fn patch_sysconfigdata(mut data: SysconfigData, real_prefix: &Path) -> SysconfigData { /// Update the `/install` prefix in a whitespace-separated string. fn update_prefix(s: &str, real_prefix: &Path) -> String { s.split_whitespace() .map(|part| { if let Some(rest) = part.strip_prefix("/install") { if rest.is_empty() { real_prefix.display().to_string() } else { real_prefix.join(&rest[1..]).display().to_string() } } else { part.to_string() } }) .collect::<Vec<_>>() .join(" ") } /// Remove any references to `-isysroot` in a whitespace-separated string. fn remove_isysroot(s: &str) -> String { // If we see `-isysroot`, drop it and the next part. let mut parts = s.split_whitespace().peekable(); let mut result = Vec::with_capacity(parts.size_hint().0); while let Some(part) = parts.next() { if part == "-isysroot" { parts.next(); } else { result.push(part); } } result.join(" ") } // Patch each value, as needed. let mut count = 0; for (key, value) in data.iter_mut() { let Value::String(value) = value else { continue; }; let patched = update_prefix(value, real_prefix); let mut patched = remove_isysroot(&patched); if let Some(replacement_entries) = DEFAULT_VARIABLE_UPDATES.get(key) { for replacement_entry in replacement_entries { patched = replacement_entry.patch(&patched); } } if *value != patched { trace!("Updated `{key}` from `{value}` to `{patched}`"); count += 1; *value = patched; } } match count { 0 => trace!("No updates required"), 1 => trace!("Updated 1 value"), n => trace!("Updated {n} values"), } // Mark the Python installation as standalone. data.insert("PYTHON_BUILD_STANDALONE".to_string(), Value::Int(1)); data } /// Find the location of all `pkg-config` files in a Python installation. /// /// Specifically, searches for files under `lib/pkgconfig` with the `.pc` extension. fn find_pkgconfigs( install_root: &Path, ) -> Result<impl Iterator<Item = Result<PathBuf, std::io::Error>>, std::io::Error> { let pkgconfig = install_root.join("lib").join("pkgconfig"); let read_dir = match pkgconfig.read_dir() { Ok(read_dir) => read_dir, Err(err) if err.kind() == std::io::ErrorKind::NotFound => { return Ok(Either::Left(std::iter::empty())); } Err(err) => return Err(err), }; Ok(Either::Right( read_dir .filter_ok(|entry| entry.path().extension().is_some_and(|ext| ext == "pc")) .filter_ok(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_file())) .map_ok(|entry| entry.path()), )) } /// Patch the given `pkgconfig` contents. /// /// Returns the updated contents, if an update is needed. fn patch_pkgconfig(contents: &str) -> Option<String> { let mut changed = false; let new_contents = contents .lines() .map(|line| { // python-build-standalone is compiled with a prefix of // /install. Replace lines like `prefix=/install` with // `prefix=${pcfiledir}/../..` (since the .pc file is in // lib/pkgconfig/). Newer versions of python-build-standalone // already have this change. let Some((prefix, suffix)) = line.split_once('=') else { return Cow::Borrowed(line); }; // The content before the `=` must be an ASCII alphabetic string. if !prefix.chars().all(|c| c.is_ascii_alphabetic()) { return Cow::Borrowed(line); } // The content after the `=` must be equal to the expected prefix. if suffix != "/install" { return Cow::Borrowed(line); } changed = true; Cow::Owned(format!("{prefix}=${{pcfiledir}}/../..")) }) .join("\n"); if changed { Some(new_contents) } else { None } } #[derive(thiserror::Error, Debug)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[error("Python installation is missing a `lib` directory at: {0}")] MissingLib(PathBuf), #[error("Python installation is missing a `_sysconfigdata_` file")] MissingSysconfigdata, #[error(transparent)] Parse(#[from] ParseError), #[error(transparent)] Json(#[from] serde_json::Error), } #[cfg(test)] #[cfg(unix)] mod tests { use super::*; use indoc::indoc; #[test] fn update_real_prefix() -> Result<(), Error> { let sysconfigdata = [ ("BASEMODLIBS", ""), ("BINDIR", "/install/bin"), ("BINLIBDEST", "/install/lib/python3.10"), ("BLDLIBRARY", "-L. -lpython3.10"), ("BUILDPYTHON", "python.exe"), ("prefix", "/install/prefix"), ("exec_prefix", "/install/exec_prefix"), ("base", "/install/base"), ] .into_iter() .map(|(k, v)| (k.to_string(), Value::String(v.to_string()))) .collect::<SysconfigData>(); let real_prefix = Path::new("/real/prefix"); let data = patch_sysconfigdata(sysconfigdata, real_prefix); insta::assert_snapshot!(data.to_string_pretty()?, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "BASEMODLIBS": "", "BINDIR": "/real/prefix/bin", "BINLIBDEST": "/real/prefix/lib/python3.10", "BLDLIBRARY": "-L. -lpython3.10", "BUILDPYTHON": "python.exe", "PYTHON_BUILD_STANDALONE": 1, "base": "/real/prefix/base", "exec_prefix": "/real/prefix/exec_prefix", "prefix": "/real/prefix/prefix" } "###); Ok(()) } #[test] fn test_replacements() -> Result<(), Error> { let sysconfigdata = [ ("CC", "clang -pthread"), ("CXX", "clang++ -pthread"), ("AR", "/tools/llvm/bin/llvm-ar"), ] .into_iter() .map(|(k, v)| (k.to_string(), Value::String(v.to_string()))) .collect::<SysconfigData>(); let real_prefix = Path::new("/real/prefix"); let data = patch_sysconfigdata(sysconfigdata, real_prefix); insta::assert_snapshot!(data.to_string_pretty()?, @r##" # system configuration generated and used by the sysconfig module build_time_vars = { "AR": "ar", "CC": "cc -pthread", "CXX": "c++ -pthread", "PYTHON_BUILD_STANDALONE": 1 } "##); // Cross-compiles use GNU let sysconfigdata = [ ("CC", "/usr/bin/riscv64-linux-gnu-gcc"), ("CXX", "/usr/bin/x86_64-linux-gnu-g++"), ] .into_iter() .map(|(k, v)| (k.to_string(), Value::String(v.to_string()))) .collect::<SysconfigData>(); let real_prefix = Path::new("/real/prefix"); let data = patch_sysconfigdata(sysconfigdata, real_prefix); insta::assert_snapshot!(data.to_string_pretty()?, @r##" # system configuration generated and used by the sysconfig module build_time_vars = { "CC": "cc", "CXX": "c++", "PYTHON_BUILD_STANDALONE": 1 } "##); Ok(()) } #[test] fn remove_isysroot() -> Result<(), Error> { let sysconfigdata = [ ("BLDSHARED", "clang -bundle -undefined dynamic_lookup -arch arm64 -isysroot /Applications/MacOSX14.2.sdk"), ] .into_iter() .map(|(k, v)| (k.to_string(), Value::String(v.to_string()))) .collect::<SysconfigData>(); let real_prefix = Path::new("/real/prefix"); let data = patch_sysconfigdata(sysconfigdata, real_prefix); insta::assert_snapshot!(data.to_string_pretty()?, @r###" # system configuration generated and used by the sysconfig module build_time_vars = { "BLDSHARED": "cc -bundle -undefined dynamic_lookup -arch arm64", "PYTHON_BUILD_STANDALONE": 1 } "###); Ok(()) } #[test] fn update_pkgconfig() { let pkgconfig = indoc! { r" # See: man pkg-config prefix=/install exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: Python Description: Build a C extension for Python Requires: Version: 3.10 Libs.private: -ldl -framework CoreFoundation Libs: Cflags: -I${includedir}/python3.10 " }; let pkgconfig = patch_pkgconfig(pkgconfig).unwrap(); insta::assert_snapshot!(pkgconfig, @r###" # See: man pkg-config prefix=${pcfiledir}/../.. exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: Python Description: Build a C extension for Python Requires: Version: 3.10 Libs.private: -ldl -framework CoreFoundation Libs: Cflags: -I${includedir}/python3.10 "###); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-dispatch/src/lib.rs
crates/uv-dispatch/src/lib.rs
//! Avoid cyclic crate dependencies between [resolver][`uv_resolver`], //! [installer][`uv_installer`] and [build][`uv_build`] through [`BuildDispatch`] //! implementing [`BuildContext`]. use std::ffi::{OsStr, OsString}; use std::path::Path; use anyhow::{Context, Result}; use futures::FutureExt; use itertools::Itertools; use rustc_hash::FxHashMap; use thiserror::Error; use tracing::{debug, instrument, trace}; use uv_build_backend::check_direct_build; use uv_build_frontend::{SourceBuild, SourceBuildContext}; use uv_cache::Cache; use uv_client::RegistryClient; use uv_configuration::{ BuildKind, BuildOptions, Constraints, IndexStrategy, Reinstall, SourceStrategy, }; use uv_configuration::{BuildOutput, Concurrency}; use uv_distribution::DistributionDatabase; use uv_distribution_filename::DistFilename; use uv_distribution_types::{ CachedDist, ConfigSettings, DependencyMetadata, ExtraBuildRequires, ExtraBuildVariables, Identifier, IndexCapabilities, IndexLocations, IsBuildBackendError, Name, PackageConfigSettings, Requirement, Resolution, SourceDist, VersionOrUrlRef, }; use uv_git::GitResolver; use uv_installer::{InstallationStrategy, Installer, Plan, Planner, Preparer, SitePackages}; use uv_preview::Preview; use uv_pypi_types::Conflicts; use uv_python::{Interpreter, PythonEnvironment}; use uv_resolver::{ ExcludeNewer, FlatIndex, Flexibility, InMemoryIndex, Manifest, OptionsBuilder, PythonRequirement, Resolver, ResolverEnvironment, }; use uv_types::{ AnyErrorBuild, BuildArena, BuildContext, BuildIsolation, BuildStack, EmptyInstalledPackages, HashStrategy, InFlight, }; use uv_workspace::WorkspaceCache; #[derive(Debug, Error)] pub enum BuildDispatchError { #[error(transparent)] BuildFrontend(#[from] AnyErrorBuild), #[error(transparent)] Tags(#[from] uv_platform_tags::TagsError), #[error(transparent)] Resolve(#[from] uv_resolver::ResolveError), #[error(transparent)] Join(#[from] tokio::task::JoinError), #[error(transparent)] Anyhow(#[from] anyhow::Error), #[error(transparent)] Prepare(#[from] uv_installer::PrepareError), } impl IsBuildBackendError for BuildDispatchError { fn is_build_backend_error(&self) -> bool { match self { Self::Tags(_) | Self::Resolve(_) | Self::Join(_) | Self::Anyhow(_) | Self::Prepare(_) => false, Self::BuildFrontend(err) => err.is_build_backend_error(), } } } /// The main implementation of [`BuildContext`], used by the CLI, see [`BuildContext`] /// documentation. pub struct BuildDispatch<'a> { client: &'a RegistryClient, cache: &'a Cache, constraints: &'a Constraints, interpreter: &'a Interpreter, index_locations: &'a IndexLocations, index_strategy: IndexStrategy, flat_index: &'a FlatIndex, shared_state: SharedState, dependency_metadata: &'a DependencyMetadata, build_isolation: BuildIsolation<'a>, extra_build_requires: &'a ExtraBuildRequires, extra_build_variables: &'a ExtraBuildVariables, link_mode: uv_install_wheel::LinkMode, build_options: &'a BuildOptions, config_settings: &'a ConfigSettings, config_settings_package: &'a PackageConfigSettings, hasher: &'a HashStrategy, exclude_newer: ExcludeNewer, source_build_context: SourceBuildContext, build_extra_env_vars: FxHashMap<OsString, OsString>, sources: SourceStrategy, workspace_cache: WorkspaceCache, concurrency: Concurrency, preview: Preview, } impl<'a> BuildDispatch<'a> { pub fn new( client: &'a RegistryClient, cache: &'a Cache, constraints: &'a Constraints, interpreter: &'a Interpreter, index_locations: &'a IndexLocations, flat_index: &'a FlatIndex, dependency_metadata: &'a DependencyMetadata, shared_state: SharedState, index_strategy: IndexStrategy, config_settings: &'a ConfigSettings, config_settings_package: &'a PackageConfigSettings, build_isolation: BuildIsolation<'a>, extra_build_requires: &'a ExtraBuildRequires, extra_build_variables: &'a ExtraBuildVariables, link_mode: uv_install_wheel::LinkMode, build_options: &'a BuildOptions, hasher: &'a HashStrategy, exclude_newer: ExcludeNewer, sources: SourceStrategy, workspace_cache: WorkspaceCache, concurrency: Concurrency, preview: Preview, ) -> Self { Self { client, cache, constraints, interpreter, index_locations, flat_index, shared_state, dependency_metadata, index_strategy, config_settings, config_settings_package, build_isolation, extra_build_requires, extra_build_variables, link_mode, build_options, hasher, exclude_newer, source_build_context: SourceBuildContext::default(), build_extra_env_vars: FxHashMap::default(), sources, workspace_cache, concurrency, preview, } } /// Set the environment variables to be used when building a source distribution. #[must_use] pub fn with_build_extra_env_vars<I, K, V>(mut self, sdist_build_env_variables: I) -> Self where I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>, { self.build_extra_env_vars = sdist_build_env_variables .into_iter() .map(|(key, value)| (key.as_ref().to_owned(), value.as_ref().to_owned())) .collect(); self } } #[allow(refining_impl_trait)] impl BuildContext for BuildDispatch<'_> { type SourceDistBuilder = SourceBuild; async fn interpreter(&self) -> &Interpreter { self.interpreter } fn cache(&self) -> &Cache { self.cache } fn git(&self) -> &GitResolver { &self.shared_state.git } fn build_arena(&self) -> &BuildArena<SourceBuild> { &self.shared_state.build_arena } fn capabilities(&self) -> &IndexCapabilities { &self.shared_state.capabilities } fn dependency_metadata(&self) -> &DependencyMetadata { self.dependency_metadata } fn build_options(&self) -> &BuildOptions { self.build_options } fn build_isolation(&self) -> BuildIsolation<'_> { self.build_isolation } fn config_settings(&self) -> &ConfigSettings { self.config_settings } fn config_settings_package(&self) -> &PackageConfigSettings { self.config_settings_package } fn sources(&self) -> SourceStrategy { self.sources } fn locations(&self) -> &IndexLocations { self.index_locations } fn workspace_cache(&self) -> &WorkspaceCache { &self.workspace_cache } fn extra_build_requires(&self) -> &ExtraBuildRequires { self.extra_build_requires } fn extra_build_variables(&self) -> &ExtraBuildVariables { self.extra_build_variables } async fn resolve<'data>( &'data self, requirements: &'data [Requirement], build_stack: &'data BuildStack, ) -> Result<Resolution, BuildDispatchError> { let python_requirement = PythonRequirement::from_interpreter(self.interpreter); let marker_env = self.interpreter.resolver_marker_environment(); let tags = self.interpreter.tags()?; let resolver = Resolver::new( Manifest::simple(requirements.to_vec()).with_constraints(self.constraints.clone()), OptionsBuilder::new() .exclude_newer(self.exclude_newer.clone()) .index_strategy(self.index_strategy) .build_options(self.build_options.clone()) .flexibility(Flexibility::Fixed) .build(), &python_requirement, ResolverEnvironment::specific(marker_env), self.interpreter.markers(), // Conflicting groups only make sense when doing universal resolution. Conflicts::empty(), Some(tags), self.flat_index, &self.shared_state.index, self.hasher, self, EmptyInstalledPackages, DistributionDatabase::new(self.client, self, self.concurrency.downloads) .with_build_stack(build_stack), )?; let resolution = Resolution::from(resolver.resolve().await.with_context(|| { format!( "No solution found when resolving: {}", requirements .iter() .map(|requirement| format!("`{requirement}`")) .join(", ") ) })?); Ok(resolution) } #[instrument( skip(self, resolution, venv), fields( resolution = resolution.distributions().map(ToString::to_string).join(", "), venv = ?venv.root() ) )] async fn install<'data>( &'data self, resolution: &'data Resolution, venv: &'data PythonEnvironment, build_stack: &'data BuildStack, ) -> Result<Vec<CachedDist>, BuildDispatchError> { debug!( "Installing in {} in {}", resolution .distributions() .map(ToString::to_string) .join(", "), venv.root().display(), ); // Determine the current environment markers. let tags = self.interpreter.tags()?; // Determine the set of installed packages. let site_packages = SitePackages::from_environment(venv)?; let Plan { cached, remote, reinstalls, extraneous: _, } = Planner::new(resolution).build( site_packages, InstallationStrategy::Permissive, &Reinstall::default(), self.build_options, self.hasher, self.index_locations, self.config_settings, self.config_settings_package, self.extra_build_requires(), self.extra_build_variables, self.cache(), venv, tags, )?; // Nothing to do. if remote.is_empty() && cached.is_empty() && reinstalls.is_empty() { debug!("No build requirements to install for build"); return Ok(vec![]); } // Verify that none of the missing distributions are already in the build stack. for dist in &remote { let id = dist.distribution_id(); if build_stack.contains(&id) { return Err(BuildDispatchError::BuildFrontend( uv_build_frontend::Error::CyclicBuildDependency(dist.name().clone()).into(), )); } } // Download any missing distributions. let wheels = if remote.is_empty() { vec![] } else { let preparer = Preparer::new( self.cache, tags, self.hasher, self.build_options, DistributionDatabase::new(self.client, self, self.concurrency.downloads) .with_build_stack(build_stack), ); debug!( "Downloading and building requirement{} for build: {}", if remote.len() == 1 { "" } else { "s" }, remote.iter().map(ToString::to_string).join(", ") ); preparer .prepare(remote, &self.shared_state.in_flight, resolution) .await? }; // Remove any unnecessary packages. if !reinstalls.is_empty() { for dist_info in &reinstalls { let summary = uv_installer::uninstall(dist_info) .await .context("Failed to uninstall build dependencies")?; debug!( "Uninstalled {} ({} file{}, {} director{})", dist_info.name(), summary.file_count, if summary.file_count == 1 { "" } else { "s" }, summary.dir_count, if summary.dir_count == 1 { "y" } else { "ies" }, ); } } // Install the resolved distributions. let mut wheels = wheels.into_iter().chain(cached).collect::<Vec<_>>(); if !wheels.is_empty() { debug!( "Installing build requirement{}: {}", if wheels.len() == 1 { "" } else { "s" }, wheels.iter().map(ToString::to_string).join(", ") ); wheels = Installer::new(venv, self.preview) .with_link_mode(self.link_mode) .with_cache(self.cache) .install(wheels) .await .context("Failed to install build dependencies")?; } Ok(wheels) } #[instrument(skip_all, fields(version_id = version_id, subdirectory = ?subdirectory))] async fn setup_build<'data>( &'data self, source: &'data Path, subdirectory: Option<&'data Path>, install_path: &'data Path, version_id: Option<&'data str>, dist: Option<&'data SourceDist>, sources: SourceStrategy, build_kind: BuildKind, build_output: BuildOutput, mut build_stack: BuildStack, ) -> Result<SourceBuild, uv_build_frontend::Error> { let dist_name = dist.map(uv_distribution_types::Name::name); let dist_version = dist .map(uv_distribution_types::DistributionMetadata::version_or_url) .and_then(|version| match version { VersionOrUrlRef::Version(version) => Some(version), VersionOrUrlRef::Url(_) => None, }); // Note we can only prevent builds by name for packages with names // unless all builds are disabled. if self .build_options .no_build_requirement(dist_name) // We always allow editable builds && !matches!(build_kind, BuildKind::Editable) { let err = if let Some(dist) = dist { uv_build_frontend::Error::NoSourceDistBuild(dist.name().clone()) } else { uv_build_frontend::Error::NoSourceDistBuilds }; return Err(err); } // Push the current distribution onto the build stack, to prevent cyclic dependencies. if let Some(dist) = dist { build_stack.insert(dist.distribution_id()); } // Get package-specific config settings if available; otherwise, use global settings. let config_settings = if let Some(name) = dist_name { if let Some(package_settings) = self.config_settings_package.get(name) { package_settings.clone().merge(self.config_settings.clone()) } else { self.config_settings.clone() } } else { self.config_settings.clone() }; // Get package-specific environment variables if available. let mut environment_variables = self.build_extra_env_vars.clone(); if let Some(name) = dist_name { if let Some(package_vars) = self.extra_build_variables.get(name) { environment_variables.extend( package_vars .iter() .map(|(key, value)| (OsString::from(key), OsString::from(value))), ); } } let builder = SourceBuild::setup( source, subdirectory, install_path, dist_name, dist_version, self.interpreter, self, self.source_build_context.clone(), version_id, self.index_locations, sources, self.workspace_cache(), config_settings, self.build_isolation, self.extra_build_requires, &build_stack, build_kind, environment_variables, build_output, self.concurrency.builds, self.client.credentials_cache(), self.preview, ) .boxed_local() .await?; Ok(builder) } async fn direct_build<'data>( &'data self, source: &'data Path, subdirectory: Option<&'data Path>, output_dir: &'data Path, sources: SourceStrategy, build_kind: BuildKind, version_id: Option<&'data str>, ) -> Result<Option<DistFilename>, BuildDispatchError> { let source_tree = if let Some(subdir) = subdirectory { source.join(subdir) } else { source.to_path_buf() }; // Only perform the direct build if the backend is uv in a compatible version. let source_tree_str = source_tree.display().to_string(); let identifier = version_id.unwrap_or_else(|| &source_tree_str); if !check_direct_build(&source_tree, identifier) { trace!("Requirements for direct build not matched: {identifier}"); return Ok(None); } debug!("Performing direct build for {identifier}"); let output_dir = output_dir.to_path_buf(); let filename = tokio::task::spawn_blocking(move || -> Result<_> { let filename = match build_kind { BuildKind::Wheel => { let wheel = uv_build_backend::build_wheel( &source_tree, &output_dir, None, uv_version::version(), sources == SourceStrategy::Enabled, )?; DistFilename::WheelFilename(wheel) } BuildKind::Sdist => { let source_dist = uv_build_backend::build_source_dist( &source_tree, &output_dir, uv_version::version(), sources == SourceStrategy::Enabled, )?; DistFilename::SourceDistFilename(source_dist) } BuildKind::Editable => { let wheel = uv_build_backend::build_editable( &source_tree, &output_dir, None, uv_version::version(), sources == SourceStrategy::Enabled, )?; DistFilename::WheelFilename(wheel) } }; Ok(filename) }) .await??; Ok(Some(filename)) } } /// Shared state used during resolution and installation. /// /// All elements are `Arc`s, so we can clone freely. #[derive(Default, Clone)] pub struct SharedState { /// The resolved Git references. git: GitResolver, /// The discovered capabilities for each registry index. capabilities: IndexCapabilities, /// The fetched package versions and metadata. index: InMemoryIndex, /// The downloaded distributions. in_flight: InFlight, /// Build directories for any PEP 517 builds executed during resolution or installation. build_arena: BuildArena<SourceBuild>, } impl SharedState { /// Fork the [`SharedState`], creating a new in-memory index and in-flight cache. /// /// State that is universally applicable (like the Git resolver and index capabilities) /// are retained. #[must_use] pub fn fork(&self) -> Self { Self { git: self.git.clone(), capabilities: self.capabilities.clone(), build_arena: self.build_arena.clone(), ..Default::default() } } /// Return the [`GitResolver`] used by the [`SharedState`]. pub fn git(&self) -> &GitResolver { &self.git } /// Return the [`InMemoryIndex`] used by the [`SharedState`]. pub fn index(&self) -> &InMemoryIndex { &self.index } /// Return the [`InFlight`] used by the [`SharedState`]. pub fn in_flight(&self) -> &InFlight { &self.in_flight } /// Return the [`IndexCapabilities`] used by the [`SharedState`]. pub fn capabilities(&self) -> &IndexCapabilities { &self.capabilities } /// Return the [`BuildArena`] used by the [`SharedState`]. pub fn build_arena(&self) -> &BuildArena<SourceBuild> { &self.build_arena } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-flags/src/lib.rs
crates/uv-flags/src/lib.rs
use std::sync::OnceLock; static FLAGS: OnceLock<EnvironmentFlags> = OnceLock::new(); bitflags::bitflags! { #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct EnvironmentFlags: u32 { const SKIP_WHEEL_FILENAME_CHECK = 1 << 0; const HIDE_BUILD_OUTPUT = 1 << 1; } } /// Initialize the environment flags. #[allow(clippy::result_unit_err)] pub fn init(flags: EnvironmentFlags) -> Result<(), ()> { FLAGS.set(flags).map_err(|_| ()) } /// Check if a specific environment flag is set. pub fn contains(flag: EnvironmentFlags) -> bool { FLAGS.get_or_init(EnvironmentFlags::default).contains(flag) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-redacted/src/lib.rs
crates/uv-redacted/src/lib.rs
use ref_cast::RefCast; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::fmt::{Debug, Display}; use std::ops::{Deref, DerefMut}; use std::str::FromStr; use thiserror::Error; use url::Url; #[derive(Error, Debug, Clone, PartialEq, Eq)] pub enum DisplaySafeUrlError { /// Failed to parse a URL. #[error(transparent)] Url(#[from] url::ParseError), /// We parsed a URL, but couldn't disambiguate its authority /// component. #[error("ambiguous user/pass authority in URL (not percent-encoded?): {0}")] AmbiguousAuthority(String), } /// A [`Url`] wrapper that redacts credentials when displaying the URL. /// /// `DisplaySafeUrl` wraps the standard [`url::Url`] type, providing functionality to mask /// secrets by default when the URL is displayed or logged. This helps prevent accidental /// exposure of sensitive information in logs and debug output. /// /// # Examples /// /// ``` /// use uv_redacted::DisplaySafeUrl; /// use std::str::FromStr; /// /// // Create a `DisplaySafeUrl` from a `&str` /// let mut url = DisplaySafeUrl::parse("https://user:password@example.com").unwrap(); /// /// // Display will mask secrets /// assert_eq!(url.to_string(), "https://user:****@example.com/"); /// /// // You can still access the username and password /// assert_eq!(url.username(), "user"); /// assert_eq!(url.password(), Some("password")); /// /// // And you can still update the username and password /// let _ = url.set_username("new_user"); /// let _ = url.set_password(Some("new_password")); /// assert_eq!(url.username(), "new_user"); /// assert_eq!(url.password(), Some("new_password")); /// /// // It is also possible to remove the credentials entirely /// url.remove_credentials(); /// assert_eq!(url.username(), ""); /// assert_eq!(url.password(), None); /// ``` #[derive(Clone, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize, RefCast)] #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] #[cfg_attr(feature = "schemars", schemars(transparent))] #[repr(transparent)] pub struct DisplaySafeUrl(Url); /// Check if a path or fragment contains a credential-like pattern (`:` followed by `@`). /// /// This skips colons that are followed by `//`, as those indicate URL schemes (e.g., `https://`) /// rather than credentials. This is important for handling nested URLs like proxy URLs: /// `git+https://proxy.com/https://github.com/user/repo.git@branch`. fn has_credential_like_pattern(s: &str) -> bool { let mut remaining = s; while let Some(colon_pos) = remaining.find(':') { let after_colon = &remaining[colon_pos + 1..]; // If the colon is followed by "//", consider it a URL scheme. if after_colon.starts_with("//") { remaining = after_colon; continue; } // Check if there's an @ after this colon. if after_colon.contains('@') { return true; } remaining = after_colon; } false } impl DisplaySafeUrl { #[inline] pub fn parse(input: &str) -> Result<Self, DisplaySafeUrlError> { let url = Url::parse(input)?; Self::reject_ambiguous_credentials(input, &url)?; Ok(Self(url)) } /// Reject some ambiguous cases, e.g., `https://user/name:password@domain/a/b/c` /// /// In this case the user *probably* meant to have a username of "user/name", but both RFC /// 3986 and WHATWG URL expect the userinfo (RFC 3986) or authority (WHATWG) to not contain a /// non-percent-encoded slash or other special character. /// /// This ends up being moderately annoying to detect, since the above gets parsed into a /// "valid" WHATWG URL where the host is `used` and the pathname is /// `/name:password@domain/a/b/c` rather than causing a parse error. /// /// To detect it, we use a heuristic: if the password component is missing but the path or /// fragment contain a `:` followed by a `@`, then we assume the URL is ambiguous. fn reject_ambiguous_credentials(input: &str, url: &Url) -> Result<(), DisplaySafeUrlError> { // `git://`, `http://`, and `https://` URLs may carry credentials, while `file://` URLs // on Windows may contain both sigils, but it's always safe, e.g. // `file://C:/Users/ferris/project@home/workspace`. if url.scheme() == "file" { return Ok(()); } if url.password().is_some() { return Ok(()); } // Check for the suspicious pattern. if !has_credential_like_pattern(url.path()) && !url .fragment() .map(has_credential_like_pattern) .unwrap_or(false) { return Ok(()); } // If the previous check passed, we should always expect to find these in the given URL. let (Some(col_pos), Some(at_pos)) = (input.find(':'), input.rfind('@')) else { if cfg!(debug_assertions) { unreachable!( "`:` or `@` sign missing in URL that was confirmed to contain them: {input}" ); } return Ok(()); }; // Our ambiguous URL probably has credentials in it, so we don't want to blast it out in // the error message. We somewhat aggressively replace everything between the scheme's // ':' and the lastmost `@` with `***`. let redacted_path = format!("{}***{}", &input[0..=col_pos], &input[at_pos..]); Err(DisplaySafeUrlError::AmbiguousAuthority(redacted_path)) } /// Create a new [`DisplaySafeUrl`] from a [`Url`]. /// /// Unlike [`Self::parse`], this doesn't perform any ambiguity checks. /// That means that it's primarily useful for contexts where a human can't easily accidentally /// introduce an ambiguous URL, such as URLs being read from a request. pub fn from_url(url: Url) -> Self { Self(url) } /// Cast a `&Url` to a `&DisplaySafeUrl` using ref-cast. #[inline] pub fn ref_cast(url: &Url) -> &Self { RefCast::ref_cast(url) } /// Parse a string as an URL, with this URL as the base URL. #[inline] pub fn join(&self, input: &str) -> Result<Self, DisplaySafeUrlError> { Ok(Self(self.0.join(input)?)) } /// Serialize with Serde using the internal representation of the `Url` struct. #[inline] pub fn serialize_internal<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize_internal(serializer) } /// Serialize with Serde using the internal representation of the `Url` struct. #[inline] pub fn deserialize_internal<'de, D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { Ok(Self(Url::deserialize_internal(deserializer)?)) } #[allow(clippy::result_unit_err)] pub fn from_file_path<P: AsRef<std::path::Path>>(path: P) -> Result<Self, ()> { Ok(Self(Url::from_file_path(path)?)) } /// Remove the credentials from a URL, allowing the generic `git` username (without a password) /// in SSH URLs, as in, `ssh://git@github.com/...`. #[inline] pub fn remove_credentials(&mut self) { // For URLs that use the `git` convention (i.e., `ssh://git@github.com/...`), avoid dropping the // username. if is_ssh_git_username(&self.0) { return; } let _ = self.0.set_username(""); let _ = self.0.set_password(None); } /// Returns the URL with any credentials removed. pub fn without_credentials(&self) -> Cow<'_, Url> { if self.0.password().is_none() && self.0.username() == "" { return Cow::Borrowed(&self.0); } // For URLs that use the `git` convention (i.e., `ssh://git@github.com/...`), avoid dropping the // username. if is_ssh_git_username(&self.0) { return Cow::Borrowed(&self.0); } let mut url = self.0.clone(); let _ = url.set_username(""); let _ = url.set_password(None); Cow::Owned(url) } /// Returns [`Display`] implementation that doesn't mask credentials. #[inline] pub fn displayable_with_credentials(&self) -> impl Display { &self.0 } } impl Deref for DisplaySafeUrl { type Target = Url; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for DisplaySafeUrl { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl Display for DisplaySafeUrl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { display_with_redacted_credentials(&self.0, f) } } impl Debug for DisplaySafeUrl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let url = &self.0; // For URLs that use the `git` convention (i.e., `ssh://git@github.com/...`), avoid masking the // username. let (username, password) = if is_ssh_git_username(url) { (url.username(), None) } else if url.username() != "" && url.password().is_some() { (url.username(), Some("****")) } else if url.username() != "" { ("****", None) } else if url.password().is_some() { ("", Some("****")) } else { ("", None) }; f.debug_struct("DisplaySafeUrl") .field("scheme", &url.scheme()) .field("cannot_be_a_base", &url.cannot_be_a_base()) .field("username", &username) .field("password", &password) .field("host", &url.host()) .field("port", &url.port()) .field("path", &url.path()) .field("query", &url.query()) .field("fragment", &url.fragment()) .finish() } } impl From<DisplaySafeUrl> for Url { fn from(url: DisplaySafeUrl) -> Self { url.0 } } impl From<Url> for DisplaySafeUrl { fn from(url: Url) -> Self { Self(url) } } impl FromStr for DisplaySafeUrl { type Err = DisplaySafeUrlError; fn from_str(input: &str) -> Result<Self, Self::Err> { Self::parse(input) } } fn is_ssh_git_username(url: &Url) -> bool { matches!(url.scheme(), "ssh" | "git+ssh" | "git+https") && url.username() == "git" && url.password().is_none() } fn display_with_redacted_credentials( url: &Url, f: &mut std::fmt::Formatter<'_>, ) -> std::fmt::Result { if url.password().is_none() && url.username() == "" { return write!(f, "{url}"); } // For URLs that use the `git` convention (i.e., `ssh://git@github.com/...`), avoid dropping the // username. if is_ssh_git_username(url) { return write!(f, "{url}"); } write!(f, "{}://", url.scheme())?; if url.username() != "" && url.password().is_some() { write!(f, "{}", url.username())?; write!(f, ":****@")?; } else if url.username() != "" { write!(f, "****@")?; } else if url.password().is_some() { write!(f, ":****@")?; } write!(f, "{}", url.host_str().unwrap_or(""))?; if let Some(port) = url.port() { write!(f, ":{port}")?; } write!(f, "{}", url.path())?; if let Some(query) = url.query() { write!(f, "?{query}")?; } if let Some(fragment) = url.fragment() { write!(f, "#{fragment}")?; } Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn from_url_no_credentials() { let url_str = "https://pypi-proxy.fly.dev/basic-auth/simple"; let log_safe_url = DisplaySafeUrl::parse("https://pypi-proxy.fly.dev/basic-auth/simple").unwrap(); assert_eq!(log_safe_url.username(), ""); assert!(log_safe_url.password().is_none()); assert_eq!(log_safe_url.to_string(), url_str); } #[test] fn from_url_username_and_password() { let log_safe_url = DisplaySafeUrl::parse("https://user:pass@pypi-proxy.fly.dev/basic-auth/simple") .unwrap(); assert_eq!(log_safe_url.username(), "user"); assert!(log_safe_url.password().is_some_and(|p| p == "pass")); assert_eq!( log_safe_url.to_string(), "https://user:****@pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn from_url_just_password() { let log_safe_url = DisplaySafeUrl::parse("https://:pass@pypi-proxy.fly.dev/basic-auth/simple").unwrap(); assert_eq!(log_safe_url.username(), ""); assert!(log_safe_url.password().is_some_and(|p| p == "pass")); assert_eq!( log_safe_url.to_string(), "https://:****@pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn from_url_just_username() { let log_safe_url = DisplaySafeUrl::parse("https://user@pypi-proxy.fly.dev/basic-auth/simple").unwrap(); assert_eq!(log_safe_url.username(), "user"); assert!(log_safe_url.password().is_none()); assert_eq!( log_safe_url.to_string(), "https://****@pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn from_url_git_username() { let ssh_str = "ssh://git@github.com/org/repo"; let ssh_url = DisplaySafeUrl::parse(ssh_str).unwrap(); assert_eq!(ssh_url.username(), "git"); assert!(ssh_url.password().is_none()); assert_eq!(ssh_url.to_string(), ssh_str); // Test again for the `git+ssh` scheme let git_ssh_str = "git+ssh://git@github.com/org/repo"; let git_ssh_url = DisplaySafeUrl::parse(git_ssh_str).unwrap(); assert_eq!(git_ssh_url.username(), "git"); assert!(git_ssh_url.password().is_none()); assert_eq!(git_ssh_url.to_string(), git_ssh_str); } #[test] fn parse_url_string() { let url_str = "https://user:pass@pypi-proxy.fly.dev/basic-auth/simple"; let log_safe_url = DisplaySafeUrl::parse(url_str).unwrap(); assert_eq!(log_safe_url.username(), "user"); assert!(log_safe_url.password().is_some_and(|p| p == "pass")); assert_eq!( log_safe_url.to_string(), "https://user:****@pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn remove_credentials() { let url_str = "https://user:pass@pypi-proxy.fly.dev/basic-auth/simple"; let mut log_safe_url = DisplaySafeUrl::parse(url_str).unwrap(); log_safe_url.remove_credentials(); assert_eq!(log_safe_url.username(), ""); assert!(log_safe_url.password().is_none()); assert_eq!( log_safe_url.to_string(), "https://pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn preserve_ssh_git_username_on_remove_credentials() { let ssh_str = "ssh://git@pypi-proxy.fly.dev/basic-auth/simple"; let mut ssh_url = DisplaySafeUrl::parse(ssh_str).unwrap(); ssh_url.remove_credentials(); assert_eq!(ssh_url.username(), "git"); assert!(ssh_url.password().is_none()); assert_eq!(ssh_url.to_string(), ssh_str); // Test again for `git+ssh` scheme let git_ssh_str = "git+ssh://git@pypi-proxy.fly.dev/basic-auth/simple"; let mut git_shh_url = DisplaySafeUrl::parse(git_ssh_str).unwrap(); git_shh_url.remove_credentials(); assert_eq!(git_shh_url.username(), "git"); assert!(git_shh_url.password().is_none()); assert_eq!(git_shh_url.to_string(), git_ssh_str); } #[test] fn displayable_with_credentials() { let url_str = "https://user:pass@pypi-proxy.fly.dev/basic-auth/simple"; let log_safe_url = DisplaySafeUrl::parse(url_str).unwrap(); assert_eq!( log_safe_url.displayable_with_credentials().to_string(), url_str ); } #[test] fn url_join() { let url_str = "https://token@example.com/abc/"; let log_safe_url = DisplaySafeUrl::parse(url_str).unwrap(); let foo_url = log_safe_url.join("foo").unwrap(); assert_eq!(foo_url.to_string(), "https://****@example.com/abc/foo"); } #[test] fn log_safe_url_ref() { let url_str = "https://user:pass@pypi-proxy.fly.dev/basic-auth/simple"; let url = DisplaySafeUrl::parse(url_str).unwrap(); let log_safe_url = DisplaySafeUrl::ref_cast(&url); assert_eq!(log_safe_url.username(), "user"); assert!(log_safe_url.password().is_some_and(|p| p == "pass")); assert_eq!( log_safe_url.to_string(), "https://user:****@pypi-proxy.fly.dev/basic-auth/simple" ); } #[test] fn parse_url_ambiguous() { for url in &[ "https://user/name:password@domain/a/b/c", "https://user\\name:password@domain/a/b/c", "https://user#name:password@domain/a/b/c", "https://user.com/name:password@domain/a/b/c", ] { let err = DisplaySafeUrl::parse(url).unwrap_err(); match err { DisplaySafeUrlError::AmbiguousAuthority(redacted) => { assert!(redacted.starts_with("https:***@domain/a/b/c")); } DisplaySafeUrlError::Url(_) => panic!("expected AmbiguousAuthority error"), } } } #[test] fn parse_url_not_ambiguous() { for url in &[ // https://github.com/astral-sh/uv/issues/16756 "file:///C:/jenkins/ython_Environment_Manager_PR-251@2/venv%201/workspace", // https://github.com/astral-sh/uv/issues/17214 // Git proxy URLs with nested schemes should not trigger the ambiguity check "git+https://githubproxy.cc/https://github.com/user/repo.git@branch", "git+https://proxy.example.com/https://github.com/org/project@v1.0.0", "git+https://proxy.example.com/https://github.com/org/project@refs/heads/main", ] { DisplaySafeUrl::parse(url).unwrap(); } } #[test] fn credential_like_pattern() { assert!(!has_credential_like_pattern( "/https://github.com/user/repo.git@branch" )); assert!(!has_credential_like_pattern("/http://example.com/path@ref")); assert!(has_credential_like_pattern("/name:password@domain/a/b/c")); assert!(has_credential_like_pattern(":password@domain")); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-publish/src/trusted_publishing.rs
crates/uv-publish/src/trusted_publishing.rs
//! Trusted publishing (via OIDC) with GitHub Actions and GitLab CI. use base64::Engine; use base64::prelude::BASE64_URL_SAFE_NO_PAD; use reqwest::StatusCode; use reqwest_middleware::ClientWithMiddleware; use serde::{Deserialize, Serialize}; use std::env; use std::fmt::Display; use thiserror::Error; use tracing::{debug, trace}; use url::Url; use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError}; use uv_static::EnvVars; #[derive(Debug, Error)] pub enum TrustedPublishingError { #[error(transparent)] Url(#[from] DisplaySafeUrlError), #[error("Failed to obtain OIDC token: is the `id-token: write` permission missing?")] GitHubPermissions(#[source] ambient_id::Error), /// A hard failure during OIDC token discovery. #[error("Failed to discover OIDC token")] Discovery(#[source] ambient_id::Error), /// A soft failure during OIDC token discovery. /// /// In practice, this usually means the user attempted to force trusted /// publishing outside of something like GitHub Actions or GitLab CI. #[error("No OIDC token discovered: are you in a supported trusted publishing environment?")] NoToken, #[error("Failed to fetch: `{0}`")] Reqwest(DisplaySafeUrl, #[source] reqwest::Error), #[error("Failed to fetch: `{0}`")] ReqwestMiddleware(DisplaySafeUrl, #[source] reqwest_middleware::Error), #[error(transparent)] SerdeJson(#[from] serde_json::error::Error), #[error( "PyPI returned error code {0}, is trusted publishing correctly configured?\nResponse: {1}\nToken claims, which must match the PyPI configuration: {2:#?}" )] Pypi(StatusCode, String, OidcTokenClaims), /// When trusted publishing is misconfigured, the error above should occur, not this one. #[error("PyPI returned error code {0}, and the OIDC has an unexpected format.\nResponse: {1}")] InvalidOidcToken(StatusCode, String), } #[derive(Deserialize)] #[serde(transparent)] pub struct TrustedPublishingToken(String); impl Display for TrustedPublishingToken { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } /// The response from querying `https://pypi.org/_/oidc/audience`. #[derive(Deserialize)] struct Audience { audience: String, } /// The body for querying `$ACTIONS_ID_TOKEN_REQUEST_URL&audience=pypi`. #[derive(Serialize)] struct MintTokenRequest { token: String, } /// The response from querying `$ACTIONS_ID_TOKEN_REQUEST_URL&audience=pypi`. #[derive(Deserialize)] struct PublishToken { token: TrustedPublishingToken, } /// The payload of the OIDC token. #[derive(Deserialize, Debug)] #[allow(dead_code)] pub struct OidcTokenClaims { sub: String, repository: String, repository_owner: String, repository_owner_id: String, job_workflow_ref: String, r#ref: String, } /// Returns the short-lived token to use for uploading. /// /// Return states: /// - `Ok(Some(token))`: Successfully obtained a trusted publishing token. /// - `Ok(None)`: Not in a supported CI environment for trusted publishing. /// - `Err(...)`: An error occurred while trying to obtain the token. pub(crate) async fn get_token( registry: &DisplaySafeUrl, client: &ClientWithMiddleware, ) -> Result<Option<TrustedPublishingToken>, TrustedPublishingError> { // Get the OIDC token's audience from the registry. let audience = get_audience(registry, client).await?; // Perform ambient OIDC token discovery. // Depending on the host (GitHub Actions, GitLab CI, etc.) // this may perform additional network requests. let oidc_token = get_oidc_token(&audience, client).await?; // Exchange the OIDC token for a short-lived upload token, // if OIDC token discovery succeeded. if let Some(oidc_token) = oidc_token { let publish_token = get_publish_token(registry, oidc_token, client).await?; // If we're on GitHub Actions, mask the exchanged token in logs. #[allow(clippy::print_stdout)] if env::var(EnvVars::GITHUB_ACTIONS) == Ok("true".to_string()) { println!("::add-mask::{publish_token}"); } Ok(Some(publish_token)) } else { // Not in a supported CI environment for trusted publishing. Ok(None) } } async fn get_audience( registry: &DisplaySafeUrl, client: &ClientWithMiddleware, ) -> Result<String, TrustedPublishingError> { // `pypa/gh-action-pypi-publish` uses `netloc` (RFC 1808), which is deprecated for authority // (RFC 3986). // Prefer HTTPS for OIDC discovery; allow HTTP only in test builds let scheme: &str = if cfg!(feature = "test") { registry.scheme() } else { "https" }; let audience_url = DisplaySafeUrl::parse(&format!( "{}://{}/_/oidc/audience", scheme, registry.authority() ))?; debug!("Querying the trusted publishing audience from {audience_url}"); let response = client .get(Url::from(audience_url.clone())) .send() .await .map_err(|err| TrustedPublishingError::ReqwestMiddleware(audience_url.clone(), err))?; let audience = response .error_for_status() .map_err(|err| TrustedPublishingError::Reqwest(audience_url.clone(), err))? .json::<Audience>() .await .map_err(|err| TrustedPublishingError::Reqwest(audience_url.clone(), err))?; trace!("The audience is `{}`", &audience.audience); Ok(audience.audience) } /// Perform ambient OIDC token discovery. async fn get_oidc_token( audience: &str, client: &ClientWithMiddleware, ) -> Result<Option<ambient_id::IdToken>, TrustedPublishingError> { let detector = ambient_id::Detector::new_with_client(client.clone()); match detector.detect(audience).await { Ok(token) => Ok(token), // Specialize the error case insufficient permissions error case, // since we can offer the user a hint about fixing their permissions. Err( err @ ambient_id::Error::GitHubActions( ambient_id::GitHubError::InsufficientPermissions(_), ), ) => Err(TrustedPublishingError::GitHubPermissions(err)), Err(err) => Err(TrustedPublishingError::Discovery(err)), } } /// Parse the JSON Web Token that the OIDC token is. /// /// See: <https://github.com/pypa/gh-action-pypi-publish/blob/db8f07d3871a0a180efa06b95d467625c19d5d5f/oidc-exchange.py#L165-L184> fn decode_oidc_token(oidc_token: &str) -> Option<OidcTokenClaims> { let token_segments = oidc_token.splitn(3, '.').collect::<Vec<&str>>(); let [_header, payload, _signature] = *token_segments.into_boxed_slice() else { return None; }; let decoded = BASE64_URL_SAFE_NO_PAD.decode(payload).ok()?; serde_json::from_slice(&decoded).ok() } async fn get_publish_token( registry: &DisplaySafeUrl, oidc_token: ambient_id::IdToken, client: &ClientWithMiddleware, ) -> Result<TrustedPublishingToken, TrustedPublishingError> { // Prefer HTTPS for OIDC minting; allow HTTP only in test builds let scheme: &str = if cfg!(feature = "test") { registry.scheme() } else { "https" }; let mint_token_url = DisplaySafeUrl::parse(&format!( "{}://{}/_/oidc/mint-token", scheme, registry.authority() ))?; debug!("Querying the trusted publishing upload token from {mint_token_url}"); let mint_token_payload = MintTokenRequest { token: oidc_token.reveal().to_string(), }; let response = client .post(Url::from(mint_token_url.clone())) .body(serde_json::to_vec(&mint_token_payload)?) .send() .await .map_err(|err| TrustedPublishingError::ReqwestMiddleware(mint_token_url.clone(), err))?; // reqwest's implementation of `.json()` also goes through `.bytes()` let status = response.status(); let body = response .bytes() .await .map_err(|err| TrustedPublishingError::Reqwest(mint_token_url.clone(), err))?; if status.is_success() { let publish_token: PublishToken = serde_json::from_slice(&body)?; Ok(publish_token.token) } else { match decode_oidc_token(oidc_token.reveal()) { Some(claims) => { // An error here means that something is misconfigured, e.g. a typo in the PyPI // configuration, so we're showing the body and the JWT claims for more context, see // https://docs.pypi.org/trusted-publishers/troubleshooting/#token-minting // for what the body can mean. Err(TrustedPublishingError::Pypi( status, String::from_utf8_lossy(&body).to_string(), claims, )) } None => { // This is not a user configuration error, the OIDC token should always have a valid // format. Err(TrustedPublishingError::InvalidOidcToken( status, String::from_utf8_lossy(&body).to_string(), )) } } } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-publish/src/lib.rs
crates/uv-publish/src/lib.rs
mod trusted_publishing; use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::{fmt, io}; use fs_err::tokio::File; use futures::TryStreamExt; use glob::{GlobError, PatternError, glob}; use itertools::Itertools; use reqwest::header::{AUTHORIZATION, LOCATION, ToStrError}; use reqwest::multipart::Part; use reqwest::{Body, Response, StatusCode}; use reqwest_retry::RetryError; use reqwest_retry::policies::ExponentialBackoff; use rustc_hash::FxHashMap; use serde::Deserialize; use thiserror::Error; use tokio::io::{AsyncReadExt, BufReader}; use tokio::sync::Semaphore; use tokio_util::io::ReaderStream; use tracing::{Level, debug, enabled, trace, warn}; use url::Url; use uv_auth::{Credentials, PyxTokenStore, Realm}; use uv_cache::{Cache, Refresh}; use uv_client::{ BaseClient, DEFAULT_MAX_REDIRECTS, MetadataFormat, OwnedArchive, RegistryClientBuilder, RequestBuilder, RetryParsingError, RetryState, }; use uv_configuration::{KeyringProviderType, TrustedPublishing}; use uv_distribution_filename::{DistFilename, SourceDistExtension, SourceDistFilename}; use uv_distribution_types::{IndexCapabilities, IndexUrl}; use uv_extract::hash::{HashReader, Hasher}; use uv_fs::{ProgressReader, Simplified}; use uv_metadata::read_metadata_async_seek; use uv_pypi_types::{HashAlgorithm, HashDigest, Metadata23, MetadataError}; use uv_redacted::{DisplaySafeUrl, DisplaySafeUrlError}; use uv_warnings::warn_user; use crate::trusted_publishing::{TrustedPublishingError, TrustedPublishingToken}; #[derive(Error, Debug)] pub enum PublishError { #[error("The publish path is not a valid glob pattern: `{0}`")] Pattern(String, #[source] PatternError), /// [`GlobError`] is a wrapped io error. #[error(transparent)] Glob(#[from] GlobError), #[error("Path patterns didn't match any wheels or source distributions")] NoFiles, #[error(transparent)] Fmt(#[from] fmt::Error), #[error("File is neither a wheel nor a source distribution: `{}`", _0.user_display())] InvalidFilename(PathBuf), #[error("Failed to publish: `{}`", _0.user_display())] PublishPrepare(PathBuf, #[source] Box<PublishPrepareError>), #[error("Failed to publish `{}` to {}", _0.user_display(), _1)] PublishSend( PathBuf, Box<DisplaySafeUrl>, #[source] Box<PublishSendError>, ), #[error("Unable to publish `{}` to {}", _0.user_display(), _1)] Validate( PathBuf, Box<DisplaySafeUrl>, #[source] Box<PublishSendError>, ), #[error("Failed to obtain token for trusted publishing")] TrustedPublishing(#[from] Box<TrustedPublishingError>), #[error("{0} are not allowed when using trusted publishing")] MixedCredentials(String), #[error("Failed to query check URL")] CheckUrlIndex(#[source] uv_client::Error), #[error( "Local file and index file do not match for {filename}. \ Local: {hash_algorithm}={local}, Remote: {hash_algorithm}={remote}" )] HashMismatch { filename: Box<DistFilename>, hash_algorithm: HashAlgorithm, local: String, remote: String, }, #[error("Hash is missing in index for {0}")] MissingHash(Box<DistFilename>), #[error(transparent)] RetryParsing(#[from] RetryParsingError), } /// Failure to get the metadata for a specific file. #[derive(Error, Debug)] pub enum PublishPrepareError { #[error(transparent)] Io(#[from] io::Error), #[error("Failed to read metadata")] Metadata(#[from] uv_metadata::Error), #[error("Failed to read metadata")] Metadata23(#[from] MetadataError), #[error("Only files ending in `.tar.gz` are valid source distributions: `{0}`")] InvalidExtension(SourceDistFilename), #[error("No PKG-INFO file found")] MissingPkgInfo, #[error("Multiple PKG-INFO files found: `{0}`")] MultiplePkgInfo(String), #[error("Failed to read: `{0}`")] Read(String, #[source] io::Error), #[error("Invalid PEP 740 attestation (not JSON): `{0}`")] InvalidAttestation(PathBuf, #[source] serde_json::Error), } /// Failure in or after (HTTP) transport for a specific file. #[derive(Error, Debug)] pub enum PublishSendError { #[error("Failed to send POST request")] ReqwestMiddleware(#[source] reqwest_middleware::Error), #[error("Upload failed with status {0}")] StatusNoBody(StatusCode, #[source] reqwest::Error), #[error("Upload failed with status code {0}. Server says: {1}")] Status(StatusCode, String), #[error( "POST requests are not supported by the endpoint, are you using the simple index URL instead of the upload URL?" )] MethodNotAllowedNoBody, #[error( "POST requests are not supported by the endpoint, are you using the simple index URL instead of the upload URL? Server says: {0}" )] MethodNotAllowed(String), /// The registry returned a "403 Forbidden". #[error("Permission denied (status code {0}): {1}")] PermissionDenied(StatusCode, String), #[error("Too many redirects, only {0} redirects are allowed")] TooManyRedirects(u32), #[error("Redirected URL is not in the same realm. Redirected to: {0}")] RedirectRealmMismatch(String), #[error("Request was redirected, but no location header was provided")] RedirectNoLocation, #[error("Request was redirected, but location header is not a UTF-8 string")] RedirectLocationInvalidStr(#[source] ToStrError), #[error("Request was redirected, but location header is not a URL")] RedirectInvalidLocation(#[source] DisplaySafeUrlError), } pub trait Reporter: Send + Sync + 'static { fn on_progress(&self, name: &str, id: usize); fn on_upload_start(&self, name: &str, size: Option<u64>) -> usize; fn on_upload_progress(&self, id: usize, inc: u64); fn on_upload_complete(&self, id: usize); } /// Context for using a fresh registry client for check URL requests. pub struct CheckUrlClient<'a> { pub index_url: IndexUrl, pub registry_client_builder: RegistryClientBuilder<'a>, pub client: &'a BaseClient, pub index_capabilities: IndexCapabilities, pub cache: &'a Cache, } impl PublishSendError { /// Extract `code` from the PyPI json error response, if any. /// /// The error response from PyPI contains crucial context, such as the difference between /// "Invalid or non-existent authentication information" and "The user 'konstin' isn't allowed /// to upload to project 'dummy'". /// /// Twine uses the HTTP status reason for its error messages. In HTTP 2.0 and onward this field /// is abolished, so reqwest doesn't expose it, see /// <https://docs.rs/reqwest/0.12.7/reqwest/struct.StatusCode.html#method.canonical_reason>. /// PyPI does respect the content type for error responses and can return an error display as /// HTML, JSON and plain. Since HTML and plain text are both overly verbose, we show the JSON /// response. Examples are shown below, line breaks were inserted for readability. Of those, /// the `code` seems to be the most helpful message, so we return it. If the response isn't a /// JSON document with `code` we return the regular body. /// /// ```json /// {"message": "The server could not comply with the request since it is either malformed or /// otherwise incorrect.\n\n\nError: Use 'source' as Python version for an sdist.\n\n", /// "code": "400 Error: Use 'source' as Python version for an sdist.", /// "title": "Bad Request"} /// ``` /// /// ```json /// {"message": "Access was denied to this resource.\n\n\nInvalid or non-existent authentication /// information. See https://test.pypi.org/help/#invalid-auth for more information.\n\n", /// "code": "403 Invalid or non-existent authentication information. See /// https://test.pypi.org/help/#invalid-auth for more information.", /// "title": "Forbidden"} /// ``` /// ```json /// {"message": "Access was denied to this resource.\n\n\n\n\n", /// "code": "403 Username/Password authentication is no longer supported. Migrate to API /// Tokens or Trusted Publishers instead. See https://test.pypi.org/help/#apitoken and /// https://test.pypi.org/help/#trusted-publishers", /// "title": "Forbidden"} /// ``` /// /// For context, for the last case twine shows: /// ```text /// WARNING Error during upload. Retry with the --verbose option for more details. /// ERROR HTTPError: 403 Forbidden from https://test.pypi.org/legacy/ /// Username/Password authentication is no longer supported. Migrate to API /// Tokens or Trusted Publishers instead. See /// https://test.pypi.org/help/#apitoken and /// https://test.pypi.org/help/#trusted-publishers /// ``` /// /// ```text /// INFO Response from https://test.pypi.org/legacy/: /// 403 Username/Password authentication is no longer supported. Migrate to /// API Tokens or Trusted Publishers instead. See /// https://test.pypi.org/help/#apitoken and /// https://test.pypi.org/help/#trusted-publishers /// INFO <html> /// <head> /// <title>403 Username/Password authentication is no longer supported. /// Migrate to API Tokens or Trusted Publishers instead. See /// https://test.pypi.org/help/#apitoken and /// https://test.pypi.org/help/#trusted-publishers</title> /// </head> /// <body> /// <h1>403 Username/Password authentication is no longer supported. /// Migrate to API Tokens or Trusted Publishers instead. See /// https://test.pypi.org/help/#apitoken and /// https://test.pypi.org/help/#trusted-publishers</h1> /// Access was denied to this resource.<br/><br/> /// ``` /// /// In comparison, we now show (line-wrapped for readability): /// /// ```text /// error: Failed to publish `dist/astral_test_1-0.1.0-py3-none-any.whl` to `https://test.pypi.org/legacy/` /// Caused by: Incorrect credentials (status code 403 Forbidden): 403 Username/Password /// authentication is no longer supported. Migrate to API Tokens or Trusted Publishers /// instead. See https://test.pypi.org/help/#apitoken and https://test.pypi.org/help/#trusted-publishers /// ``` fn extract_error_message(body: String, content_type: Option<&str>) -> String { if content_type == Some("application/json") { #[derive(Deserialize)] struct ErrorBody { code: String, } if let Ok(structured) = serde_json::from_str::<ErrorBody>(&body) { structured.code } else { body } } else { body } } } /// Represents a single "to-be-uploaded" distribution, along with zero /// or more attestations that will be uploaded alongside it. #[derive(Debug)] pub struct UploadDistribution { /// The path to the main distribution file to upload. pub file: PathBuf, /// The raw filename of the main distribution file. pub raw_filename: String, /// The parsed filename of the main distribution file. pub filename: DistFilename, /// Zero or more paths to PEP 740 attestations for the distribution. pub attestations: Vec<PathBuf>, } /// Given a list of paths (which may contain globs), unroll them into /// a flat, unique list of files. Files are returned in a stable /// but unspecified order. fn unroll_paths(paths: Vec<String>) -> Result<Vec<PathBuf>, PublishError> { let mut files = BTreeSet::default(); for path in paths { for file in glob(&path).map_err(|err| PublishError::Pattern(path.clone(), err))? { let file = file?; if !file.is_file() { continue; } files.insert(file); } } Ok(files.into_iter().collect()) } /// Given a flat list of input files, merge them into a list of [`UploadDistribution`]s. fn group_files(files: Vec<PathBuf>, no_attestations: bool) -> Vec<UploadDistribution> { let mut groups = FxHashMap::default(); let mut attestations_by_dist = FxHashMap::default(); for file in files { let Some(filename) = file .file_name() .and_then(|filename| filename.to_str()) .map(ToString::to_string) else { continue; }; // Attestations are named as `<dist>.<type>.attestation`, e.g. // `foo-1.2.3.tar.gz.publish.attestation`. // We use this to build up a map of `dist -> [attestations]` // for subsequent merging. let mut filename_parts = filename.rsplitn(3, '.'); if filename_parts.next() == Some("attestation") && let Some(_) = filename_parts.next() && let Some(dist_name) = filename_parts.next() { debug!( "Found attestation for distribution: `{}` -> `{}`", file.user_display(), dist_name ); attestations_by_dist .entry(dist_name.to_string()) .or_insert_with(Vec::new) .push(file); } else { let Some(dist_filename) = DistFilename::try_from_normalized_filename(&filename) else { debug!("Not a distribution filename: `{filename}`"); // I've never seen these in upper case #[allow(clippy::case_sensitive_file_extension_comparisons)] if filename.ends_with(".whl") || filename.ends_with(".zip") // Catch all compressed tar variants, e.g., `.tar.gz` || filename .split_once(".tar.") .is_some_and(|(_, ext)| ext.chars().all(char::is_alphanumeric)) { warn_user!( "Skipping file that looks like a distribution, \ but is not a valid distribution filename: `{}`", file.user_display() ); } continue; }; groups.insert( filename.clone(), UploadDistribution { file, raw_filename: filename, filename: dist_filename, attestations: Vec::new(), }, ); } } if no_attestations { debug!("Not merging attestations with distributions per user request"); } else { // Merge attestations into their respective upload groups. for (dist_name, attestations) in attestations_by_dist { if let Some(group) = groups.get_mut(&dist_name) { group.attestations = attestations; group.attestations.sort(); } } } groups.into_values().collect() } /// Collect the source distributions and wheels for publishing. /// /// Returns an [`UploadGroup`] for each distribution to be published. /// This group contains the path, the raw filename and the parsed filename. The raw filename is a fixup for /// <https://github.com/astral-sh/uv/issues/8030> caused by /// <https://github.com/pypa/setuptools/issues/3777> in combination with /// <https://github.com/pypi/warehouse/blob/50a58f3081e693a3772c0283050a275e350004bf/warehouse/forklift/legacy.py#L1133-L1155> pub fn group_files_for_publishing( paths: Vec<String>, no_attestations: bool, ) -> Result<Vec<UploadDistribution>, PublishError> { Ok(group_files(unroll_paths(paths)?, no_attestations)) } pub enum TrustedPublishResult { /// We didn't check for trusted publishing. Skipped, /// We checked for trusted publishing and found a token. Configured(TrustedPublishingToken), /// We checked for optional trusted publishing, but it didn't succeed. Ignored(TrustedPublishingError), } /// If applicable, attempt obtaining a token for trusted publishing. pub async fn check_trusted_publishing( username: Option<&str>, password: Option<&str>, keyring_provider: KeyringProviderType, trusted_publishing: TrustedPublishing, registry: &DisplaySafeUrl, client: &BaseClient, ) -> Result<TrustedPublishResult, PublishError> { match trusted_publishing { TrustedPublishing::Automatic => { // If the user provided credentials, use those. if username.is_some() || password.is_some() || keyring_provider != KeyringProviderType::Disabled { return Ok(TrustedPublishResult::Skipped); } debug!("Attempting to get a token for trusted publishing"); // Attempt to get a token for trusted publishing. match trusted_publishing::get_token(registry, client.for_host(registry).raw_client()) .await { // Success: we have a token for trusted publishing. Ok(Some(token)) => Ok(TrustedPublishResult::Configured(token)), // Failed to discover an ambient OIDC token. Ok(None) => Ok(TrustedPublishResult::Ignored( TrustedPublishingError::NoToken, )), // Hard failure during OIDC discovery or token exchange. Err(err) => Ok(TrustedPublishResult::Ignored(err)), } } TrustedPublishing::Always => { debug!("Using trusted publishing for GitHub Actions"); let mut conflicts = Vec::new(); if username.is_some() { conflicts.push("a username"); } if password.is_some() { conflicts.push("a password"); } if keyring_provider != KeyringProviderType::Disabled { conflicts.push("the keyring"); } if !conflicts.is_empty() { return Err(PublishError::MixedCredentials(conflicts.join(" and "))); } let Some(token) = trusted_publishing::get_token(registry, client.for_host(registry).raw_client()) .await .map_err(Box::new)? else { return Err(PublishError::TrustedPublishing( TrustedPublishingError::NoToken.into(), )); }; Ok(TrustedPublishResult::Configured(token)) } TrustedPublishing::Never => Ok(TrustedPublishResult::Skipped), } } /// Upload a file to a registry. /// /// Returns `true` if the file was newly uploaded and `false` if it already existed. /// /// Implements a custom retry flow since the request isn't cloneable. pub async fn upload( group: &UploadDistribution, form_metadata: &FormMetadata, registry: &DisplaySafeUrl, client: &BaseClient, retry_policy: ExponentialBackoff, credentials: &Credentials, check_url_client: Option<&CheckUrlClient<'_>>, download_concurrency: &Semaphore, reporter: Arc<impl Reporter>, ) -> Result<bool, PublishError> { let mut n_past_redirections = 0; let max_redirects = DEFAULT_MAX_REDIRECTS; let mut current_registry = registry.clone(); let mut retry_state = RetryState::start(retry_policy, registry.clone()); loop { let (request, idx) = build_upload_request( group, &current_registry, client, credentials, form_metadata, reporter.clone(), ) .await .map_err(|err| PublishError::PublishPrepare(group.file.clone(), Box::new(err)))?; let result = request.send().await; let response = match result { Ok(response) => { // When the user accidentally uses https://test.pypi.org/legacy (no slash) as publish URL, we // get a redirect to https://test.pypi.org/legacy/ (the canonical index URL). // In the above case we get 308, where reqwest or `RedirectClientWithMiddleware` would try // cloning the streaming body, which is not possible. // For https://test.pypi.org/simple (no slash), we get 301, which means we should make a GET request: // https://fetch.spec.whatwg.org/#http-redirect-fetch). // Reqwest doesn't support redirect policies conditional on the HTTP // method (https://github.com/seanmonstar/reqwest/issues/1777#issuecomment-2303386160), so we're // implementing our custom redirection logic. if response.status().is_redirection() { if n_past_redirections >= max_redirects { return Err(PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::TooManyRedirects(n_past_redirections).into(), )); } let location = response .headers() .get(LOCATION) .ok_or_else(|| { PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::RedirectNoLocation.into(), ) })? .to_str() .map_err(|err| { PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::RedirectLocationInvalidStr(err).into(), ) })?; current_registry = DisplaySafeUrl::parse(location).map_err(|err| { PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::RedirectInvalidLocation(err).into(), ) })?; if Realm::from(&current_registry) != Realm::from(registry) { return Err(PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::RedirectRealmMismatch(current_registry.to_string()) .into(), )); } debug!("Redirecting the request to: {}", current_registry); n_past_redirections += 1; continue; } reporter.on_upload_complete(idx); response } Err(err) => { let middleware_retries = if let Some(RetryError::WithRetries { retries, .. }) = (&err as &dyn std::error::Error).downcast_ref::<RetryError>() { *retries } else { 0 }; if let Some(backoff) = retry_state.should_retry(&err, middleware_retries) { retry_state.sleep_backoff(backoff).await; continue; } return Err(PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), PublishSendError::ReqwestMiddleware(err).into(), )); } }; return match handle_response(&current_registry, response).await { Ok(()) => { // Upload successful; for PyPI this can also mean a hash match in a raced upload // (but it doesn't tell us), for other registries it should mean a fresh upload. Ok(true) } Err(err) => { if matches!( err, PublishSendError::Status(..) | PublishSendError::StatusNoBody(..) ) { if let Some(check_url_client) = &check_url_client { if check_url( check_url_client, &group.file, &group.filename, download_concurrency, ) .await? { // There was a raced upload of the same file, so even though our upload failed, // the right file now exists in the registry. return Ok(false); } } } Err(PublishError::PublishSend( group.file.clone(), current_registry.clone().into(), err.into(), )) } }; } } /// Validate a file against a registry. pub async fn validate( file: &Path, form_metadata: &FormMetadata, raw_filename: &str, registry: &DisplaySafeUrl, store: &PyxTokenStore, client: &BaseClient, credentials: &Credentials, ) -> Result<(), PublishError> { if store.is_known_url(registry) { debug!("Performing validation request for {registry}"); let mut validation_url = registry.clone(); validation_url .path_segments_mut() .expect("URL must have path segments") .push("validate"); let request = build_validation_request( raw_filename, &validation_url, client, credentials, form_metadata, ); let response = request.send().await.map_err(|err| { PublishError::Validate( file.to_path_buf(), registry.clone().into(), PublishSendError::ReqwestMiddleware(err).into(), ) })?; handle_response(&validation_url, response) .await .map_err(|err| { PublishError::Validate(file.to_path_buf(), registry.clone().into(), err.into()) })?; } else { debug!("Skipping validation request for unsupported publish URL: {registry}"); } Ok(()) } /// Check whether we should skip the upload of a file because it already exists on the index. pub async fn check_url( check_url_client: &CheckUrlClient<'_>, file: &Path, filename: &DistFilename, download_concurrency: &Semaphore, ) -> Result<bool, PublishError> { let CheckUrlClient { index_url, registry_client_builder, client, index_capabilities, cache, } = check_url_client; // Avoid using the PyPI 10min default cache. let cache_refresh = (*cache) .clone() .with_refresh(Refresh::from_args(None, vec![filename.name().clone()])); let registry_client = registry_client_builder .clone() .cache(cache_refresh) .wrap_existing(client); debug!("Checking for {filename} in the registry"); let response = match registry_client .simple_detail( filename.name(), Some(index_url.into()), index_capabilities, download_concurrency, ) .await { Ok(response) => response, Err(err) => { return match err.kind() { uv_client::ErrorKind::RemotePackageNotFound(_) => { // The package doesn't exist, so we can't have uploaded it. warn!( "Package not found in the registry; skipping upload check for {filename}" ); Ok(false) } _ => Err(PublishError::CheckUrlIndex(err)), }; } }; let [(_, MetadataFormat::Simple(simple_metadata))] = response.as_slice() else { unreachable!("We queried a single index, we must get a single response"); }; let simple_metadata = OwnedArchive::deserialize(simple_metadata); let Some(metadatum) = simple_metadata .iter() .find(|metadatum| &metadatum.version == filename.version()) else { return Ok(false); }; let archived_file = match filename { DistFilename::SourceDistFilename(source_dist) => metadatum .files .source_dists .iter() .find(|entry| &entry.name == source_dist) .map(|entry| &entry.file), DistFilename::WheelFilename(wheel) => metadatum .files .wheels .iter() .find(|entry| &entry.name == wheel) .map(|entry| &entry.file), }; let Some(archived_file) = archived_file else { return Ok(false); }; // TODO(konsti): Do we have a preference for a hash here? if let Some(remote_hash) = archived_file.hashes.first() { // We accept the risk for TOCTOU errors here, since we already read the file once before the // streaming upload to compute the hash for the form metadata. let local_hash = &hash_file(file, vec![Hasher::from(remote_hash.algorithm)]) .await .map_err(|err| { PublishError::PublishPrepare( file.to_path_buf(), Box::new(PublishPrepareError::Io(err)), ) })?[0]; if local_hash.digest == remote_hash.digest { debug!( "Found {filename} in the registry with matching hash {}", remote_hash.digest ); Ok(true) } else { Err(PublishError::HashMismatch { filename: Box::new(filename.clone()), hash_algorithm: remote_hash.algorithm, local: local_hash.digest.to_string(), remote: remote_hash.digest.to_string(), }) } } else { Err(PublishError::MissingHash(Box::new(filename.clone()))) } } /// Calculate the requested hashes of a file. async fn hash_file( path: impl AsRef<Path>, hashers: Vec<Hasher>, ) -> Result<Vec<HashDigest>, io::Error> { debug!("Hashing {}", path.as_ref().display()); let file = BufReader::new(File::open(path.as_ref()).await?); let mut hashers = hashers; HashReader::new(file, &mut hashers).finish().await?; Ok(hashers .into_iter() .map(HashDigest::from) .collect::<Vec<_>>()) } // Not in `uv-metadata` because we only support tar files here. async fn source_dist_pkg_info(file: &Path) -> Result<Vec<u8>, PublishPrepareError> { let reader = BufReader::new(File::open(&file).await?); let decoded = async_compression::tokio::bufread::GzipDecoder::new(reader); let mut archive = tokio_tar::Archive::new(decoded); let mut pkg_infos: Vec<(PathBuf, Vec<u8>)> = archive .entries()? .map_err(PublishPrepareError::from) .try_filter_map(async |mut entry| { let path = entry .path() .map_err(PublishPrepareError::from)? .to_path_buf(); let mut components = path.components(); let Some(_top_level) = components.next() else { return Ok(None); }; let Some(pkg_info) = components.next() else { return Ok(None); }; if components.next().is_some() || pkg_info.as_os_str() != "PKG-INFO" { return Ok(None); } let mut buffer = Vec::new(); // We have to read while iterating or the entry is empty as we're beyond it in the file. entry.read_to_end(&mut buffer).await.map_err(|err| { PublishPrepareError::Read(path.to_string_lossy().to_string(), err) })?; Ok(Some((path, buffer))) }) .try_collect() .await?; match pkg_infos.len() { 0 => Err(PublishPrepareError::MissingPkgInfo), 1 => Ok(pkg_infos.remove(0).1), _ => Err(PublishPrepareError::MultiplePkgInfo( pkg_infos .iter() .map(|(path, _buffer)| path.to_string_lossy()) .join(", "), )), } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-static/src/lib.rs
crates/uv-static/src/lib.rs
pub use env_vars::*; mod env_vars;
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-static/src/env_vars.rs
crates/uv-static/src/env_vars.rs
//! Environment variables used or supported by uv. //! Used to generate `docs/reference/environment.md`. use uv_macros::{attr_added_in, attr_env_var_pattern, attr_hidden, attribute_env_vars_metadata}; /// Declares all environment variable used throughout `uv` and its crates. pub struct EnvVars; #[attribute_env_vars_metadata] impl EnvVars { /// The path to the binary that was used to invoke uv. /// /// This is propagated to all subprocesses spawned by uv. /// /// If the executable was invoked through a symbolic link, some platforms will return the path /// of the symbolic link and other platforms will return the path of the symbolic link’s target. /// /// See <https://doc.rust-lang.org/std/env/fn.current_exe.html#security> for security /// considerations. #[attr_added_in("0.6.0")] pub const UV: &'static str = "UV"; /// Equivalent to the `--offline` command-line argument. If set, uv will disable network access. #[attr_added_in("0.5.9")] pub const UV_OFFLINE: &'static str = "UV_OFFLINE"; /// Equivalent to the `--default-index` command-line argument. If set, uv will use /// this URL as the default index when searching for packages. #[attr_added_in("0.4.23")] pub const UV_DEFAULT_INDEX: &'static str = "UV_DEFAULT_INDEX"; /// Equivalent to the `--index` command-line argument. If set, uv will use this /// space-separated list of URLs as additional indexes when searching for packages. #[attr_added_in("0.4.23")] pub const UV_INDEX: &'static str = "UV_INDEX"; /// Equivalent to the `--index-url` command-line argument. If set, uv will use this /// URL as the default index when searching for packages. /// (Deprecated: use `UV_DEFAULT_INDEX` instead.) #[attr_added_in("0.0.5")] pub const UV_INDEX_URL: &'static str = "UV_INDEX_URL"; /// Equivalent to the `--extra-index-url` command-line argument. If set, uv will /// use this space-separated list of URLs as additional indexes when searching for packages. /// (Deprecated: use `UV_INDEX` instead.) #[attr_added_in("0.1.3")] pub const UV_EXTRA_INDEX_URL: &'static str = "UV_EXTRA_INDEX_URL"; /// Equivalent to the `--find-links` command-line argument. If set, uv will use this /// comma-separated list of additional locations to search for packages. #[attr_added_in("0.4.19")] pub const UV_FIND_LINKS: &'static str = "UV_FIND_LINKS"; /// Equivalent to the `--no-sources` command-line argument. If set, uv will ignore /// `[tool.uv.sources]` annotations when resolving dependencies. #[attr_added_in("0.9.8")] pub const UV_NO_SOURCES: &'static str = "UV_NO_SOURCES"; /// Equivalent to the `--cache-dir` command-line argument. If set, uv will use this /// directory for caching instead of the default cache directory. #[attr_added_in("0.0.5")] pub const UV_CACHE_DIR: &'static str = "UV_CACHE_DIR"; /// The directory for storage of credentials when using a plain text backend. #[attr_added_in("0.8.15")] pub const UV_CREDENTIALS_DIR: &'static str = "UV_CREDENTIALS_DIR"; /// Equivalent to the `--no-cache` command-line argument. If set, uv will not use the /// cache for any operations. #[attr_added_in("0.1.2")] pub const UV_NO_CACHE: &'static str = "UV_NO_CACHE"; /// Equivalent to the `--resolution` command-line argument. For example, if set to /// `lowest-direct`, uv will install the lowest compatible versions of all direct dependencies. #[attr_added_in("0.1.27")] pub const UV_RESOLUTION: &'static str = "UV_RESOLUTION"; /// Equivalent to the `--prerelease` command-line argument. For example, if set to /// `allow`, uv will allow pre-release versions for all dependencies. #[attr_added_in("0.1.16")] pub const UV_PRERELEASE: &'static str = "UV_PRERELEASE"; /// Equivalent to the `--fork-strategy` argument. Controls version selection during universal /// resolution. #[attr_added_in("0.5.9")] pub const UV_FORK_STRATEGY: &'static str = "UV_FORK_STRATEGY"; /// Equivalent to the `--system` command-line argument. If set to `true`, uv will /// use the first Python interpreter found in the system `PATH`. /// /// WARNING: `UV_SYSTEM_PYTHON=true` is intended for use in continuous integration (CI) /// or containerized environments and should be used with caution, as modifying the system /// Python can lead to unexpected behavior. #[attr_added_in("0.1.18")] pub const UV_SYSTEM_PYTHON: &'static str = "UV_SYSTEM_PYTHON"; /// Equivalent to the `--python` command-line argument. If set to a path, uv will use /// this Python interpreter for all operations. #[attr_added_in("0.1.40")] pub const UV_PYTHON: &'static str = "UV_PYTHON"; /// Equivalent to the `--break-system-packages` command-line argument. If set to `true`, /// uv will allow the installation of packages that conflict with system-installed packages. /// /// WARNING: `UV_BREAK_SYSTEM_PACKAGES=true` is intended for use in continuous integration /// (CI) or containerized environments and should be used with caution, as modifying the system /// Python can lead to unexpected behavior. #[attr_added_in("0.1.32")] pub const UV_BREAK_SYSTEM_PACKAGES: &'static str = "UV_BREAK_SYSTEM_PACKAGES"; /// Equivalent to the `--native-tls` command-line argument. If set to `true`, uv will /// use the system's trust store instead of the bundled `webpki-roots` crate. #[attr_added_in("0.1.19")] pub const UV_NATIVE_TLS: &'static str = "UV_NATIVE_TLS"; /// Equivalent to the `--index-strategy` command-line argument. /// /// For example, if set to `unsafe-best-match`, uv will consider versions of a given package /// available across all index URLs, rather than limiting its search to the first index URL /// that contains the package. #[attr_added_in("0.1.29")] pub const UV_INDEX_STRATEGY: &'static str = "UV_INDEX_STRATEGY"; /// Equivalent to the `--require-hashes` command-line argument. If set to `true`, /// uv will require that all dependencies have a hash specified in the requirements file. #[attr_added_in("0.1.34")] pub const UV_REQUIRE_HASHES: &'static str = "UV_REQUIRE_HASHES"; /// Equivalent to the `--constraints` command-line argument. If set, uv will use this /// file as the constraints file. Uses space-separated list of files. #[attr_added_in("0.1.36")] pub const UV_CONSTRAINT: &'static str = "UV_CONSTRAINT"; /// Equivalent to the `--build-constraints` command-line argument. If set, uv will use this file /// as constraints for any source distribution builds. Uses space-separated list of files. #[attr_added_in("0.2.34")] pub const UV_BUILD_CONSTRAINT: &'static str = "UV_BUILD_CONSTRAINT"; /// Equivalent to the `--overrides` command-line argument. If set, uv will use this file /// as the overrides file. Uses space-separated list of files. #[attr_added_in("0.2.22")] pub const UV_OVERRIDE: &'static str = "UV_OVERRIDE"; /// Equivalent to the `--excludes` command-line argument. If set, uv will use this /// as the excludes file. Uses space-separated list of files. #[attr_added_in("0.9.8")] pub const UV_EXCLUDE: &'static str = "UV_EXCLUDE"; /// Equivalent to the `--link-mode` command-line argument. If set, uv will use this as /// a link mode. #[attr_added_in("0.1.40")] pub const UV_LINK_MODE: &'static str = "UV_LINK_MODE"; /// Equivalent to the `--no-build-isolation` command-line argument. If set, uv will /// skip isolation when building source distributions. #[attr_added_in("0.1.40")] pub const UV_NO_BUILD_ISOLATION: &'static str = "UV_NO_BUILD_ISOLATION"; /// Equivalent to the `--custom-compile-command` command-line argument. /// /// Used to override uv in the output header of the `requirements.txt` files generated by /// `uv pip compile`. Intended for use-cases in which `uv pip compile` is called from within a wrapper /// script, to include the name of the wrapper script in the output file. #[attr_added_in("0.1.23")] pub const UV_CUSTOM_COMPILE_COMMAND: &'static str = "UV_CUSTOM_COMPILE_COMMAND"; /// Equivalent to the `--keyring-provider` command-line argument. If set, uv /// will use this value as the keyring provider. #[attr_added_in("0.1.19")] pub const UV_KEYRING_PROVIDER: &'static str = "UV_KEYRING_PROVIDER"; /// Equivalent to the `--config-file` command-line argument. Expects a path to a /// local `uv.toml` file to use as the configuration file. #[attr_added_in("0.1.34")] pub const UV_CONFIG_FILE: &'static str = "UV_CONFIG_FILE"; /// Equivalent to the `--no-config` command-line argument. If set, uv will not read /// any configuration files from the current directory, parent directories, or user configuration /// directories. #[attr_added_in("0.2.30")] pub const UV_NO_CONFIG: &'static str = "UV_NO_CONFIG"; /// Equivalent to the `--isolated` command-line argument. If set, uv will avoid discovering /// a `pyproject.toml` or `uv.toml` file. #[attr_added_in("0.8.14")] pub const UV_ISOLATED: &'static str = "UV_ISOLATED"; /// Equivalent to the `--exclude-newer` command-line argument. If set, uv will /// exclude distributions published after the specified date. #[attr_added_in("0.2.12")] pub const UV_EXCLUDE_NEWER: &'static str = "UV_EXCLUDE_NEWER"; /// Whether uv should prefer system or managed Python versions. #[attr_added_in("0.3.2")] pub const UV_PYTHON_PREFERENCE: &'static str = "UV_PYTHON_PREFERENCE"; /// Require use of uv-managed Python versions. #[attr_added_in("0.6.8")] pub const UV_MANAGED_PYTHON: &'static str = "UV_MANAGED_PYTHON"; /// Disable use of uv-managed Python versions. #[attr_added_in("0.6.8")] pub const UV_NO_MANAGED_PYTHON: &'static str = "UV_NO_MANAGED_PYTHON"; /// Equivalent to the /// [`python-downloads`](../reference/settings.md#python-downloads) setting and, when disabled, the /// `--no-python-downloads` option. Whether uv should allow Python downloads. #[attr_added_in("0.3.2")] pub const UV_PYTHON_DOWNLOADS: &'static str = "UV_PYTHON_DOWNLOADS"; /// Overrides the environment-determined libc on linux systems when filling in the current platform /// within Python version requests. Options are: `gnu`, `gnueabi`, `gnueabihf`, `musl`, and `none`. #[attr_added_in("0.7.22")] pub const UV_LIBC: &'static str = "UV_LIBC"; /// Equivalent to the `--compile-bytecode` command-line argument. If set, uv /// will compile Python source files to bytecode after installation. #[attr_added_in("0.3.3")] pub const UV_COMPILE_BYTECODE: &'static str = "UV_COMPILE_BYTECODE"; /// Timeout (in seconds) for bytecode compilation. #[attr_added_in("0.7.22")] pub const UV_COMPILE_BYTECODE_TIMEOUT: &'static str = "UV_COMPILE_BYTECODE_TIMEOUT"; /// Equivalent to the `--no-editable` command-line argument. If set, uv /// installs or exports any editable dependencies, including the project and any workspace /// members, as non-editable. #[attr_added_in("0.6.15")] pub const UV_NO_EDITABLE: &'static str = "UV_NO_EDITABLE"; /// Equivalent to the `--dev` command-line argument. If set, uv will include /// development dependencies. #[attr_added_in("0.8.7")] pub const UV_DEV: &'static str = "UV_DEV"; /// Equivalent to the `--no-dev` command-line argument. If set, uv will exclude /// development dependencies. #[attr_added_in("0.8.7")] pub const UV_NO_DEV: &'static str = "UV_NO_DEV"; /// Equivalent to the `--no-group` command-line argument. If set, uv will disable /// the specified dependency groups for the given space-delimited list of packages. #[attr_added_in("0.9.8")] pub const UV_NO_GROUP: &'static str = "UV_NO_GROUP"; /// Equivalent to the `--no-default-groups` command-line argument. If set, uv will /// not select the default dependency groups defined in `tool.uv.default-groups`. #[attr_added_in("0.9.9")] pub const UV_NO_DEFAULT_GROUPS: &'static str = "UV_NO_DEFAULT_GROUPS"; /// Equivalent to the `--no-binary` command-line argument. If set, uv will install /// all packages from source. The resolver will still use pre-built wheels to /// extract package metadata, if available. #[attr_added_in("0.5.30")] pub const UV_NO_BINARY: &'static str = "UV_NO_BINARY"; /// Equivalent to the `--no-binary-package` command line argument. If set, uv will /// not use pre-built wheels for the given space-delimited list of packages. #[attr_added_in("0.5.30")] pub const UV_NO_BINARY_PACKAGE: &'static str = "UV_NO_BINARY_PACKAGE"; /// Equivalent to the `--no-build` command-line argument. If set, uv will not build /// source distributions. #[attr_added_in("0.1.40")] pub const UV_NO_BUILD: &'static str = "UV_NO_BUILD"; /// Equivalent to the `--no-build-package` command line argument. If set, uv will /// not build source distributions for the given space-delimited list of packages. #[attr_added_in("0.6.5")] pub const UV_NO_BUILD_PACKAGE: &'static str = "UV_NO_BUILD_PACKAGE"; /// Equivalent to the `--publish-url` command-line argument. The URL of the upload /// endpoint of the index to use with `uv publish`. #[attr_added_in("0.4.16")] pub const UV_PUBLISH_URL: &'static str = "UV_PUBLISH_URL"; /// Equivalent to the `--token` command-line argument in `uv publish`. If set, uv /// will use this token (with the username `__token__`) for publishing. #[attr_added_in("0.4.16")] pub const UV_PUBLISH_TOKEN: &'static str = "UV_PUBLISH_TOKEN"; /// Equivalent to the `--index` command-line argument in `uv publish`. If /// set, uv the index with this name in the configuration for publishing. #[attr_added_in("0.5.8")] pub const UV_PUBLISH_INDEX: &'static str = "UV_PUBLISH_INDEX"; /// Equivalent to the `--username` command-line argument in `uv publish`. If /// set, uv will use this username for publishing. #[attr_added_in("0.4.16")] pub const UV_PUBLISH_USERNAME: &'static str = "UV_PUBLISH_USERNAME"; /// Equivalent to the `--password` command-line argument in `uv publish`. If /// set, uv will use this password for publishing. #[attr_added_in("0.4.16")] pub const UV_PUBLISH_PASSWORD: &'static str = "UV_PUBLISH_PASSWORD"; /// Don't upload a file if it already exists on the index. The value is the URL of the index. #[attr_added_in("0.4.30")] pub const UV_PUBLISH_CHECK_URL: &'static str = "UV_PUBLISH_CHECK_URL"; /// Equivalent to the `--no-attestations` command-line argument in `uv publish`. If set, /// uv will skip uploading any collected attestations for the published distributions. #[attr_added_in("0.9.12")] pub const UV_PUBLISH_NO_ATTESTATIONS: &'static str = "UV_PUBLISH_NO_ATTESTATIONS"; /// Equivalent to the `--no-sync` command-line argument. If set, uv will skip updating /// the environment. #[attr_added_in("0.4.18")] pub const UV_NO_SYNC: &'static str = "UV_NO_SYNC"; /// Equivalent to the `--locked` command-line argument. If set, uv will assert that the /// `uv.lock` remains unchanged. #[attr_added_in("0.4.25")] pub const UV_LOCKED: &'static str = "UV_LOCKED"; /// Equivalent to the `--frozen` command-line argument. If set, uv will run without /// updating the `uv.lock` file. #[attr_added_in("0.4.25")] pub const UV_FROZEN: &'static str = "UV_FROZEN"; /// Equivalent to the `--preview` argument. Enables preview mode. #[attr_added_in("0.1.37")] pub const UV_PREVIEW: &'static str = "UV_PREVIEW"; /// Equivalent to the `--preview-features` argument. Enables specific preview features. #[attr_added_in("0.8.4")] pub const UV_PREVIEW_FEATURES: &'static str = "UV_PREVIEW_FEATURES"; /// Equivalent to the `--token` argument for self update. A GitHub token for authentication. #[attr_added_in("0.4.10")] pub const UV_GITHUB_TOKEN: &'static str = "UV_GITHUB_TOKEN"; /// Equivalent to the `--no-verify-hashes` argument. Disables hash verification for /// `requirements.txt` files. #[attr_added_in("0.5.3")] pub const UV_NO_VERIFY_HASHES: &'static str = "UV_NO_VERIFY_HASHES"; /// Equivalent to the `--allow-insecure-host` argument. #[attr_added_in("0.3.5")] pub const UV_INSECURE_HOST: &'static str = "UV_INSECURE_HOST"; /// Disable ZIP validation for streamed wheels and ZIP-based source distributions. /// /// WARNING: Disabling ZIP validation can expose your system to security risks by bypassing /// integrity checks and allowing uv to install potentially malicious ZIP files. If uv rejects /// a ZIP file due to failing validation, it is likely that the file is malformed; consider /// filing an issue with the package maintainer. #[attr_added_in("0.8.6")] pub const UV_INSECURE_NO_ZIP_VALIDATION: &'static str = "UV_INSECURE_NO_ZIP_VALIDATION"; /// Sets the maximum number of in-flight concurrent downloads that uv will /// perform at any given time. #[attr_added_in("0.1.43")] pub const UV_CONCURRENT_DOWNLOADS: &'static str = "UV_CONCURRENT_DOWNLOADS"; /// Sets the maximum number of source distributions that uv will build /// concurrently at any given time. #[attr_added_in("0.1.43")] pub const UV_CONCURRENT_BUILDS: &'static str = "UV_CONCURRENT_BUILDS"; /// Controls the number of threads used when installing and unzipping /// packages. #[attr_added_in("0.1.45")] pub const UV_CONCURRENT_INSTALLS: &'static str = "UV_CONCURRENT_INSTALLS"; /// Equivalent to the `--no-progress` command-line argument. Disables all progress output. For /// example, spinners and progress bars. #[attr_added_in("0.2.28")] pub const UV_NO_PROGRESS: &'static str = "UV_NO_PROGRESS"; /// Specifies the directory where uv stores managed tools. #[attr_added_in("0.2.16")] pub const UV_TOOL_DIR: &'static str = "UV_TOOL_DIR"; /// Specifies the "bin" directory for installing tool executables. #[attr_added_in("0.3.0")] pub const UV_TOOL_BIN_DIR: &'static str = "UV_TOOL_BIN_DIR"; /// Equivalent to the `--build-backend` argument for `uv init`. Determines the default backend /// to use when creating a new project. #[attr_added_in("0.8.2")] pub const UV_INIT_BUILD_BACKEND: &'static str = "UV_INIT_BUILD_BACKEND"; /// Specifies the path to the directory to use for a project virtual environment. /// /// See the [project documentation](../concepts/projects/config.md#project-environment-path) /// for more details. #[attr_added_in("0.4.4")] pub const UV_PROJECT_ENVIRONMENT: &'static str = "UV_PROJECT_ENVIRONMENT"; /// Specifies the directory to place links to installed, managed Python executables. #[attr_added_in("0.4.29")] pub const UV_PYTHON_BIN_DIR: &'static str = "UV_PYTHON_BIN_DIR"; /// Specifies the directory for storing managed Python installations. #[attr_added_in("0.2.22")] pub const UV_PYTHON_INSTALL_DIR: &'static str = "UV_PYTHON_INSTALL_DIR"; /// Whether to install the Python executable into the `UV_PYTHON_BIN_DIR` directory. #[attr_added_in("0.8.0")] pub const UV_PYTHON_INSTALL_BIN: &'static str = "UV_PYTHON_INSTALL_BIN"; /// Whether to install the Python executable into the Windows registry. #[attr_added_in("0.8.0")] pub const UV_PYTHON_INSTALL_REGISTRY: &'static str = "UV_PYTHON_INSTALL_REGISTRY"; /// Managed Python installations information is hardcoded in the `uv` binary. /// /// This variable can be set to a local path or URL pointing to /// a JSON list of Python installations to override the hardcoded list. /// /// This allows customizing the URLs for downloads or using slightly older or newer versions /// of Python than the ones hardcoded into this build of `uv`. #[attr_added_in("0.6.13")] pub const UV_PYTHON_DOWNLOADS_JSON_URL: &'static str = "UV_PYTHON_DOWNLOADS_JSON_URL"; /// Specifies the directory for caching the archives of managed Python installations before /// installation. #[attr_added_in("0.7.0")] pub const UV_PYTHON_CACHE_DIR: &'static str = "UV_PYTHON_CACHE_DIR"; /// Managed Python installations are downloaded from the Astral /// [`python-build-standalone`](https://github.com/astral-sh/python-build-standalone) project. /// /// This variable can be set to a mirror URL to use a different source for Python installations. /// The provided URL will replace `https://github.com/astral-sh/python-build-standalone/releases/download` in, e.g., /// `https://github.com/astral-sh/python-build-standalone/releases/download/20240713/cpython-3.12.4%2B20240713-aarch64-apple-darwin-install_only.tar.gz`. /// Distributions can be read from a local directory by using the `file://` URL scheme. #[attr_added_in("0.2.35")] pub const UV_PYTHON_INSTALL_MIRROR: &'static str = "UV_PYTHON_INSTALL_MIRROR"; /// Managed PyPy installations are downloaded from [python.org](https://downloads.python.org/). /// /// This variable can be set to a mirror URL to use a /// different source for PyPy installations. The provided URL will replace /// `https://downloads.python.org/pypy` in, e.g., /// `https://downloads.python.org/pypy/pypy3.8-v7.3.7-osx64.tar.bz2`. /// Distributions can be read from a local directory by using the `file://` URL scheme. #[attr_added_in("0.2.35")] pub const UV_PYPY_INSTALL_MIRROR: &'static str = "UV_PYPY_INSTALL_MIRROR"; /// Pin managed CPython versions to a specific build version. /// /// For CPython, this should be the build date (e.g., "20250814"). #[attr_added_in("0.8.14")] pub const UV_PYTHON_CPYTHON_BUILD: &'static str = "UV_PYTHON_CPYTHON_BUILD"; /// Pin managed PyPy versions to a specific build version. /// /// For PyPy, this should be the PyPy version (e.g., "7.3.20"). #[attr_added_in("0.8.14")] pub const UV_PYTHON_PYPY_BUILD: &'static str = "UV_PYTHON_PYPY_BUILD"; /// Pin managed GraalPy versions to a specific build version. /// /// For GraalPy, this should be the GraalPy version (e.g., "24.2.2"). #[attr_added_in("0.8.14")] pub const UV_PYTHON_GRAALPY_BUILD: &'static str = "UV_PYTHON_GRAALPY_BUILD"; /// Pin managed Pyodide versions to a specific build version. /// /// For Pyodide, this should be the Pyodide version (e.g., "0.28.1"). #[attr_added_in("0.8.14")] pub const UV_PYTHON_PYODIDE_BUILD: &'static str = "UV_PYTHON_PYODIDE_BUILD"; /// Equivalent to the `--clear` command-line argument. If set, uv will remove any /// existing files or directories at the target path. #[attr_added_in("0.8.0")] pub const UV_VENV_CLEAR: &'static str = "UV_VENV_CLEAR"; /// Install seed packages (one or more of: `pip`, `setuptools`, and `wheel`) into the virtual environment /// created by `uv venv`. /// /// Note that `setuptools` and `wheel` are not included in Python 3.12+ environments. #[attr_added_in("0.5.21")] pub const UV_VENV_SEED: &'static str = "UV_VENV_SEED"; /// Used to override `PATH` to limit Python executable availability in the test suite. #[attr_hidden] #[attr_added_in("0.0.5")] pub const UV_TEST_PYTHON_PATH: &'static str = "UV_TEST_PYTHON_PATH"; /// Include resolver and installer output related to environment modifications. #[attr_hidden] #[attr_added_in("0.2.32")] pub const UV_SHOW_RESOLUTION: &'static str = "UV_SHOW_RESOLUTION"; /// Use to update the json schema files. #[attr_hidden] #[attr_added_in("0.1.34")] pub const UV_UPDATE_SCHEMA: &'static str = "UV_UPDATE_SCHEMA"; /// Use to disable line wrapping for diagnostics. #[attr_added_in("0.0.5")] pub const UV_NO_WRAP: &'static str = "UV_NO_WRAP"; /// Provides the HTTP Basic authentication username for a named index. /// /// The `name` parameter is the name of the index. For example, given an index named `foo`, /// the environment variable key would be `UV_INDEX_FOO_USERNAME`. #[attr_added_in("0.4.23")] #[attr_env_var_pattern("UV_INDEX_{name}_USERNAME")] pub fn index_username(name: &str) -> String { format!("UV_INDEX_{name}_USERNAME") } /// Provides the HTTP Basic authentication password for a named index. /// /// The `name` parameter is the name of the index. For example, given an index named `foo`, /// the environment variable key would be `UV_INDEX_FOO_PASSWORD`. #[attr_added_in("0.4.23")] #[attr_env_var_pattern("UV_INDEX_{name}_PASSWORD")] pub fn index_password(name: &str) -> String { format!("UV_INDEX_{name}_PASSWORD") } /// Used to set the uv commit hash at build time via `build.rs`. #[attr_hidden] #[attr_added_in("0.1.11")] pub const UV_COMMIT_HASH: &'static str = "UV_COMMIT_HASH"; /// Used to set the uv commit short hash at build time via `build.rs`. #[attr_hidden] #[attr_added_in("0.1.11")] pub const UV_COMMIT_SHORT_HASH: &'static str = "UV_COMMIT_SHORT_HASH"; /// Used to set the uv commit date at build time via `build.rs`. #[attr_hidden] #[attr_added_in("0.1.11")] pub const UV_COMMIT_DATE: &'static str = "UV_COMMIT_DATE"; /// Used to set the uv tag at build time via `build.rs`. #[attr_hidden] #[attr_added_in("0.1.11")] pub const UV_LAST_TAG: &'static str = "UV_LAST_TAG"; /// Used to set the uv tag distance from head at build time via `build.rs`. #[attr_hidden] #[attr_added_in("0.1.11")] pub const UV_LAST_TAG_DISTANCE: &'static str = "UV_LAST_TAG_DISTANCE"; /// Used to set the spawning/parent interpreter when using --system in the test suite. #[attr_hidden] #[attr_added_in("0.2.0")] pub const UV_INTERNAL__PARENT_INTERPRETER: &'static str = "UV_INTERNAL__PARENT_INTERPRETER"; /// Used to force showing the derivation tree during resolver error reporting. #[attr_hidden] #[attr_added_in("0.3.0")] pub const UV_INTERNAL__SHOW_DERIVATION_TREE: &'static str = "UV_INTERNAL__SHOW_DERIVATION_TREE"; /// Used to set a temporary directory for some tests. #[attr_hidden] #[attr_added_in("0.3.4")] pub const UV_INTERNAL__TEST_DIR: &'static str = "UV_INTERNAL__TEST_DIR"; /// Used to force treating an interpreter as "managed" during tests. #[attr_hidden] #[attr_added_in("0.8.0")] pub const UV_INTERNAL__TEST_PYTHON_MANAGED: &'static str = "UV_INTERNAL__TEST_PYTHON_MANAGED"; /// Used to force ignoring Git LFS commands as `git-lfs` detection cannot be overridden via PATH. #[attr_hidden] #[attr_added_in("0.9.15")] pub const UV_INTERNAL__TEST_LFS_DISABLED: &'static str = "UV_INTERNAL__TEST_LFS_DISABLED"; /// Path to system-level configuration directory on Unix systems. #[attr_added_in("0.4.26")] pub const XDG_CONFIG_DIRS: &'static str = "XDG_CONFIG_DIRS"; /// Path to system-level configuration directory on Windows systems. #[attr_added_in("0.4.26")] pub const SYSTEMDRIVE: &'static str = "SYSTEMDRIVE"; /// Path to user-level configuration directory on Windows systems. #[attr_added_in("0.1.42")] pub const APPDATA: &'static str = "APPDATA"; /// Path to root directory of user's profile on Windows systems. #[attr_added_in("0.0.5")] pub const USERPROFILE: &'static str = "USERPROFILE"; /// Path to user-level configuration directory on Unix systems. #[attr_added_in("0.1.34")] pub const XDG_CONFIG_HOME: &'static str = "XDG_CONFIG_HOME"; /// Path to cache directory on Unix systems. #[attr_added_in("0.1.17")] pub const XDG_CACHE_HOME: &'static str = "XDG_CACHE_HOME"; /// Path to directory for storing managed Python installations and tools. #[attr_added_in("0.2.16")] pub const XDG_DATA_HOME: &'static str = "XDG_DATA_HOME"; /// Path to directory where executables are installed. #[attr_added_in("0.2.16")] pub const XDG_BIN_HOME: &'static str = "XDG_BIN_HOME"; /// Custom certificate bundle file path for SSL connections. /// /// Takes precedence over `UV_NATIVE_TLS` when set. #[attr_added_in("0.1.14")] pub const SSL_CERT_FILE: &'static str = "SSL_CERT_FILE"; /// Custom path for certificate bundles for SSL connections. /// Multiple entries are supported separated using a platform-specific /// delimiter (`:` on Unix, `;` on Windows). /// /// Takes precedence over `UV_NATIVE_TLS` when set. #[attr_added_in("0.9.10")] pub const SSL_CERT_DIR: &'static str = "SSL_CERT_DIR"; /// If set, uv will use this file for mTLS authentication. /// This should be a single file containing both the certificate and the private key in PEM format. #[attr_added_in("0.2.11")] pub const SSL_CLIENT_CERT: &'static str = "SSL_CLIENT_CERT"; /// Proxy for HTTP requests. #[attr_added_in("0.1.38")] pub const HTTP_PROXY: &'static str = "HTTP_PROXY"; /// Proxy for HTTPS requests. #[attr_added_in("0.1.38")] pub const HTTPS_PROXY: &'static str = "HTTPS_PROXY"; /// General proxy for all network requests. #[attr_added_in("0.1.38")] pub const ALL_PROXY: &'static str = "ALL_PROXY"; /// Comma-separated list of hostnames (e.g., `example.com`) and/or patterns (e.g., `192.168.1.0/24`) that should bypass the proxy. #[attr_added_in("0.1.38")] pub const NO_PROXY: &'static str = "NO_PROXY"; /// Timeout (in seconds) for only upload HTTP requests. (default: 900 s) #[attr_added_in("0.9.1")] pub const UV_UPLOAD_HTTP_TIMEOUT: &'static str = "UV_UPLOAD_HTTP_TIMEOUT"; /// Timeout (in seconds) for HTTP requests. (default: 30 s) #[attr_added_in("0.1.7")] pub const UV_HTTP_TIMEOUT: &'static str = "UV_HTTP_TIMEOUT"; /// The number of retries for HTTP requests. (default: 3) #[attr_added_in("0.7.21")] pub const UV_HTTP_RETRIES: &'static str = "UV_HTTP_RETRIES"; /// Timeout (in seconds) for HTTP requests. Equivalent to `UV_HTTP_TIMEOUT`. #[attr_added_in("0.1.6")] pub const UV_REQUEST_TIMEOUT: &'static str = "UV_REQUEST_TIMEOUT"; /// Timeout (in seconds) for HTTP requests. Equivalent to `UV_HTTP_TIMEOUT`. #[attr_added_in("0.1.7")] pub const HTTP_TIMEOUT: &'static str = "HTTP_TIMEOUT"; /// The validation modes to use when run with `--compile`. /// /// See [`PycInvalidationMode`](https://docs.python.org/3/library/py_compile.html#py_compile.PycInvalidationMode). #[attr_added_in("0.1.7")] pub const PYC_INVALIDATION_MODE: &'static str = "PYC_INVALIDATION_MODE"; /// Used to detect an activated virtual environment. #[attr_added_in("0.0.5")] pub const VIRTUAL_ENV: &'static str = "VIRTUAL_ENV"; /// Used to detect the path of an active Conda environment. #[attr_added_in("0.0.5")] pub const CONDA_PREFIX: &'static str = "CONDA_PREFIX"; /// Used to determine the name of the active Conda environment. #[attr_added_in("0.5.0")] pub const CONDA_DEFAULT_ENV: &'static str = "CONDA_DEFAULT_ENV"; /// Used to determine the root install path of Conda. #[attr_added_in("0.8.18")] pub const CONDA_ROOT: &'static str = "_CONDA_ROOT"; /// Used to determine if we're running in Dependabot. #[attr_added_in("0.9.11")] pub const DEPENDABOT: &'static str = "DEPENDABOT"; /// If set to `1` before a virtual environment is activated, then the /// virtual environment name will not be prepended to the terminal prompt. #[attr_added_in("0.0.5")] pub const VIRTUAL_ENV_DISABLE_PROMPT: &'static str = "VIRTUAL_ENV_DISABLE_PROMPT"; /// Used to detect the use of the Windows Command Prompt (as opposed to PowerShell). #[attr_added_in("0.1.16")] pub const PROMPT: &'static str = "PROMPT"; /// Used to detect `NuShell` usage. #[attr_added_in("0.1.16")] pub const NU_VERSION: &'static str = "NU_VERSION"; /// Used to detect Fish shell usage. #[attr_added_in("0.1.28")] pub const FISH_VERSION: &'static str = "FISH_VERSION"; /// Used to detect Bash shell usage. #[attr_added_in("0.1.28")] pub const BASH_VERSION: &'static str = "BASH_VERSION"; /// Used to detect Zsh shell usage. #[attr_added_in("0.1.28")] pub const ZSH_VERSION: &'static str = "ZSH_VERSION";
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git-types/src/reference.rs
crates/uv-git-types/src/reference.rs
use std::fmt::Display; use std::str; /// A reference to commit or commit-ish. #[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub enum GitReference { /// A specific branch. Branch(String), /// A specific tag. Tag(String), /// From a reference that's ambiguously a branch or tag. BranchOrTag(String), /// From a reference that's ambiguously a commit, branch, or tag. BranchOrTagOrCommit(String), /// From a named reference, like `refs/pull/493/head`. NamedRef(String), /// The default branch of the repository, the reference named `HEAD`. DefaultBranch, } impl GitReference { /// Creates a [`GitReference`] from an arbitrary revision string, which could represent a /// branch, tag, commit, or named ref. pub fn from_rev(rev: String) -> Self { if rev.starts_with("refs/") { Self::NamedRef(rev) } else if looks_like_commit_hash(&rev) { Self::BranchOrTagOrCommit(rev) } else { Self::BranchOrTag(rev) } } /// Converts the [`GitReference`] to a `str`. pub fn as_str(&self) -> Option<&str> { match self { Self::Tag(rev) => Some(rev), Self::Branch(rev) => Some(rev), Self::BranchOrTag(rev) => Some(rev), Self::BranchOrTagOrCommit(rev) => Some(rev), Self::NamedRef(rev) => Some(rev), Self::DefaultBranch => None, } } /// Converts the [`GitReference`] to a `str` that can be used as a revision. pub fn as_rev(&self) -> &str { match self { Self::Tag(rev) => rev, Self::Branch(rev) => rev, Self::BranchOrTag(rev) => rev, Self::BranchOrTagOrCommit(rev) => rev, Self::NamedRef(rev) => rev, Self::DefaultBranch => "HEAD", } } /// Returns the kind of this reference. pub fn kind_str(&self) -> &str { match self { Self::Branch(_) => "branch", Self::Tag(_) => "tag", Self::BranchOrTag(_) => "branch or tag", Self::BranchOrTagOrCommit(_) => "branch, tag, or commit", Self::NamedRef(_) => "ref", Self::DefaultBranch => "default branch", } } } impl Display for GitReference { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str().unwrap_or("HEAD")) } } /// Whether a `rev` looks like a commit hash (ASCII hex digits). fn looks_like_commit_hash(rev: &str) -> bool { rev.len() >= 7 && rev.chars().all(|ch| ch.is_ascii_hexdigit()) }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git-types/src/lib.rs
crates/uv-git-types/src/lib.rs
pub use crate::github::GitHubRepository; pub use crate::oid::{GitOid, OidParseError}; pub use crate::reference::GitReference; use std::sync::LazyLock; use thiserror::Error; use uv_redacted::DisplaySafeUrl; use uv_static::EnvVars; mod github; mod oid; mod reference; /// Initialize [`GitLfs`] mode from `UV_GIT_LFS` environment. pub static UV_GIT_LFS: LazyLock<GitLfs> = LazyLock::new(|| { // TODO(konsti): Parse this in `EnvironmentOptions`. if std::env::var_os(EnvVars::UV_GIT_LFS) .and_then(|v| v.to_str().map(str::to_lowercase)) .is_some_and(|v| matches!(v.as_str(), "y" | "yes" | "t" | "true" | "on" | "1")) { GitLfs::Enabled } else { GitLfs::Disabled } }); /// Configuration for Git LFS (Large File Storage) support. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)] pub enum GitLfs { /// Git LFS is disabled (default). #[default] Disabled, /// Git LFS is enabled. Enabled, } impl GitLfs { /// Create a `GitLfs` configuration from environment variables. pub fn from_env() -> Self { *UV_GIT_LFS } /// Returns true if LFS is enabled. pub fn enabled(self) -> bool { matches!(self, Self::Enabled) } } impl From<Option<bool>> for GitLfs { fn from(value: Option<bool>) -> Self { match value { Some(true) => Self::Enabled, Some(false) => Self::Disabled, None => Self::from_env(), } } } impl From<bool> for GitLfs { fn from(value: bool) -> Self { if value { Self::Enabled } else { Self::Disabled } } } impl std::fmt::Display for GitLfs { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Enabled => write!(f, "enabled"), Self::Disabled => write!(f, "disabled"), } } } #[derive(Debug, Error)] pub enum GitUrlParseError { #[error( "Unsupported Git URL scheme `{0}:` in `{1}` (expected one of `https:`, `ssh:`, or `file:`)" )] UnsupportedGitScheme(String, DisplaySafeUrl), } /// A URL reference to a Git repository. #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Hash, Ord)] pub struct GitUrl { /// The URL of the Git repository, with any query parameters, fragments, and leading `git+` /// removed. repository: DisplaySafeUrl, /// The reference to the commit to use, which could be a branch, tag or revision. reference: GitReference, /// The precise commit to use, if known. precise: Option<GitOid>, /// Git LFS configuration for this repository. lfs: GitLfs, } impl GitUrl { /// Create a new [`GitUrl`] from a repository URL and a reference. pub fn from_reference( repository: DisplaySafeUrl, reference: GitReference, lfs: GitLfs, ) -> Result<Self, GitUrlParseError> { Self::from_fields(repository, reference, None, lfs) } /// Create a new [`GitUrl`] from a repository URL and a precise commit. pub fn from_commit( repository: DisplaySafeUrl, reference: GitReference, precise: GitOid, lfs: GitLfs, ) -> Result<Self, GitUrlParseError> { Self::from_fields(repository, reference, Some(precise), lfs) } /// Create a new [`GitUrl`] from a repository URL and a precise commit, if known. pub fn from_fields( repository: DisplaySafeUrl, reference: GitReference, precise: Option<GitOid>, lfs: GitLfs, ) -> Result<Self, GitUrlParseError> { match repository.scheme() { "http" | "https" | "ssh" | "file" => {} unsupported => { return Err(GitUrlParseError::UnsupportedGitScheme( unsupported.to_string(), repository, )); } } Ok(Self { repository, reference, precise, lfs, }) } /// Set the precise [`GitOid`] to use for this Git URL. #[must_use] pub fn with_precise(mut self, precise: GitOid) -> Self { self.precise = Some(precise); self } /// Set the [`GitReference`] to use for this Git URL. #[must_use] pub fn with_reference(mut self, reference: GitReference) -> Self { self.reference = reference; self } /// Return the [`Url`] of the Git repository. pub fn repository(&self) -> &DisplaySafeUrl { &self.repository } /// Return the reference to the commit to use, which could be a branch, tag or revision. pub fn reference(&self) -> &GitReference { &self.reference } /// Return the precise commit, if known. pub fn precise(&self) -> Option<GitOid> { self.precise } /// Return the Git LFS configuration. pub fn lfs(&self) -> GitLfs { self.lfs } /// Set the Git LFS configuration. #[must_use] pub fn with_lfs(mut self, lfs: GitLfs) -> Self { self.lfs = lfs; self } } impl TryFrom<DisplaySafeUrl> for GitUrl { type Error = GitUrlParseError; /// Initialize a [`GitUrl`] source from a URL. fn try_from(mut url: DisplaySafeUrl) -> Result<Self, Self::Error> { // Remove any query parameters and fragments. url.set_fragment(None); url.set_query(None); // If the URL ends with a reference, like `https://git.example.com/MyProject.git@v1.0`, // extract it. let mut reference = GitReference::DefaultBranch; if let Some((prefix, suffix)) = url .path() .rsplit_once('@') .map(|(prefix, suffix)| (prefix.to_string(), suffix.to_string())) { reference = GitReference::from_rev(suffix); url.set_path(&prefix); } // TODO(samypr100): GitLfs::from_env() for now unless we want to support parsing lfs=true Self::from_reference(url, reference, GitLfs::from_env()) } } impl From<GitUrl> for DisplaySafeUrl { fn from(git: GitUrl) -> Self { let mut url = git.repository; // If we have a precise commit, add `@` and the commit hash to the URL. if let Some(precise) = git.precise { let path = format!("{}@{}", url.path(), precise); url.set_path(&path); } else { // Otherwise, add the branch or tag name. match git.reference { GitReference::Branch(rev) | GitReference::Tag(rev) | GitReference::BranchOrTag(rev) | GitReference::NamedRef(rev) | GitReference::BranchOrTagOrCommit(rev) => { let path = format!("{}@{}", url.path(), rev); url.set_path(&path); } GitReference::DefaultBranch => {} } } url } } impl std::fmt::Display for GitUrl { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", &self.repository) } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git-types/src/oid.rs
crates/uv-git-types/src/oid.rs
use std::fmt::{Display, Formatter}; use std::str::{self, FromStr}; use thiserror::Error; /// Unique identity of any Git object (commit, tree, blob, tag). /// /// This type's `FromStr` implementation validates that it's exactly 40 hex characters, i.e. a /// full-length git commit. /// /// If Git's SHA-256 support becomes more widespread in the future (in particular if GitHub ever /// adds support), we might need to make this an enum. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct GitOid { bytes: [u8; 40], } impl GitOid { /// Return the string representation of an object ID. pub fn as_str(&self) -> &str { str::from_utf8(&self.bytes).unwrap() } /// Return a truncated representation, i.e., the first 16 characters of the SHA. pub fn as_short_str(&self) -> &str { &self.as_str()[..16] } /// Return a (very) truncated representation, i.e., the first 8 characters of the SHA. pub fn as_tiny_str(&self) -> &str { &self.as_str()[..8] } } #[derive(Debug, Error, PartialEq)] pub enum OidParseError { #[error("Object ID cannot be parsed from empty string")] Empty, #[error("Object ID must be exactly 40 hex characters")] WrongLength, #[error("Object ID must be valid hex characters")] NotHex, } impl FromStr for GitOid { type Err = OidParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.is_empty() { return Err(OidParseError::Empty); } if s.len() != 40 { return Err(OidParseError::WrongLength); } if !s.chars().all(|ch| ch.is_ascii_hexdigit()) { return Err(OidParseError::NotHex); } let mut bytes = [0; 40]; bytes.copy_from_slice(s.as_bytes()); Ok(Self { bytes }) } } impl Display for GitOid { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.as_str()) } } impl serde::Serialize for GitOid { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.as_str().serialize(serializer) } } impl<'de> serde::Deserialize<'de> for GitOid { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct Visitor; impl serde::de::Visitor<'_> for Visitor { type Value = GitOid; fn expecting(&self, f: &mut Formatter) -> std::fmt::Result { f.write_str("a string") } fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> { GitOid::from_str(v).map_err(serde::de::Error::custom) } } deserializer.deserialize_str(Visitor) } } #[cfg(test)] mod tests { use std::str::FromStr; use super::{GitOid, OidParseError}; #[test] fn git_oid() { GitOid::from_str("4a23745badf5bf5ef7928f1e346e9986bd696d82").unwrap(); GitOid::from_str("4A23745BADF5BF5EF7928F1E346E9986BD696D82").unwrap(); assert_eq!(GitOid::from_str(""), Err(OidParseError::Empty)); assert_eq!( GitOid::from_str(&str::repeat("a", 41)), Err(OidParseError::WrongLength) ); assert_eq!( GitOid::from_str(&str::repeat("a", 39)), Err(OidParseError::WrongLength) ); assert_eq!( GitOid::from_str(&str::repeat("x", 40)), Err(OidParseError::NotHex) ); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-git-types/src/github.rs
crates/uv-git-types/src/github.rs
use tracing::debug; use url::Url; /// A reference to a repository on GitHub. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct GitHubRepository<'a> { /// The `owner` field for the repository, i.e., the user or organization that owns the /// repository, like `astral-sh`. pub owner: &'a str, /// The `repo` field for the repository, i.e., the name of the repository, like `uv`. pub repo: &'a str, } impl<'a> GitHubRepository<'a> { /// Parse a GitHub repository from a URL. /// /// Expects to receive a URL of the form: `https://github.com/{user}/{repo}[.git]`, e.g., /// `https://github.com/astral-sh/uv`. Otherwise, returns `None`. pub fn parse(url: &'a Url) -> Option<Self> { // The fast path is only available for GitHub repositories. if url.host_str() != Some("github.com") { return None; } // The GitHub URL must take the form: `https://github.com/{user}/{repo}`, e.g., // `https://github.com/astral-sh/uv`. let Some(mut segments) = url.path_segments() else { debug!("GitHub URL is missing path segments: {url}"); return None; }; let Some(owner) = segments.next() else { debug!("GitHub URL is missing owner: {url}"); return None; }; let Some(repo) = segments.next() else { debug!("GitHub URL is missing repo: {url}"); return None; }; if segments.next().is_some() { debug!("GitHub URL has too many path segments: {url}"); return None; } // Trim off the `.git` from the repository, if present. let repo = repo.strip_suffix(".git").unwrap_or(repo); Some(Self { owner, repo }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse_valid_url() { let url = Url::parse("https://github.com/astral-sh/uv").unwrap(); let repo = GitHubRepository::parse(&url).unwrap(); assert_eq!(repo.owner, "astral-sh"); assert_eq!(repo.repo, "uv"); } #[test] fn test_parse_with_git_suffix() { let url = Url::parse("https://github.com/astral-sh/uv.git").unwrap(); let repo = GitHubRepository::parse(&url).unwrap(); assert_eq!(repo.owner, "astral-sh"); assert_eq!(repo.repo, "uv"); } #[test] fn test_parse_invalid_host() { let url = Url::parse("https://gitlab.com/astral-sh/uv").unwrap(); assert!(GitHubRepository::parse(&url).is_none()); } #[test] fn test_parse_invalid_path() { let url = Url::parse("https://github.com/astral-sh").unwrap(); assert!(GitHubRepository::parse(&url).is_none()); let url = Url::parse("https://github.com/astral-sh/uv/extra").unwrap(); assert!(GitHubRepository::parse(&url).is_none()); } }
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
false
astral-sh/uv
https://github.com/astral-sh/uv/blob/2318e48e819080f37a002551035c2b1880a81a70/crates/uv-cache/src/lib.rs
crates/uv-cache/src/lib.rs
use std::fmt::{Display, Formatter}; use std::io; use std::io::Write; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::str::FromStr; use std::sync::Arc; use rustc_hash::FxHashMap; use tracing::{debug, trace, warn}; use uv_cache_info::Timestamp; use uv_fs::{LockedFile, LockedFileError, LockedFileMode, Simplified, cachedir, directories}; use uv_normalize::PackageName; use uv_pypi_types::ResolutionMetadata; pub use crate::by_timestamp::CachedByTimestamp; #[cfg(feature = "clap")] pub use crate::cli::CacheArgs; use crate::removal::Remover; pub use crate::removal::{Removal, rm_rf}; pub use crate::wheel::WheelCache; use crate::wheel::WheelCacheKind; pub use archive::ArchiveId; mod archive; mod by_timestamp; #[cfg(feature = "clap")] mod cli; mod removal; mod wheel; /// The version of the archive bucket. /// /// Must be kept in-sync with the version in [`CacheBucket::to_str`]. pub const ARCHIVE_VERSION: u8 = 0; /// Error locking a cache entry or shard #[derive(Debug, thiserror::Error)] pub enum Error { #[error(transparent)] Io(#[from] io::Error), #[error("Could not make the path absolute")] Absolute(#[source] io::Error), #[error("Could not acquire lock")] Acquire(#[from] LockedFileError), } /// A [`CacheEntry`] which may or may not exist yet. #[derive(Debug, Clone)] pub struct CacheEntry(PathBuf); impl CacheEntry { /// Create a new [`CacheEntry`] from a directory and a file name. pub fn new(dir: impl Into<PathBuf>, file: impl AsRef<Path>) -> Self { Self(dir.into().join(file)) } /// Create a new [`CacheEntry`] from a path. pub fn from_path(path: impl Into<PathBuf>) -> Self { Self(path.into()) } /// Return the cache entry's parent directory. pub fn shard(&self) -> CacheShard { CacheShard(self.dir().to_path_buf()) } /// Convert the [`CacheEntry`] into a [`PathBuf`]. #[inline] pub fn into_path_buf(self) -> PathBuf { self.0 } /// Return the path to the [`CacheEntry`]. #[inline] pub fn path(&self) -> &Path { &self.0 } /// Return the cache entry's parent directory. #[inline] pub fn dir(&self) -> &Path { self.0.parent().expect("Cache entry has no parent") } /// Create a new [`CacheEntry`] with the given file name. #[must_use] pub fn with_file(&self, file: impl AsRef<Path>) -> Self { Self(self.dir().join(file)) } /// Acquire the [`CacheEntry`] as an exclusive lock. pub async fn lock(&self) -> Result<LockedFile, Error> { fs_err::create_dir_all(self.dir())?; Ok(LockedFile::acquire( self.path(), LockedFileMode::Exclusive, self.path().display(), ) .await?) } } impl AsRef<Path> for CacheEntry { fn as_ref(&self) -> &Path { &self.0 } } /// A subdirectory within the cache. #[derive(Debug, Clone)] pub struct CacheShard(PathBuf); impl CacheShard { /// Return a [`CacheEntry`] within this shard. pub fn entry(&self, file: impl AsRef<Path>) -> CacheEntry { CacheEntry::new(&self.0, file) } /// Return a [`CacheShard`] within this shard. #[must_use] pub fn shard(&self, dir: impl AsRef<Path>) -> Self { Self(self.0.join(dir.as_ref())) } /// Acquire the cache entry as an exclusive lock. pub async fn lock(&self) -> Result<LockedFile, Error> { fs_err::create_dir_all(self.as_ref())?; Ok(LockedFile::acquire( self.join(".lock"), LockedFileMode::Exclusive, self.display(), ) .await?) } /// Return the [`CacheShard`] as a [`PathBuf`]. pub fn into_path_buf(self) -> PathBuf { self.0 } } impl AsRef<Path> for CacheShard { fn as_ref(&self) -> &Path { &self.0 } } impl Deref for CacheShard { type Target = Path; fn deref(&self) -> &Self::Target { &self.0 } } /// The main cache abstraction. /// /// While the cache is active, it holds a read (shared) lock that prevents cache cleaning #[derive(Debug, Clone)] pub struct Cache { /// The cache directory. root: PathBuf, /// The refresh strategy to use when reading from the cache. refresh: Refresh, /// A temporary cache directory, if the user requested `--no-cache`. /// /// Included to ensure that the temporary directory exists for the length of the operation, but /// is dropped at the end as appropriate. temp_dir: Option<Arc<tempfile::TempDir>>, /// Ensure that `uv cache` operations don't remove items from the cache that are used by another /// uv process. lock_file: Option<Arc<LockedFile>>, } impl Cache { /// A persistent cache directory at `root`. pub fn from_path(root: impl Into<PathBuf>) -> Self { Self { root: root.into(), refresh: Refresh::None(Timestamp::now()), temp_dir: None, lock_file: None, } } /// Create a temporary cache directory. pub fn temp() -> Result<Self, io::Error> { let temp_dir = tempfile::tempdir()?; Ok(Self { root: temp_dir.path().to_path_buf(), refresh: Refresh::None(Timestamp::now()), temp_dir: Some(Arc::new(temp_dir)), lock_file: None, }) } /// Set the [`Refresh`] policy for the cache. #[must_use] pub fn with_refresh(self, refresh: Refresh) -> Self { Self { refresh, ..self } } /// Acquire a lock that allows removing entries from the cache. pub async fn with_exclusive_lock(self) -> Result<Self, LockedFileError> { let Self { root, refresh, temp_dir, lock_file, } = self; // Release the existing lock, avoid deadlocks from a cloned cache. if let Some(lock_file) = lock_file { drop( Arc::try_unwrap(lock_file).expect( "cloning the cache before acquiring an exclusive lock causes a deadlock", ), ); } let lock_file = LockedFile::acquire( root.join(".lock"), LockedFileMode::Exclusive, root.simplified_display(), ) .await?; Ok(Self { root, refresh, temp_dir, lock_file: Some(Arc::new(lock_file)), }) } /// Acquire a lock that allows removing entries from the cache, if available. /// /// If the lock is not immediately available, returns [`Err`] with self. pub fn with_exclusive_lock_no_wait(self) -> Result<Self, Self> { let Self { root, refresh, temp_dir, lock_file, } = self; match LockedFile::acquire_no_wait( root.join(".lock"), LockedFileMode::Exclusive, root.simplified_display(), ) { Some(lock_file) => Ok(Self { root, refresh, temp_dir, lock_file: Some(Arc::new(lock_file)), }), None => Err(Self { root, refresh, temp_dir, lock_file, }), } } /// Return the root of the cache. pub fn root(&self) -> &Path { &self.root } /// Return the [`Refresh`] policy for the cache. pub fn refresh(&self) -> &Refresh { &self.refresh } /// The folder for a specific cache bucket pub fn bucket(&self, cache_bucket: CacheBucket) -> PathBuf { self.root.join(cache_bucket.to_str()) } /// Compute an entry in the cache. pub fn shard(&self, cache_bucket: CacheBucket, dir: impl AsRef<Path>) -> CacheShard { CacheShard(self.bucket(cache_bucket).join(dir.as_ref())) } /// Compute an entry in the cache. pub fn entry( &self, cache_bucket: CacheBucket, dir: impl AsRef<Path>, file: impl AsRef<Path>, ) -> CacheEntry { CacheEntry::new(self.bucket(cache_bucket).join(dir), file) } /// Return the path to an archive in the cache. pub fn archive(&self, id: &ArchiveId) -> PathBuf { self.bucket(CacheBucket::Archive).join(id) } /// Create a temporary directory to be used as a Python virtual environment. pub fn venv_dir(&self) -> io::Result<tempfile::TempDir> { fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?; tempfile::tempdir_in(self.bucket(CacheBucket::Builds)) } /// Create a temporary directory to be used for executing PEP 517 source distribution builds. pub fn build_dir(&self) -> io::Result<tempfile::TempDir> { fs_err::create_dir_all(self.bucket(CacheBucket::Builds))?; tempfile::tempdir_in(self.bucket(CacheBucket::Builds)) } /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy. pub fn must_revalidate_package(&self, package: &PackageName) -> bool { match &self.refresh { Refresh::None(_) => false, Refresh::All(_) => true, Refresh::Packages(packages, _, _) => packages.contains(package), } } /// Returns `true` if a cache entry must be revalidated given the [`Refresh`] policy. pub fn must_revalidate_path(&self, path: &Path) -> bool { match &self.refresh { Refresh::None(_) => false, Refresh::All(_) => true, Refresh::Packages(_, paths, _) => paths .iter() .any(|target| same_file::is_same_file(path, target).unwrap_or(false)), } } /// Returns the [`Freshness`] for a cache entry, validating it against the [`Refresh`] policy. /// /// A cache entry is considered fresh if it was created after the cache itself was /// initialized, or if the [`Refresh`] policy does not require revalidation. pub fn freshness( &self, entry: &CacheEntry, package: Option<&PackageName>, path: Option<&Path>, ) -> io::Result<Freshness> { // Grab the cutoff timestamp, if it's relevant. let timestamp = match &self.refresh { Refresh::None(_) => return Ok(Freshness::Fresh), Refresh::All(timestamp) => timestamp, Refresh::Packages(packages, paths, timestamp) => { if package.is_none_or(|package| packages.contains(package)) || path.is_some_and(|path| { paths .iter() .any(|target| same_file::is_same_file(path, target).unwrap_or(false)) }) { timestamp } else { return Ok(Freshness::Fresh); } } }; match fs_err::metadata(entry.path()) { Ok(metadata) => { if Timestamp::from_metadata(&metadata) >= *timestamp { Ok(Freshness::Fresh) } else { Ok(Freshness::Stale) } } Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(Freshness::Missing), Err(err) => Err(err), } } /// Persist a temporary directory to the artifact store, returning its unique ID. pub async fn persist( &self, temp_dir: impl AsRef<Path>, path: impl AsRef<Path>, ) -> io::Result<ArchiveId> { // Create a unique ID for the artifact. // TODO(charlie): Support content-addressed persistence via SHAs. let id = ArchiveId::new(); // Move the temporary directory into the directory store. let archive_entry = self.entry(CacheBucket::Archive, "", &id); fs_err::create_dir_all(archive_entry.dir())?; uv_fs::rename_with_retry(temp_dir.as_ref(), archive_entry.path()).await?; // Create a symlink to the directory store. fs_err::create_dir_all(path.as_ref().parent().expect("Cache entry to have parent"))?; self.create_link(&id, path.as_ref())?; Ok(id) } /// Returns `true` if the [`Cache`] is temporary. pub fn is_temporary(&self) -> bool { self.temp_dir.is_some() } /// Populate the cache scaffold. fn create_base_files(root: &PathBuf) -> io::Result<()> { // Create the cache directory, if it doesn't exist. fs_err::create_dir_all(root)?; // Add the CACHEDIR.TAG. cachedir::ensure_tag(root)?; // Add the .gitignore. match fs_err::OpenOptions::new() .write(true) .create_new(true) .open(root.join(".gitignore")) { Ok(mut file) => file.write_all(b"*")?, Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (), Err(err) => return Err(err), } // Add an empty .gitignore to the build bucket, to ensure that the cache's own .gitignore // doesn't interfere with source distribution builds. Build backends (like hatchling) will // traverse upwards to look for .gitignore files. fs_err::create_dir_all(root.join(CacheBucket::SourceDistributions.to_str()))?; match fs_err::OpenOptions::new() .write(true) .create_new(true) .open( root.join(CacheBucket::SourceDistributions.to_str()) .join(".gitignore"), ) { Ok(_) => {} Err(err) if err.kind() == io::ErrorKind::AlreadyExists => (), Err(err) => return Err(err), } // Add a phony .git, if it doesn't exist, to ensure that the cache isn't considered to be // part of a Git repository. (Some packages will include Git metadata (like a hash) in the // built version if they're in a Git repository, but the cache should be viewed as an // isolated store.). // We have to put this below the gitignore. Otherwise, if the build backend uses the rust // ignore crate it will walk up to the top level .gitignore and ignore its python source // files. fs_err::OpenOptions::new().create(true).write(true).open( root.join(CacheBucket::SourceDistributions.to_str()) .join(".git"), )?; Ok(()) } /// Initialize the [`Cache`]. pub async fn init(self) -> Result<Self, Error> { let root = &self.root; Self::create_base_files(root)?; // Block cache removal operations from interfering. let lock_file = match LockedFile::acquire( root.join(".lock"), LockedFileMode::Shared, root.simplified_display(), ) .await { Ok(lock_file) => Some(Arc::new(lock_file)), Err(err) if err .as_io_error() .is_some_and(|err| err.kind() == io::ErrorKind::Unsupported) => { warn!( "Shared locking is not supported by the current platform or filesystem, \ reduced parallel process safety with `uv cache clean` and `uv cache prune`." ); None } Err(err) => return Err(err.into()), }; Ok(Self { root: std::path::absolute(root).map_err(Error::Absolute)?, lock_file, ..self }) } /// Initialize the [`Cache`], assuming that there are no other uv processes running. pub fn init_no_wait(self) -> Result<Option<Self>, Error> { let root = &self.root; Self::create_base_files(root)?; // Block cache removal operations from interfering. let Some(lock_file) = LockedFile::acquire_no_wait( root.join(".lock"), LockedFileMode::Shared, root.simplified_display(), ) else { return Ok(None); }; Ok(Some(Self { root: std::path::absolute(root).map_err(Error::Absolute)?, lock_file: Some(Arc::new(lock_file)), ..self })) } /// Clear the cache, removing all entries. pub fn clear(self, reporter: Box<dyn CleanReporter>) -> Result<Removal, io::Error> { // Remove everything but `.lock`, Windows does not allow removal of a locked file let mut removal = Remover::new(reporter).rm_rf(&self.root, true)?; let Self { root, lock_file, .. } = self; // Remove the `.lock` file, unlocking it first if let Some(lock) = lock_file { drop(lock); fs_err::remove_file(root.join(".lock"))?; } removal.num_files += 1; // Remove the root directory match fs_err::remove_dir(root) { Ok(()) => { removal.num_dirs += 1; } // On Windows, when `--force` is used, the `.lock` file can exist and be unremovable, // so we make this non-fatal Err(err) if err.kind() == io::ErrorKind::DirectoryNotEmpty => { trace!("Failed to remove root cache directory: not empty"); } Err(err) => return Err(err), } Ok(removal) } /// Remove a package from the cache. /// /// Returns the number of entries removed from the cache. pub fn remove(&self, name: &PackageName) -> io::Result<Removal> { // Collect the set of referenced archives. let references = self.find_archive_references()?; // Remove any entries for the package from the cache. let mut summary = Removal::default(); for bucket in CacheBucket::iter() { summary += bucket.remove(self, name)?; } // Remove any archives that are no longer referenced. for (target, references) in references { if references.iter().all(|path| !path.exists()) { debug!("Removing dangling cache entry: {}", target.display()); summary += rm_rf(target)?; } } Ok(summary) } /// Run the garbage collector on the cache, removing any dangling entries. pub fn prune(&self, ci: bool) -> Result<Removal, io::Error> { let mut summary = Removal::default(); // First, remove any top-level directories that are unused. These typically represent // outdated cache buckets (e.g., `wheels-v0`, when latest is `wheels-v1`). for entry in fs_err::read_dir(&self.root)? { let entry = entry?; let metadata = entry.metadata()?; if entry.file_name() == "CACHEDIR.TAG" || entry.file_name() == ".gitignore" || entry.file_name() == ".git" || entry.file_name() == ".lock" { continue; } if metadata.is_dir() { // If the directory is not a cache bucket, remove it. if CacheBucket::iter().all(|bucket| entry.file_name() != bucket.to_str()) { let path = entry.path(); debug!("Removing dangling cache bucket: {}", path.display()); summary += rm_rf(path)?; } } else { // If the file is not a marker file, remove it. let path = entry.path(); debug!("Removing dangling cache bucket: {}", path.display()); summary += rm_rf(path)?; } } // Second, remove any cached environments. These are never referenced by symlinks, so we can // remove them directly. match fs_err::read_dir(self.bucket(CacheBucket::Environments)) { Ok(entries) => { for entry in entries { let entry = entry?; let path = fs_err::canonicalize(entry.path())?; debug!("Removing dangling cache environment: {}", path.display()); summary += rm_rf(path)?; } } Err(err) if err.kind() == io::ErrorKind::NotFound => (), Err(err) => return Err(err), } // Third, if enabled, remove all unzipped wheels, leaving only the wheel archives. if ci { // Remove the entire pre-built wheel cache, since every entry is an unzipped wheel. match fs_err::read_dir(self.bucket(CacheBucket::Wheels)) { Ok(entries) => { for entry in entries { let entry = entry?; let path = fs_err::canonicalize(entry.path())?; if path.is_dir() { debug!("Removing unzipped wheel entry: {}", path.display()); summary += rm_rf(path)?; } } } Err(err) if err.kind() == io::ErrorKind::NotFound => (), Err(err) => return Err(err), } for entry in walkdir::WalkDir::new(self.bucket(CacheBucket::SourceDistributions)) { let entry = entry?; // If the directory contains a `metadata.msgpack`, then it's a built wheel revision. if !entry.file_type().is_dir() { continue; } if !entry.path().join("metadata.msgpack").exists() { continue; } // Remove everything except the built wheel archive and the metadata. for entry in fs_err::read_dir(entry.path())? { let entry = entry?; let path = entry.path(); // Retain the resolved metadata (`metadata.msgpack`). if path .file_name() .is_some_and(|file_name| file_name == "metadata.msgpack") { continue; } // Retain any built wheel archives. if path .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("whl")) { continue; } debug!("Removing unzipped built wheel entry: {}", path.display()); summary += rm_rf(path)?; } } } // Fourth, remove any unused archives (by searching for archives that are not symlinked). let references = self.find_archive_references()?; match fs_err::read_dir(self.bucket(CacheBucket::Archive)) { Ok(entries) => { for entry in entries { let entry = entry?; let path = fs_err::canonicalize(entry.path())?; if !references.contains_key(&path) { debug!("Removing dangling cache archive: {}", path.display()); summary += rm_rf(path)?; } } } Err(err) if err.kind() == io::ErrorKind::NotFound => (), Err(err) => return Err(err), } Ok(summary) } /// Find all references to entries in the archive bucket. /// /// Archive entries are often referenced by symlinks in other cache buckets. This method /// searches for all such references. /// /// Returns a map from archive path to paths that reference it. fn find_archive_references(&self) -> Result<FxHashMap<PathBuf, Vec<PathBuf>>, io::Error> { let mut references = FxHashMap::<PathBuf, Vec<PathBuf>>::default(); for bucket in [CacheBucket::SourceDistributions, CacheBucket::Wheels] { let bucket_path = self.bucket(bucket); if bucket_path.is_dir() { let walker = walkdir::WalkDir::new(&bucket_path).into_iter(); for entry in walker.filter_entry(|entry| { !( // As an optimization, ignore any `.lock`, `.whl`, `.msgpack`, `.rev`, or // `.http` files, along with the `src` directory, which represents the // unpacked source distribution. entry.file_name() == "src" || entry.file_name() == ".lock" || entry.file_name() == ".gitignore" || entry.path().extension().is_some_and(|ext| { ext.eq_ignore_ascii_case("lock") || ext.eq_ignore_ascii_case("whl") || ext.eq_ignore_ascii_case("http") || ext.eq_ignore_ascii_case("rev") || ext.eq_ignore_ascii_case("msgpack") }) ) }) { let entry = entry?; // On Unix, archive references use symlinks. if cfg!(unix) { if !entry.file_type().is_symlink() { continue; } } // On Windows, archive references are files containing structured data. if cfg!(windows) { if !entry.file_type().is_file() { continue; } } if let Ok(target) = self.resolve_link(entry.path()) { references .entry(target) .or_default() .push(entry.path().to_path_buf()); } } } } Ok(references) } /// Create a link to a directory in the archive bucket. /// /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and /// version. On Unix, we create a symlink to the target directory. #[cfg(windows)] pub fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> { // Serialize the link. let link = Link::new(id.clone()); let contents = link.to_string(); // First, attempt to create a file at the location, but fail if it already exists. match fs_err::OpenOptions::new() .write(true) .create_new(true) .open(dst.as_ref()) { Ok(mut file) => { // Write the target path to the file. file.write_all(contents.as_bytes())?; Ok(()) } Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { // Write to a temporary file, then move it into place. let temp_dir = tempfile::tempdir_in(dst.as_ref().parent().unwrap())?; let temp_file = temp_dir.path().join("link"); fs_err::write(&temp_file, contents.as_bytes())?; // Move the symlink into the target location. fs_err::rename(&temp_file, dst.as_ref())?; Ok(()) } Err(err) => Err(err), } } /// Resolve an archive link, returning the fully-resolved path. /// /// Returns an error if the link target does not exist. #[cfg(windows)] pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> { // Deserialize the link. let contents = fs_err::read_to_string(path.as_ref())?; let link = Link::from_str(&contents)?; // Ignore stale links. if link.version != ARCHIVE_VERSION { return Err(io::Error::new( io::ErrorKind::NotFound, "The link target does not exist.", )); } // Reconstruct the path. let path = self.archive(&link.id); path.canonicalize() } /// Create a link to a directory in the archive bucket. /// /// On Windows, we write structured data ([`Link`]) to a file containing the archive ID and /// version. On Unix, we create a symlink to the target directory. #[cfg(unix)] pub fn create_link(&self, id: &ArchiveId, dst: impl AsRef<Path>) -> io::Result<()> { // Construct the link target. let src = self.archive(id); let dst = dst.as_ref(); // Attempt to create the symlink directly. match fs_err::os::unix::fs::symlink(&src, dst) { Ok(()) => Ok(()), Err(err) if err.kind() == io::ErrorKind::AlreadyExists => { // Create a symlink, using a temporary file to ensure atomicity. let temp_dir = tempfile::tempdir_in(dst.parent().unwrap())?; let temp_file = temp_dir.path().join("link"); fs_err::os::unix::fs::symlink(&src, &temp_file)?; // Move the symlink into the target location. fs_err::rename(&temp_file, dst)?; Ok(()) } Err(err) => Err(err), } } /// Resolve an archive link, returning the fully-resolved path. /// /// Returns an error if the link target does not exist. #[cfg(unix)] pub fn resolve_link(&self, path: impl AsRef<Path>) -> io::Result<PathBuf> { path.as_ref().canonicalize() } } /// An archive (unzipped wheel) that exists in the local cache. #[derive(Debug, Clone)] #[allow(unused)] struct Link { /// The unique ID of the entry in the archive bucket. id: ArchiveId, /// The version of the archive bucket. version: u8, } #[allow(unused)] impl Link { /// Create a new [`Archive`] with the given ID and hashes. fn new(id: ArchiveId) -> Self { Self { id, version: ARCHIVE_VERSION, } } } impl Display for Link { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "archive-v{}/{}", self.version, self.id) } } impl FromStr for Link { type Err = io::Error; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut parts = s.splitn(2, '/'); let version = parts .next() .filter(|s| !s.is_empty()) .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version"))?; let id = parts .next() .filter(|s| !s.is_empty()) .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing ID"))?; // Parse the archive version from `archive-v{version}/{id}`. let version = version .strip_prefix("archive-v") .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing version prefix"))?; let version = u8::from_str(version).map_err(|err| { io::Error::new( io::ErrorKind::InvalidData, format!("failed to parse version: {err}"), ) })?; // Parse the ID from `archive-v{version}/{id}`. let id = ArchiveId::from_str(id).map_err(|err| { io::Error::new( io::ErrorKind::InvalidData, format!("failed to parse ID: {err}"), ) })?; Ok(Self { id, version }) } } pub trait CleanReporter: Send + Sync { /// Called after one file or directory is removed. fn on_clean(&self); /// Called after all files and directories are removed. fn on_complete(&self); } /// The different kinds of data in the cache are stored in different bucket, which in our case /// are subdirectories of the cache root. #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)] pub enum CacheBucket { /// Wheels (excluding built wheels), alongside their metadata and cache policy. /// /// There are three kinds from cache entries: Wheel metadata and policy as `MsgPack` files, the /// wheels themselves, and the unzipped wheel archives. If a wheel file is over an in-memory /// size threshold, we first download the zip file into the cache, then unzip it into a /// directory with the same name (exclusive of the `.whl` extension). /// /// Cache structure: /// * `wheel-metadata-v0/pypi/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}` /// * `wheel-metadata-v0/<digest(index-url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}` /// * `wheel-metadata-v0/url/<digest(url)>/foo/{foo-1.0.0-py3-none-any.msgpack, foo-1.0.0-py3-none-any.whl}` ///
rust
Apache-2.0
2318e48e819080f37a002551035c2b1880a81a70
2026-01-04T15:31:58.679374Z
true